我正在尝试根据请求参数动态地将mixin添加到我的控制器中,如下所示:
# 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
之后为{{1}}实例。
我想了解为什么这不起作用以及如何实现类似的目标。
答案 0 :(得分:0)
这是我提出的解决方案。它适合我的需要。
class QuantitiesController < Admin::BaseController
before_filter :extend_input_method, only: [:create, :new]
def new
_new
end
def create
_create
end
private
def extend_input_method
input_method = params[:input_method]
extend(Dep.get("InputMethod::#{input_method.classify}")) if input_method
end
end
module InputMethod::Single
include InputMethod::Helpers
def _new
# Do stuff...
end
def _create
# Do stuff...
end
end