2014-01-29 62 views
1

如何從外部訪問以下代碼中的reserved_words如何從外部調用模塊的attr_accessor變量?

module FriendlyId 
    module Reserved 
     module Configuration 
     attr_accessor :reserved_words 
     end 
    end 
end 

FriendlyId::Reserved::Configuration.instance_variable_get(:reserved_words)給了我以下錯誤:

NameError: 'reserved_words' is not allowed as an instance variable name

+0

您是否特別需要'attr_accessor'或者您可以使用rails提供的擴展名'mattr_accessor'(http://api.rubyonrails.org/classes/Module.html#method-i-mattr_accessor) – Shadwell

+0

試試這個:: FriendlyId :: Reserved :: Configuration.instance_variable_get(:reserved_words) – Egalitarian

+0

檢查此線程http://stackoverflow.com/questions/185573/what-is-mattr-accessor-in-a-rails-module – xlembouras

回答

1

::attr_accessor的正確用法,以及實例和類變量如下。由於::attr_accessor只是限定了對實例方法#m,和m=,到模塊的分配不能被用於模塊:

module M 
    attr_accessor :m 
end 

M.instance_methods 
# => [:m, :m=] 
M.instance_variables 
# => [] 

,但它可用於一類:

class A 
    include M 

    def initialize 
     @m = 1 
     @@mm = 2 
    end 

    def self.mm 
     @@mm 
    end 
end 

a = A.new 
p a.m 
# => 1 
p A.mm 
# => 2 
p A.new.instance_variable_get(:@m) 
# => 1 
p A.class_variable_get(:@@mm) 
# => 2 

在上面的例子中,我們定義了類變量@@mm,只有在這種情況下我們可以用::class_variable_get方法讀取它,實例變量@m只能在類的實例被創建時才能讀取。