I have a class like so:
Railsapp/lib/five9_providers/record_provider.rb:
class Five9Providers::RecordProvider < Five9Providers::BaseProvider
def add_record_to_list
variable = 'test'
end
end
Then, in a controller I have this:
Railsapp/app/controllers/five9_controller.rb:
class Five9Controller < ApplicationController
def import
record_provider = Five9Providers::RecordProvider.new()
record_provider.add_record_to_list
puts Five9Providers::RecordProvider::variable
end
end
However, calling my controller method import just returns:
NoMethodError (undefined method 'variable' for Five9Providers::RecordProvider:Class)
How can I access variable from the recover_provider.rb class in my five9_controller.rb class?
EDIT:
Even when using ##variable in both my record_provider and my five9_controller, I still can't access that variable. I am calling it like so: puts ##variable.
As written, you cannot. variable is local to the instance method and can't be accessed by any Ruby expression from outside the method.
On a related point, the term "class variable" is typically used to refer to variables of the form ##variable.
Update: In response to your "Edit" statement, if you change variable to ##variable in your class, then there are techniques available to access that variable from outside the class, but a naked reference to ##variable isn't one of them. Carefully read the answers to the question you cited in your comment for more information.
Best way is to set and get the value using methods. Below is a sample code
class Planet
##planets_count = 0
def initialize(name)
#name = name
##planets_count += 1
end
def self.planets_count
##planets_count
end
def self.add_planet
##planets_count += 1
end
def add_planet_from_obj
##planets_count += 1
end
end
Planet.new("uranus")
Plant.add_planet
obj = Planet.new("earth")
obj.add_planet_from_obj
Related
i am trying to understand the .self pointer , class and instance variable and their uses. I found many useful links but nothing seems to get into my head. like this medium post ::
medium.com - #/## vs. self in Ruby
here is the code I tried (filename = hello.rb)
class Person
def instance_variable_get
#instance_var = "instance variable"
end
def class_var
##class_var = "class variable"
end
def sayhi
puts "this is a ins #{#instance_var}"
puts "this is a cls #{class_var}" #note i removed the # sign from this.
end
def self.sayhi
puts "this is a ins from class #{#instance_var}"
puts "this is a cls from class #{#class_var}"
end
end
bob = Person.new
bob.sayhi
Person.sayhi
and by executing this i got
cd#CD:~/Desktop$ ruby hello.rb
this is a ins
this is a cls class variable
this is a ins from class
this is a cls from class
how does this all thing work? what am I doing wrong?
the result I am expecting from this is
this is a ins instance variable
this is a cls class variable
this is a ins from class instance variable
this is a cls from class class variable
That code doesn't actually work since you're not calling any of methods that set the variables. Its kind of a mess and I think I can explain this better with more idiomatic examples.
In Ruby instance variables are just lexically scoped local variables that are scoped to an object instance. They are always "private" but you can provide accessor methods to provide access from the outside (and the insider also):
class Person
def initialize(name)
#name = name
end
def name=(value)
#name = name
end
def name
#name
end
def hello
"Hello, my name is #{name}"
end
end
jane = Person.new("Jane")
puts jane.hello # "Hello, my name is Jane"
jane.name = "Jaayne"
puts jane.hello # "Hello, my name is Jaayne"
Inside the hello method self is the instance of Person that you are calling the the method on.
We can simply call name instead of self.name since its the implicit reciever. We could also write "Hello, my name is #{#name}" and it would give the exact same result since the getter method is just returning the instance variable.
Ending setter methods with = is just a convention that lets you use the method with the = operator. You can actually set instance variables from any method.
class Person
attr_accessor :name
def initialize(name)
#name = name
end
def backwardize!
#name = #name.reverse
end
end
Class variables on the other hand are a whole different cup of tea. The scope of a class variable is a class - but the are also shared with any subclasses. This is an example of why they are best avoided:
class Vehicle
def self.number_of_wheels=(value)
##number_of_wheels = value
end
def self.number_of_wheels
##number_of_wheels
end
end
class Car < Vehicle
self.number_of_wheels = 4
end
puts Car.number_of_wheels # 4 - good
class Bike < Vehicle
self.number_of_wheels = 2
end
puts Bike.number_of_wheels # 2 - good
puts Car.number_of_wheels # 2 - WAAAT?!
Setting class variables from an instance method which you have done in your example is not commonly done. If you have an instance method that changes the behavior of all other instances of the same class it will often lead to a large amount of swearing.
Instead of class variables use class instance variables:
class Vehicle
def self.number_of_wheels=(value)
#number_of_wheels = value
end
def self.number_of_wheels
#number_of_wheels
end
end
class Car < Vehicle
# you need to explicitly use self when calling setter methods
# otherwise Ruby will think you're setting a local variable.
self.number_of_wheels = 4
end
puts Car.number_of_wheels # 4 - good
class Bike < Vehicle
self.number_of_wheels = 2
end
puts Bike.number_of_wheels # 2 - good
puts Car.number_of_wheels # 4 - good
This can be a mind boggling concept but just try to remember that in Ruby classes are just instances of Class.
You also seem to be somewhat confused about what instance_variable_get whould be used for. Its used to violate encapsulation and get the instance variables of an object from the outside.
class Foo
def initialize
#bar = "I'm Foo's secret"
end
end
puts Foo.new.instance_variable_get(:#bar) # "I'm Foo's secret"
Violating encapsulation should not normally be how you structure your code but it can be very useful in some circumstances. It is not called when accessing instance variables from within an object. I don't think I have ever seen anyone redefine the method - just because you can doesn't mean you should.
Because the functions which assign values to variables are not called at all. Do something like this. This ensures the variable values are set when you run a method from object or class:
class Person
#instance_var = "instance variable"
##class_var = "class variable"
def sayhi
puts "this is a ins #{#instance_var}"
puts "this is a cls #{class_var}" #note i removed the # sign from this.
end
def self.sayhi
puts "this is a ins from class #{#instance_var}"
puts "this is a cls from class #{#class_var}"
end
end
bob = Person.new
bob.sayhi
Person.sayhi
Additionally refer to this: Ruby class instance variable vs. class variable
Is there a way to implement monkey patching while an object is being instantiated?
When I call:
a = Foo.new
Prior to the instance being instantiated, I would like to extend the Foo class based on information which I will read from a data store. As such, each time I call Foo.new, the extension(s) that will be added to that instance of the class would change dynamically.
tl;dr: Adding methods to an instance is possible.
Answer: Adding methods to an instance is not possible. Instances in Ruby don't have methods. But each instance can have a singleton class, where one can add methods, which will then be only available on the single instance that this singleton class is made for.
class Foo
end
foo = Foo.new
def foo.bark
puts "Woof"
end
foo.bark
class << foo
def chew
puts "Crunch"
end
end
foo.chew
foo.define_singleton_method(:mark) do
puts "Widdle"
end
foo.mark
are just some of the ways to define a singleton method for an object.
module Happy
def cheer
puts "Wag"
end
end
foo.extend(Happy)
foo.cheer
This takes another approach, it will insert the module between the singleton class and the real class in the inheritance chain. This way, too, the module is available to the instance, but not on the whole class.
Sure you can!
method_name_only_known_at_runtime = 'hello'
string_only_known_at_runtime = 'Hello World!'
test = Object.new
test.define_singleton_method(method_name_only_known_at_runtime) do
puts(string_only_known_at_runtime)
end
test.hello
#> Hello World!
Prior to the instance being instantiated, I would like to extend
Given a class Foo which does something within its initialize method:
class Foo
attr_accessor :name
def initialize(name)
self.name = name
end
end
And a module FooExtension which wants to alter that behavior:
module FooExtension
def name=(value)
#name = value.reverse.upcase
end
end
You could patch it via prepend:
module FooPatcher
def initialize(*)
extend(FooExtension) if $do_extend # replace with actual logic
super
end
end
Foo.prepend(FooPatcher)
Or you could extend even before calling initialize by providing your own new class method:
class Foo
def self.new(*args)
obj = allocate
obj.extend(FooExtension) if $do_extend # replace with actual logic
obj.send(:initialize, *args)
obj
end
end
Both variants produce the same result:
$do_extend = false
Foo.new('hello')
#=> #<Foo:0x00007ff66582b640 #name="hello">
$do_extend = true
Foo.new('hello')
#=> #<Foo:0x00007ff66582b280 #name="OLLEH">
I have a controller that counts the number of times the user has been to a page. I'm trying to extract that count to a getter and setter which set a session variable. Getting works, but setting doesn't. This is the controller:
class StoreController < ApplicationController
def index
#products = Product.order(:title)
v = store_visits + 1
store_visits = v # tests fail if I do it like this
# store_visits += 1 # Undefined method '+' for NilClass if i do it like this
#visits = store_visits
end
def store_visits
if session[:store_counter].nil?
session[:store_counter] = 0
end
session[:store_counter]
end
def store_visits=(value)
session[:store_counter] = value
end
end
And here's a failing test:
require 'test_helper'
class StoreControllerTest < ActionController::TestCase
test "should count store visits" do
get :index
assert session[:store_counter] == 1
get :index
assert session[:store_counter] == 2
end
end
Why isn't it setting, and why is store_visits returning nil if I use += ? Any help is appreciated.
Note: Originally I extracted the methods to a concern, but I've edited this to remove the concern, because the problem isn't with the concern, it's with the setter and/or getter.
Update: After adding logging statments, it's obvious that the inside of the store_visits=() method is never reached (but somehow an error is not thrown). However, if I rename it to assign_store_visits(), it does get called, and does update the session variable. So I'm guessing this is either a bug where setter methods don't work in controllers (this is Rails 4.0.0) or they're intentionally blocked (in which case, an exception would be nice).
try switch to include ActiveSupport::Concern
this will provide instance methods instead class methods
You need to wrap the methods inside of your concern inside of an included block like:
module Visits
extend ActiveSupport::Concern
included do
#private
def store_visits
if session[:store_counter].nil?
session[:store_counter] = 0
end
session[:store_counter]
end
def store_visits=(value)
session[:store_counter] = value
end
# private
end
end
end
Doing that will make those methods available as instance methods inside of your controller.
I am trying to learn Ruby by reading tutorials on Class Variables.
The code creates a "Worker" object, a class variable is created to keep track of which instance of Worker was created by the user last.
I have copied the code from the author but I get the error:
undefined method `latest' for Worker:Class (NoMethodError)
The code I have found is:
class Worker
attr_writer :number_of_jobs
def initialize(name, job)
#name = name
#job = job
##latest = #name
##job = #job
puts "Lets get started"
end
def new_job(job)
#job = job
puts "I moved to #{job}!"
self.fetch_info
end
def name_update(name_new)
#name = name_new
puts "My new name is #{name_new}."
self.fetch_info
end
def fetch_info
puts "I'm #{#name} in #{#location}."
end
def job_score
return "#{#number_of_jobs * 10}Fg"
end
protected
def are_you_worker?(guest_name)
puts "Yes #{guest_name}, I am a worker!"
return true
end
private
def text_a_message(message)
puts message
end
public
def tell_friend(where)
text_a_message("I just applied to #{where}")
end
end
#running the code
Worker1 = Worker.new("Steve", "Support")
Worker2 = Worker.new("Alan", "PA")
puts Worker.latest
Can anybody see why?
The Class variables are private inside this class which is causing a problem. Therefore accessing the Worker.latest variable will cause an error as it isn't visible from instances outside of the class (but it is created and set).
Additionally, attributes are part of the object not the class so you shouldn't have an attribute for this class . In native Ruby the class variables are not accessible from outside EXCEPT through a class method (there are extensions in Rails for them tho).
Hope that helps
IMHO, this is one of the more frustrating things about Ruby's class system. The privacy of class variables is true even for subclasses. In any case, the immediate solution to your problem is to add a class method like so:
class Worker
def self.latest
##latest
end
end
How do you define a method for an attribute of an instance in Ruby?
Let's say we've got a class called HtmlSnippet, which extends ActiveRecord::Base of Rails and has got an attribute content. And, I want to define a method replace_url_to_anchor_tag! for it and get it called in the following way;
html_snippet = HtmlSnippet.find(1)
html_snippet.content = "Link to http://stackoverflow.com"
html_snippet.content.replace_url_to_anchor_tag!
# => "Link to <a href='http://stackoverflow.com'>http://stackoverflow.com</a>"
# app/models/html_snippet.rb
class HtmlSnippet < ActiveRecord::Base
# I expected this bit to do what I want but not
class << #content
def replace_url_to_anchor_tag!
matching = self.match(/(https?:\/\/[\S]+)/)
"<a href='#{matching[0]}'/>#{matching[0]}</a>"
end
end
end
As content is an instance of String class, redefine String class is one option. But I don't feel like to going for it because it overwrites behaviour of all instances of String;
class HtmlSnippet < ActiveRecord::Base
class String
def replace_url_to_anchor_tag!
...
end
end
end
Any suggestions please?
The reason why your code is not working is simple - you are working with #content which is nil in the context of execution (the self is the class, not the instance). So you are basically modifying eigenclass of nil.
So you need to extend the instance of #content when it's set. There are few ways, there is one:
class HtmlSnippet < ActiveRecord::Base
# getter is overrided to extend behaviour of freshly loaded values
def content
value = read_attribute(:content)
decorate_it(value) unless value.respond_to?(:replace_url_to_anchor_tag)
value
end
def content=(value)
dup_value = value.dup
decorate_it(dup_value)
write_attribute(:content, dup_value)
end
private
def decorate_it(value)
class << value
def replace_url_to_anchor_tag
# ...
end
end
end
end
For the sake of simplicity I've ommited the "nil scenario" - you should handle nil values differently. But that's quite simple.
Another thing is that you might ask is why I use dup in the setter. If there is no dup in the code, the behaviour of the following code might be wrong (obviously it depends on your requirements):
x = "something"
s = HtmlSnippet.find(1)
s.content = x
s.content.replace_url_to_anchor_tag # that's ok
x.content.replace_url_to_anchor_tag # that's not ok
Wihtout dup you are extending not only x.content but also original string that you've assigned.