Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: How to get a applcation controller variable to my application layout

I'm trying to get a variable set in the application controller to bubble up to the application layout.

If I use:

@var = 'foo'

...the application layout doesn't know what I'm talking about

If I use a global variable

$var = 'foo'

... the application layout works. However, my functional tests don't work:

# application layout
# my var is an AR object
$var.name

# Stock functional test
class HomeControllerTest < ActionController::TestCase
  test "should get index" do
    get :index
    assert_response :success
  end
end

# test:functionals 
ActionView::Template::Error: undefined method `name' for nil:NilClass

I need this var available to the application layout (every page). Thoughts? Do I need to make this a session var?

Update

Based on a few other posts I'm reading, is it considered best practice to place these in the application helper, then call them from the layout?

# Application helper
def get_var
   Product.first
end

# Application layout
<% @var = get_var %>
<!DOCTYPE html>
<html lang="en">
<head>
...

This a) works in my browser and b) passes tests. Is it best practice? Is there an easier/better way?

like image 997
jmccartie Avatar asked Dec 04 '10 00:12

jmccartie


2 Answers

Did you try before_filter the method where the variable is declared to make sure each other controller calls it and pass the variable to their corresponding view?

class ApplicationController < ActionController::Base

before_filter :foo_function

def foo_function
@var = "foo"
end

end

If @var is an AR object and not a string, you sure you have the Model name and column name defined correctly?

like image 167
KMC Avatar answered Nov 14 '22 12:11

KMC


Have you tried implement it as a helper_method?

class ApplicationController < ActionController::Base
  helper_method :foo, :foo=

  def foo
    @var ||= "foo"
  end

  def foo=(val)
    @var = val
  end
end
like image 44
PeterWong Avatar answered Nov 14 '22 12:11

PeterWong