根据包含的模块初始化Ruby类

时间:2011-12-30 14:01:13

标签: ruby-on-rails ruby module initialization

我想知道根据所包含的模块在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模块的每个类上初始化:where和: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

有更好的解决方案吗?我希望如此!

2 个答案:

答案 0 :(得分:3)

为什么不覆盖模块中的initialize?你可以做到

class BaseSearch
  def initialize query
    puts "base initialize"
  end
end

module Geo
  def initialize query
    super
    puts "module initialize"
  end
end

class Subclass < BaseSearch
  include Geo
  def initialize query
    super
    puts "subclass initialize"
  end
end

Subclass.new('foo') #=>
  base initialize
  module initialize
  subclass initialize

显然,这确实需要包含您的模块的所有内容都具有类似签名的初始化或可能发生奇怪的事情

答案 1 :(得分:0)

请参阅此代码:

module Search::Geolocalisable
  def self.included(base)
    base.class_eval do
      attr_accessor :where, :user_location #...
    end
  end
end

class EventSearch < BaseSearch
  include Search::Geolocalisable
end