0
我想要一個mixin添加到我的控制器動態取決於請求參數,像這樣添加動作:的Rails 3控制器的距離的before_filter
# Controller
class QuantitiesController < Admin::BaseController
before_filter :extend_input_method, only: [:create, :new]
def extend_input_method
input_method = params[:input_method]
if input_method
send(:extend, "InputMethod::#{input_method.classify}".constantize)
end
end
end
# Mixin that gets included in the controller
module InputMethod::Single
include InputMethod::Helpers
def new
puts "CALLED #new" # Debug information
load_recent_entries
quantity
end
def create
@quantity = scoped_by_subject.new(process_attributes)
if @quantity.save
save_success
else
load_recent_entries
save_error
end
end
end
的new
方法不會被調用,但我的模板被不渲染引發例外,即使action_name
是new
和respond_to?("new")
是true
擴展實例後。
我想了解爲什麼這不起作用,以及如何實現類似的功能。
確定它是'''extend'''而不是'''include'''?不過,我認爲這是我今天看到的最糟糕的主意。 – phoet
目的是什麼?想要這樣做的用途是什麼? –
@DaveNewton它聽起來很簡單,可以毫不費力地添加新的輸入方法,並可以與其他控制器操作(before_filters等)共享邏輯,同時仍處於控制器範圍內。你建議哪種方法?對於它的價值,我的第一種方法是使用PORO並傳入控制器,但我基本上都是用'controller.'開始每一行。 – Jimmy