Rails 3 - 在before_filter中添加控制器中的动作

时间:2012-09-04 20:38:12

标签: ruby-on-rails-3 metaprogramming

我正在尝试根据请求参数动态地将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之后为{{1}}实例。

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

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