0

我正在尝试根据请求参数动态地将 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_namenewrespond_to?("new")是。true

我想了解为什么这不起作用以及如何实现类似的目标。

4

1 回答 1

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
于 2012-09-16T21:41:33.430 回答