我有很多重复的方法,并且我确信我可以以某种方式使用 Ruby 的元编程。
我的班级是这样的:
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
我想我只能有一种方法,例如:
def count(prefix)
redis.scard("#{prefix}_key") # wrong, but something like this
end
上面的说法是错误的,但我想说的是*_count
方法将遵循某种模式。我希望学习使用元编程来避免重复。
我怎么能这样做呢?
我会将所有“函数前缀”放入一个数组中。初始化后,您可以使用:define_singleton_method https://apidock.com/ruby/Object/define_singleton_method在这些前缀上动态创建每个前缀的实例方法:
class SomePatterns
def initialize()
prefixes = [:address, :location, :user]
prefixes.each do |prefix|
define_singleton_method("#{prefix}_count") { redis.scard("#{prefix}_key") }
end
end
end
EDIT:
:define_singleton_method
实际上可能有点矫枉过正。它将满足您的需求,但它将为该特定实例定义这些函数(因此称为单例)。差异很微妙,但很重要。相反,使用它可能会更好:class_eval https://ruby-doc.org/core-2.2.0/Module.html#method-i-class_eval和这个结合:定义方法 https://apidock.com/ruby/Module/define_method.
class SomePatterns
# ...
class_eval do
[:address, :location, :user].each do |prefix|
define_method("#{prefix}_count") { redis.scard("#{prefix}_key") }
end
end
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)