假设我有一系列相关模块:
module Has_Chocolate
def has_chocolate?
true
end
end
module Has_Cake
def has_cake?
true
end
end。。。
如何构造模板模块Has_Something,其中某些内容将是模块的参数?
发布于 2009-07-20 14:32:40
模块是封装上下文中的常量,在顶层是内核。这使我们可以使用const_get获得模块。试试这个:
module Has_Something
def has(*items)
items.each do |item|
mod = Kernel.const_get("Has_" + item.to_s.capitalize)
instance_eval { include mod }
end
end
end
class Baker
extend Has_Something
has :cake
end
class CandyMan
extend Has_Something
has :chocolate
end
class ChocolateCake
extend Has_Something
has :cake, :chocolate
end如果您喜欢包含而不是扩展,您也可以这样做:
module Has_Something
def self.included(base)
base.extend HasTemplate
end
module HasTemplate
def has(*items)
items.each do |item|
mod = Kernel.const_get("Has_" + item.to_s.capitalize)
instance_eval { include mod }
end
end
end
end
class Baker
include Has_Something
has :cake
end
class CandyMan
include Has_Something
has :chocolate
end
class ChocolateCake
include Has_Something
has :cake, :chocolate
end在任何一种情况下,此代码都是相同的:
steve = Baker.new
bob = CandyMan.new
delicious = ChocolateCake.new
steve.has_cake? && bob.has_chocolate? # => true
delicious.has_cake? && delicious.has_chocolate? #=> true编辑:
基于您的评论,您要寻找的是一种自动创建格式has_ the ?方法的方法。这样做更容易:
module Has_Something
def has (*items)
items.each do |item|
method_name = ('has_' + item.to_s + '?').to_sym
send :define_method, method_name do
true
end
end
end
end
class Baker
extend Has_Something
has :cake
end
class CandyMan
extend Has_Something
has :chocolate
end
class ChocolateCake
extend Has_Something
has :cake, :chocolate
end
steve = Baker.new
bob = CandyMan.new
delicious = ChocolateCake.new
steve.has_cake? && bob.has_chocolate? # => true
delicious.has_cake? && delicious.has_chocolate? # => truehttps://stackoverflow.com/questions/1153536
复制相似问题