0

I am using ruby 2.3.1 and rails 3.2.1. I need to initialize a variable called has_sub_menu = false in application controller.

In my application i am using more than 30 controllers and only two controllers contains sub-menu, so i need to assign has_sub_menu = true to these controllers to validate it in layout file.

This is my application.rb

has_sub_menu = false

some_controller01.rb

has_sub_menu = true

some_controller02.rb

has_sub_menu = true

I tried like this in layout.rb,

if controller.has_sub_menu == true
  show_menu_items
end

show_menu_items will be available in that two controller and currently i am not able to access the has_sub_menu value in layout file

I know in c# I can declare the variable as static and access it in any file using object.

Like wise how can i declare a variable in application controller and assign different value to that variable in other two controller and I need to access that value in layout.rb file for sub-menu validation.

1
  • shouldnt that go in the application_controller as a method instead of application.rb? Commented Nov 4, 2016 at 14:32

2 Answers 2

1

Add an instance method in application_controller.rb and override it in any controller, that should have different value:

class ApplicationController < ActionController::Base
  def has_sub_menu # unless overriden in descending controller, value will be true
    true
  end
end

class OtherController < ApplicationController
  def has_sub_menu
     false
  end
end

This way you have access to has_sub_menu "method" in all controllers.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead, you can create a helper method and check for controller name

module ApplicationHelper
  CONTROLLERS_LIST = ['UsersController']

  def has_sub_menu
    CONTROLLERS_LIST.exclude?(params[:controller])
  end
end

4 Comments

not that straightforward and clear for those, who see controller's code for the first time, but indeed a good option!
He says he need to check it in layout so it's better to add this logic in helper method
I am looking for a solution to validate it instead of controller_name.
In that case go for the solution @andrey has posted

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.