公开控制器的类方法来查看辅助方法?

时间:2012-07-09 20:43:54

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

如何在视图层中提供以下方法?

# app/controllers/base_jobs_controller.rb
class BaseJobsController < ApplicationController
  def self.filter_name
    (controller_name.singularize + "_filter").to_sym
  end
end

我想在像这样的视图助手中使用它:

module ApplicationHelper
  def filter_link(text, options = {})
    # Need access to filter_name in here....
  end
end

1 个答案:

答案 0 :(得分:2)

我宁愿在模块中包含此类功能,而不是helper_method

module BaseJobsHelp
  def filter_name
    (controller_name.singularize + "_filter").to_sym
  end
end

然后在BaseJobsControllerApplicationHelper

中加入该模块
class BaseJobsController < ApplicationController
  include BaseJobsHelp

  # ...
end


module ApplicationHelper
  include BaseJobsHelp

  def filter_link(text, options = {})
    # You can access filter_name without trouble
  end
end

根据模块中方法的内容,您可能需要使用替代方法来访问某些数据(即当前控制器的名称)