0

I have this code:

module Helper
  def translates(*attributes)
    attributes.each do |attribute|
      define_method("find_by_#{attribute}") do |value|
        value
      end  
    end  
  end  
end  

class SomeClass
  extend Helper
  translates :foo
end

Now, in my opinion, the method SomeClass.find_by_foo should exist. But it doesn't. Do you know what am I doing wrong?

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
Janko
  • 8,985
  • 7
  • 34
  • 51

2 Answers2

2

You'll find that SomeClass.new.respond_to?(:find_by_foo) returns true. If you want to add the methods to the class side, use define_singleton_method.

Frank Shearar
  • 17,012
  • 8
  • 67
  • 94
1

Use the Eigenclass

You can define the method as a class method using the eigenclass. For example:

module Helper
  def translates(*attributes)
    attributes.each do |attribute|
      define_singleton_method("find_by_#{attribute}") do |value|
        value
      end
    end
  end
end
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • Thanks. I tried to put `define_method` inside `instance_eval` but it didn't work. I didn't know about this one. – Janko Jul 17 '12 at 14:14