1

How can I access reserved_words in the code below from outside?

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

Doing FriendlyId::Reserved::Configuration.instance_variable_get(:reserved_words) gives me the following error:

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

Hopstream
  • 6,391
  • 11
  • 50
  • 81
  • Do you specifically need `attr_accessor` or could you use the extension that rails provides `mattr_accessor` (http://api.rubyonrails.org/classes/Module.html#method-i-mattr_accessor) – Shadwell Jan 29 '14 at 12:33
  • Try this ::FriendlyId::Reserved::Configuration.instance_variable_get(:reserved_words) – Egalitarian Jan 29 '14 at 12:33
  • check this thread http://stackoverflow.com/questions/185573/what-is-mattr-accessor-in-a-rails-module – xlembouras Jan 29 '14 at 12:36

1 Answers1

1

The correct usage of the ::attr_accessor, and instance and class variable is the following. Since the ::attr_accessor is just defines the pair of instance methods #m, and m=, the assignment to module can't be used for the module:

module M
   attr_accessor :m
end

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

but it could be used for a class:

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

In above example, we defined class variable @@mm, and only in this case we can read it with ::class_variable_get method, instance variable @m can be read only when the instance of class been created.

Малъ Скрылевъ
  • 16,187
  • 5
  • 56
  • 69