【问题标题】:Rails 3 – add action in controller's from before_filterRails 3 – 在控制器的 before_filter 中添加动作
【发布时间】:2012-09-04 20:38:11
【问题描述】:

我正在尝试根据请求参数向我的控制器动态添加一个 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_namenew 并且 respond_to?("new")true

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

【问题讨论】:

  • 确定是extend 而不是include?尽管如此,我认为这是我今天见过的最糟糕的主意。
  • 目的是什么?想要这样做的用例是什么?
  • @DaveNewton 这听起来很简单,可以轻松添加新的输入法,并与其他控制器操作(before_filters 等)共享逻辑,同时仍处于控制器的范围内。您建议采用哪种方法?值得一提的是,我的第一种方法是使用 PORO 并传入控制器,但我基本上每行都以 controller. 开头。
  • @phoet 我正在扩展实例,而不是类。我可能弄错了,但我认为 extend 是我要找的。​​span>
  • 我猜你正在寻找这样的东西:github.com/bitlove/objectify

标签: ruby-on-rails-3 metaprogramming


【解决方案1】:

这是我想出的解决方案。它可以满足我的需求。

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

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    相关资源
    最近更新 更多