我想知道什么是根据包含的模块初始化ruby中的类的最佳方法。我给大家举一个例子:根据包含的模块初始化一个Ruby类
class BaseSearch
def initialize query, options
@page = options[:page]
#...
end
end
class EventSearch < BaseSearch
include Search::Geolocalisable
def initialize query, options
end
end
class GroupSearch < BaseSearch
include Search::Geolocalisable
def initialize query, options
end
end
module Search::Geolocalisable
extend ActiveSupport::Concern
included do
attr_accessor :where, :user_location #...
end
end
我不想要什么,是有初始化:其中和:这包括geolocalisable
模块上的每个类USER_LOCATION变量。
目前,我只是定义就像在我的模块def geolocalisable?; true; end
方法,然后,我初始化这些属性(由模块添加的)在基类:
class BaseSearch
def initialize query, options
@page = options[:page]
#...
if geolocalisable?
@where = query[:where]
end
end
end
class EventSearch < BaseSearch
#...
def initialize query, options
#...
super query, options
end
end
是否有更好的解决方案?但愿如此!
我会尝试,但是你知道它是否以同样的方式使用ActiveSupport时: :关心?在这种情况下,我并不认为所包含的模块几乎像您的示例中那样充当超类。 – Robin 2011-12-30 22:35:59
好吧,它的工作原理完全相同,而且您的解决方案是我一直在寻找的,谢谢。我在搜索时学到的随机事物:调用'super()'与'super'不同。逻辑但仍然^^。 – Robin 2011-12-30 23:09:14