Domanda

Within my application.html.erb, I want to be able to detect if the currently rendering page is from within a mounted engine (Forem, if that matters), so that I can add an active class to the nav bar. Is there an easy way to detect this?

I'm using Rails 3.2.

È stato utile?

Soluzione

You could add a helper method in Forem::ApplicationController by reopening the class:

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

  helper_method :forem?
end

Add the above file in app/decorators/forem/application_controller_decorator.rb for example.

This way every time a view is rendered by Forem's controller you would be able to call forem? within your view.

application.html.erb

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

You might want to check if the current instance respond_to?(:forem?) first, or add a forem? method returning false in your own application_controller.rb.

Altri suggerimenti

A very similar approach can be done without the use of decorator loading (just using Rails default loading), e.g. for 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

and then add the default value and helper_method declaration in your own ApplicationController:

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

  # etc

end

You can use this:

<% if controller.controller_name == ""something" && 
               controller.action_name == "something" %> 
   Do someting  <!-- add you class -->
<% end %>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top