开发者

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, m开发者_高级运维y 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?


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?


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜