Reputation: 5603
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
.
Upvotes: 0
Views: 2158
Reputation: 330
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
Upvotes: 0
Reputation: 29379
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.
Upvotes: 1