別のモジュールで初期化され、コントローラーに含まれてコントローラークラスレベルで変更され、コントローラーインスタンスレベルでアクセスできる、ある種の単一のリストが必要です。クラス変数はここで機能すると思っていましたが、奇妙なことが起こっています。終了クラス内で初期化されていないようです。
すなわち:
モジュールには、いくつかのデフォルト機能を含む多くのコントローラーがあります。
class BlahController < ApplicationController
include DefaultFunctionality
end
class FooController < ApplicationController
include DefaultFunctionality
end
module DefaultFunctionality
def show
render 'shared/show'
end
def model
controller_name
end
end
、 例えば。これは実際のコードではありませんが、現時点で最も多くのやり取りがあります。
これを他の機能(リストのソート可能なインターフェース)で拡張したいと思います[クラスごとにソート順リスト機能を交換できるようにしたいことに注意してください]:
module DefaultFunctionality
module Sortable
def sort_params
params.slice(:order, :sort_direction).reverse_merge(default_sort_params)
end
def default_sort_params
@@sorts.first
end
def set_sorts(sorts = []) #sorts = [{:order => "most_recent", :sort_direction => :desc},...]
@@sorts = sorts
end
end
include Sortable
set_sorts([{:order => :alphabetical, :sort_direction => :asc}] #never run?
end
アイデアは、次のように、クラスごとに可能なすべての並べ替えのセットを交換できるようにすることです。
class FooController < ApplicationController
include DefaultFunctionality #calls the default set_sorts
set_sorts([{:order => :most_recent, :sort_direction => :asc}])
end
また、エラーが発生することを除いて、以下のようにビューに素敵なリンクを作成することもできます。
___/blah/1 => shared/show.html.erb__
<%= link_to("upside down", polymorphic_path(model, sort_params) %><%#BOOOM uninitialized class variable @@sorts for BlahController %>
class_var は悪い呼び出しだと思いますが、他に何を使用できるか考えられません。(クラスインスタンス変数?)