如何在Rails中区分相同的命名辅助方法?

Dhi*_*esh 2 ruby-on-rails-3

我在两个不同的帮助器中创建了辅助函数(link_to_alert)

  1. 应用程序/佣工/ posts_helper.rb
  2. 应用程序/佣工/ students_helper.rb

现在,打电话给我的助手功能link_to_alertapp/views/student/index.html.haml

问题是调用相同函数的视图 app/helpers/posts_helper.rb

如何app/helpers/students_helper.rb从我的 app/views/student/index.html.haml视图中调用辅助函数?

Sim*_*tsa 8

由于默认情况下所有控制器都包含在所有控制器中,因此最常见的方法是以不同方式命名函数,例如link_to_alert_postslink_to_alert_students.

第二种方法是禁用包括所有帮助程序并在控制器中选择所需的帮助程序.

config.action_controller.include_all_helpers = false

class PostsController
  helper :posts
end

class StudentsController
  helper :students
end
Run Code Online (Sandbox Code Playgroud)

在这种情况下,Posts Controller呈现的所有视图都将具有Posts Helper和Student Controller的功能 - 来自Students Helper.

第三种方法是使用module_function并使用辅助模块名称为所有调用添加前缀.我从来没有见过这个特别适用于Rails助手.

module StudentsHelper
  module_function

  def link_to_alert
  end
end

StudentsHelper.link_to_alert
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用演示者或装饰者,但这是一个完全不同的主题.