【问题标题】:Expose controller's class method to view helper method?将控制器的类方法公开给查看辅助方法?
【发布时间】:2012-07-09 20:43:53
【问题描述】:
如何使以下方法在视图层中可用?
# 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
【问题讨论】:
标签:
ruby-on-rails
ruby
ruby-on-rails-3
ruby-on-rails-3.1
【解决方案1】:
比起helper_method,我更喜欢在模块中包含这样的功能。
module BaseJobsHelp
def filter_name
(controller_name.singularize + "_filter").to_sym
end
end
然后将模块包含在BaseJobsController 和ApplicationHelper 中。
class BaseJobsController < ApplicationController
include BaseJobsHelp
# ...
end
module ApplicationHelper
include BaseJobsHelp
def filter_link(text, options = {})
# You can access filter_name without trouble
end
end
根据模块中方法的内容,您可能需要使用替代方法来访问某些数据(即当前控制器的名称)。