如何判断当前操作是否在引擎中?

时间:2013-09-19 20:59:10

标签: ruby-on-rails rails-engines

在我的application.html.erb中,我希望能够检测当前呈现页面是否来自已安装的引擎(Forem,如果这很重要),以便我可以添加active类导航栏。有没有一种简单的方法来检测这个?

我正在使用Rails 3.2。

3 个答案:

答案 0 :(得分:5)

您可以通过重新打开课程在Forem::ApplicationController中添加辅助方法:

Forem::ApplicationController.class_eval do
  def forem?
    true
  end

  helper_method :forem?
end

例如,在app/decorators/forem/application_controller_decorator.rb中添加上述文件。

这样,每次Forem的控制器呈现视图时,您都可以在视图中调用forem?

<强> application.html.erb

<% if forem? %>
  # do something
<% end %>

您可能想先检查当前实例respond_to?(:forem?),或者在自己的forem?中添加false方法返回application_controller.rb

答案 1 :(得分:1)

可以在不使用装饰器加载(仅使用Rails默认加载)的情况下完成非常类似的方法,例如,对于Thredded:

#This file would be at app/controllers/thredded/application_controller.rb in your main_app repo

require_dependency File.expand_path("../../app/controllers/thredded/application_controller",
  Thredded::Engine.called_from)

module Thredded
  class ApplicationController < ::ApplicationController
    def thredded?
      true
    end
  end
end

然后在您自己的ApplicationController中添加默认值和helper_method声明:

class ApplicationController < ActionController::Base
  helper_method :thredded? 
  def thredded?
    false
  end

  # etc

end

答案 2 :(得分:0)

您可以使用:

<% if controller.controller_name == ""something" && 
               controller.action_name == "something" %> 
   Do someting  <!-- add you class -->
<% end %>