Nona
Nona

Reputation: 5462

Why are these methods not dynamically defined at runtime by define_method?

So I have the following class below in a Rails 4.2 app that uses define_method to dynamically define class methods at runtime. When I boot up the rails console it says that the Dynamic.kite_flying and Dynamic.tail_flying methods don't exist. Is there something I'm missing to define these methods when I invoke them on the Dynamic class?

class Dynamic
  def self.hello_world
    puts "hello"
  end
  ["kite", "tail"].each do |arg|
    define_method("self.#{arg}_flying") do |word_name, list|
      puts "hello some dynamic #{arg}_flying"
    end
  end

end

Upvotes: 2

Views: 155

Answers (1)

smathy
smathy

Reputation: 27961

define_method doesn't define class methods, it defines instance methods. You want define_singleton_method to define class methods in the code you have above.

Upvotes: 2

Related Questions