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?

0

1 Answer 1

3

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
1
  • This defines blah on every class.
    – philomory
    Jun 12, 2016 at 21:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.