Pass option value to InstanceMethods define_method


#1

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?


#2

On Oct 7, 7:19 pm, Vidmantas Kabošis <rails-mailing-l…@andreas-
s.net> wrote:

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


#3

Frederick C. wrote:

using self.some_field ?

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


#4

On Oct 8, 8:36 am, Vidmantas Kabošis <rails-mailing-l…@andreas-
s.net> wrote:

Frederick C. 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


#5

On 8 Oct 2008, at 11:11, Vidmantas Kabošis wrote:

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


#6

Frederick C. 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


#7

Got it, thank you!

Frederick C. wrote:

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.