define_method:如何动态创建带有参数的方法 [英] define_method: How to dynamically create methods with arguments

查看:53
本文介绍了define_method:如何动态创建带有参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为find_by功能创建一堆方法.我不想一遍又一遍写同一件事,所以我想使用元编程.

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.

说我想创建一个用于按名称查找的方法,接受名称作为参数.我该怎么办?我过去使用过define_method,但是我没有任何方法要使用的参数. 这是我的(坏)方法

Say I want to create a method for finding by name, accepting the name as an argument. How would I do it? I've used define_method in the past but I didn't have any arguments for the method to take. Here's my (bad) approach

["name", "brand"].each do |attribute|
    define_method("self.find_by_#{attribute}") do |attr_|
      all.each do |prod|
        return prod if prod.attr_ == attr_
      end
    end
  end

有什么想法吗?预先感谢.

Any thoughts? Thanks in advance.

推荐答案

如果我正确理解了您的问题,则需要这样的东西:

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

(我假设all方法返回一个Enumerable.)

(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

这篇关于define_method:如何动态创建带有参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆