含まれるモジュールに応じて、Rubyでクラスを初期化する最良の方法は何か疑問があります。例を挙げましょう:と::geolocalisable
モジュールを含む各クラスのUSER_LOCATION変数含まれるモジュールに応じて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
私はしたくない何を、初期化するために持っています。
現在、私はちょうど私のモジュール内の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
それで、まったく同じように動作し、あなたのソリューションは私が探していたものでした。ありがとうございました。検索中に覚えたランダムなこと: 'super()'を呼び出すことは 'super'とは異なります。論理的ですがまだ^^。 – Robin