在 Ruby 1.9 中访问类变量的正确方法是什么? [英] What is the proper way to access class variables in Ruby 1.9?
问题描述
我正在尝试设置一些类变量来存储 Rails 应用程序中的路径(但我认为这更像是一个红宝石问题)
I'm trying to set some class variables to store paths in a Rails application (but I think this more a ruby question)
基本上我的班级是这样的
Basically my class looks like this
class Image < ActiveRecord::Base
@@path_to_folder = "app/assets"
@@images_folder = "upimages"
@@path_to_images = File.join(@@path_to_folder, @@images_folder)
end
但是当我尝试通过执行 Image.path_to_images
从我的控制器访问 @@path_to_images
时,我得到一个 NoMethodError
But when I try to access @@path_to_images
from my controller by doing Image.path_to_images
, I get a NoMethodError
当我尝试使用 Image.class_eval(@@path_to_images)
时,我在 ImagesController 中得到了 未初始化的类变量 @@path_to_images
When I try with Image.class_eval( @@path_to_images )
, I get uninitialized class variable @@path_to_images in ImagesController
我四处搜索,我所看到的都说这些会起作用,所以我对此感到非常困惑
I've searched around and all I've seen says those would work, so I'm very confused about this
更重要的是,我尝试使用 ruby 控制台定义简单的类
What's more, I tried defining simple classes with the ruby console like so
class Bidule
@@foo = "foo"
Bar = "bar"
end
所以我尝试了所有可能的方法(包括前 2 种)来访问它们,但没有办法总是引发异常
And so I tried, I think, all the ways possible (previous 2 included) to access them but no way I always get an exception raised
推荐答案
Rails 为此功能提供了类级别的属性访问器
Rails provides class level attribute accessor for this functionality
试试
class Image < ActiveRecord::Base
cattr_accessor :path_to_folder
@@path_to_folder = "app/assets"
end
然后访问 path_to_folder 类变量只需使用
Then to access path_to_folder class variable just use
Image.path_to_folder
但是人们总是建议避免类变量,因为它在继承中的行为.所以你可以使用像
But people always suggest to avoid class variables due to its behavior in inheritance.So you can use constants like
class Image < ActiveRecord::Base
PATH_TO_FOLDER = "app/assets"
end
然后你可以像这样访问常量
Then you can access the constant like
Image::PATH_TO_FOLDER
这篇关于在 Ruby 1.9 中访问类变量的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!