[英]Can't access class variable in ruby/rails?
I have a class like so: 我有一个像这样的课程:
Railsapp/lib/five9_providers/record_provider.rb: 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: Railsapp /应用程序/控制器/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: 但是,调用我的控制器方法
import
只会返回:
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? 如何访问
variable
从recover_provider.rb
类在我five9_controller.rb
类?
EDIT: 编辑:
Even when using @@variable
in both my record_provider
and my five9_controller
, I still can't access that variable. 即使在
record_provider
和five9_controller
中都使用@@variable
时,我仍然无法访问该变量。 I am calling it like so: puts @@variable
. 我这样称呼它:
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. variable
是实例方法的局部variable
,任何方法外部的Ruby表达式都不能访问该variable
。
On a related point, the term "class variable" is typically used to refer to variables of the form @@variable
. 与此相关的是,术语“类变量”通常用于表示
@@variable
形式的@@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. 更新 :作为对“编辑”语句的响应,如果您在类中将
variable
更改为@@variable
,则可以使用一些技术从类外部访问该变量,但是对@@variable
的裸引用不是其中一种他们。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.