define_method: How to dynamically create methods with arguments

前端 未结 3 1809
梦谈多话
梦谈多话 2020-12-30 20:05

I want to create a bunch of methods for a find_by feature. I don\'t want to write the same thing over and over again so I want to use metaprogramming.

Say I want to

3条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-30 20:31

    If I understand your question correctly, you want something like this:

    class Product
      class << self
        [:name, :brand].each do |attribute|
          define_method :"find_by_#{attribute}" do |value|
            all.find {|prod| prod.public_send(attribute) == value }
          end
        end
      end
    end
    

    (I'm assuming that the all method returns an Enumerable.)

    The above is more-or-less equivalent to defining two class methods like this:

    class Product
      def self.find_by_name(value)
        all.find {|prod| prod.name == value }
      end
    
      def self.find_by_brand(value)
        all.find {|prod| prod.brand == value }
      end
    end
    

提交回复
热议问题