请帮帮我。
我需要在许多类中使用相同的属性。我建议创建具有预定义属性的模块,并在每个类中扩展该模块
module Basic
@a=10
end
class Use
extend Basic
def self.sh
@a
end
end
puts Use.sh
但输出为空。好像我错过了什么。
也许有更好的方法可以做到这一点?
你的想法?
答案 0 :(得分:1)
module Basic
@a=10
end
评估为self
。当扩展后者时,您希望它评估为Use
:
module Basic
# self = Basic, but methods defined for instances
class << self
# self = Basic's eigenclass
def extended(base)
base.class_eval do
# self = base due to class_eval
@a=10
end
end
end
end
class Use
# self = Use, but methods defined for instances
extend Basic # base = Use in the above
class << self
# self = Use's eigenclass
def sh
@a
end
end
end
Use.sh # 10
答案 1 :(得分:0)
您所描述的是Flyweight设计模式。虽然有些人认为这很少用于ruby(http://designpatternsinruby.com/section02/flyweight.html),但其他人提供了一种实现(http://www.scribd.com/doc/396559/gof-patterns-in-ruby第14页)
就个人而言,我要做的是将所有这些属性放入yaml文件中,并将它们解析为全局变量:
ATTRIBUTES = YAML.load_file(File.expand_path('attributes.yml',File.dirname( FILE ))
或类方法(在此处使用缓存,假设您在应用程序运行时不会更改yml文件并需要新值)。我建议在这里使用ActiveSupport::Concern
因为它比传统的类方法混合更容易阅读:
module Basic
extend ActiveSupport::Concern
module ClassMethods
def attributes_file
File.expand_path('attributes.yml', File.dirname(__FILE__))
def attributes
@attributes ||= YAML.load_file(attributes_file)
@attributes
end
end
module InstanceMethods
# define any here that you need, like:
def attributes
self.class.attributes
end
end
end
您可以为每个属性定义方法,或者依赖索引到属性哈希。您还可以使用fancy并定义method_missing以检查是否存在具有该名称的属性,这样您就不必继续添加方法,因为您希望向共享配置添加更多属性。