如何使用Ruby的元编程来减少方法数量 [英] How to use Ruby's metaprogramming to reduce method count

查看:68
本文介绍了如何使用Ruby的元编程来减少方法数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆重复的方法,而且我确定我可以以某种方式使用Ruby的元编程.

I have a bunch of methods that are repeating, and I am sure I can use Ruby's metaprogramming somehow.

我的课看起来像这样:

class SomePatterns

  def address_key
    "..."
  end

  def user_key
    "..."
  end

  def location_key
    "..."
  end

  def address_count
    redis.scard("#{address_key}")
  end

  def location_count
    redis.scard("#{location_key}")
  end

  def user_count
    redis.scard("#{user_key}")
  end

end

我当时想我只能使用一种方法:

I was thinking I could have only one method like:

def count(prefix)
  redis.scard("#{prefix}_key") # wrong, but something like this
end

以上是错误的,但我是说*_count方法将遵循一种模式.我希望学习使用元编程来避免重复.

The above is wrong, but I'm saying that the *_count methods will follow a pattern. I'm hoping to learn to use metaprogramming to avoid the duplication.

我该怎么办?

推荐答案

我会将所有函数前缀"放入数组中.初始化后,您可以在这些前缀上使用 :define_singleton_method 在每个实例上动态创建实例方法其中之一:

I would put all of the "function prefixes" into an array. Upon initialization you can use the :define_singleton_method on these prefixes to dynamically create a instance method on every one of them:

class SomePatterns
  def initialize()
    prefixes = [:address, :location, :user]
    prefixes.each do |prefix|
      define_singleton_method("#{prefix}_count") { redis.scard("#{prefix}_key") }
    end
  end
end

:define_singleton_method可能实际上是多余的.它可以根据您的需要工作,但是它将为该特定实例定义这些功能(因此称为单例").差异是微妙的,但很重要.相反,最好使用:class_eval :define_method 结合.

:define_singleton_method might actually be overkill. It will work for what you want, but it will define these functions for that specific instance (hence why its called singleton). The difference is subtle, but important. Instead, it would probably be better to use :class_eval in conjunction with :define_method.

class SomePatterns
    # ...
    class_eval do
      [:address, :location, :user].each do |prefix|
        define_method("#{prefix}_count") { redis.scard("#{prefix}_key") }
      end
    end
end

这篇关于如何使用Ruby的元编程来减少方法数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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