0

I am trying to create an accessor for a class instance variable. I am calling the attr_accessor method from a module which is included in the class. See the code below:

module Persistence
  def self.included(mod)
      mod.extend ClassMethods
      # Add accessor for class instance variable
      class << mod
          attr_accessor :persistent_data
      end
  end

  module ClassMethods
      def X
          persistent_data = 'data'
      end
  end
end

The above code works. However when I change the code which calls attr_accessor, to this:

 mod.instance_eval do
     attr_accessor :persistent_data
 end

I get NoMethodError: undefined method `persistent_data='

Shouldn't both ways work the same or is my understanding wrong here? I am using REE 1.8.7

ShadyKiller
  • 700
  • 8
  • 16
  • 3
    `attr_accessor` is an instance method and defines instance methods. So it has to be executed in a context where defining *instance* methods is actually defining a class method. And because class methods are actually singleton methods, you have to execute it in the singleton class. – Linuxios Oct 19 '12 at 18:29
  • 1
    ActiveSupport provides `cattr_accessor` which defines both a class method and an instance method to access the same value. (See also its [rdoc](http://api.rubyonrails.org/classes/Class.html#method-i-cattr_accessor) and ActiveSupport [guide](http://guides.rubyonrails.org/active_support_core_extensions.html#cattr_reader-cattr_writer-and-cattr_accessor).) If you have ActiveSupport, use it; if not, its implementation might still be useful as inspiration. – willglynn Oct 20 '12 at 04:46

0 Answers0