siva
siva

Reputation: 1481

How to use same variable across various controllers - ruby on rails

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.

Upvotes: 0

Views: 452

Answers (2)

Deepak Mahakale
Deepak Mahakale

Reputation: 23671

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

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52357

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.

Upvotes: 1

Related Questions