Pass option value to InstanceMethods define_method

Hello,

I'm trying to develop a ActiveRecord plugin but run into the following problem: I pass arguments to

write_inheritable_attribute :some_field, 'value' class_inheritable_reader :some_field

in ClassMethods module and I'm available to get them in InstanceMethods with self.class.some_field. But when I try to do like this:

define_method "#{self.class.some_field}" ...

or

class_eval <<-eval   def #{self.class.some_field}    ...   end eval

I get NoMethodError: undefined method `some_field' for Module:Class

Anybody could help with this?

Hello,

I'm trying to develop a ActiveRecord plugin but run into the following problem: I pass arguments to

write_inheritable_attribute :some_field, 'value' class_inheritable_reader :some_field

in ClassMethods module and I'm available to get them in InstanceMethods with self.class.some_field. But when I try to do like this:

I may not be reading you correctly, but at that point do you not need to be using self.some_field ? (self.class.some_field would be trying to find that method on Class or something like that.

Fred

Frederick Cheung wrote:

using self.some_field ?

I've tried this too, but then I get NoMethodError: undefined method `some_field' for MyModule::InstanceMethods:Module

I think you need to post more of your code. It's not clear where you are calling what which is rather important here.

Fred

Frederick Cheung wrote:

I think you need to post more of your code.

Sure:

module MyModule   def self.included(base)     base.extend ClassMethods   end

  module ClassMethods     def money_is(field_name)       write_inheritable_attribute :some_field, 'value'       class_inheritable_reader :some_field

      self.send(:include, MyModule::InstanceMethods)     end   end

  module InstanceMethods     define_method "#{self.some_field}" do       # code     end   end end

script/console

Loading development environment (Rails 2.1.0) /home/vidmantas/projects/my_project/vendor/plugins/my_module/lib/my_module.rb:16:NoMethodError: undefined method `some_field' for MyModule::InstanceMethods:Module

Frederick Cheung wrote:

I think you need to post more of your code.

Sure:

module MyModule def self.included(base)    base.extend ClassMethods end

module ClassMethods    def money_is(field_name)      write_inheritable_attribute :some_field, 'value'      class_inheritable_reader :some_field

     self.send(:include, MyModule::InstanceMethods)    end end

module InstanceMethods    define_method "#{self.some_field}" do      # code    end end end

OK. when the define_method runs, self is the module InstanceMethods.
At that point it hasn't even been included in anything so there is no
way to get the value of some_field.

I would just be doing this from the money_is method (or if you want to
keep the InstanceMethods module then from its included hook.

Fred

Got it, thank you!

Frederick Cheung wrote: