views:

57

answers:

1

Possible Duplicate:
How do I use define_method to create class methods?

I am trying to do this:

class Foo
  class << self
    def runtime_method(*methods)
      methods.each do |name|
        define_method "self.#{name}" do |*args|
          "dynamic class method #{name.inspect}"
        end
        self.class_eval do
          define_method name do
            "dynamic instance method #{name.inspect}"
          end
        end
      end
    end
  end

  runtime_method :foo, :bar
end

puts Foo.foo rescue #=> otherwise, undefined method `foo' for Foo:Class (NoMethodError)
puts Foo.new.foo #=> dynamic instance method: :foo
puts Foo.new.bar #=> dynamic instance method: :bar

Is there any way to define dynamic class methods in ruby?

+3  A: 

Hi, I'm not sure I understand you exactly, but is this what you mean?

>> class Foo
>> end
=> nil
>> Foo.blah
NoMethodError: undefined method `blah' for Foo:Class
    from (irb):3
>> 
?> Foo.class.class_eval do
?>   def blah
>>     puts "hello"
>>   end
>> end
=> nil
>> Foo.blah
hello
=> nil
clocKwize
nice! that's what i mean :)
viatropos