Reputation: 591
In pages_controller.rb:
class PagesController < ApplicationController
def show
@page = Page.find_by(url: params[:url])
@meta = { title: @page.title, description: @page.description, keywords: @page.keywords }
end
end
In layout I use such a way to show meta title of a page:
<title><%= @meta[:title] %></title>
But when I go other page, for example root page ("/") I have an error
undefined method `[]' for nil:NilClass
Because for this page @meta is not initialized.
So I think I have to initialize @meta[:title] with a default value. Where in app should I put this code?
And one more. I want to wrap assigning @meta to a helper method. Where should I define it?
Upvotes: 1
Views: 1378
Reputation: 1137
If you want to use this as Class variable
User @@meta in ApplicationController
@@ creates a class variable that you can use in all the project because all inherit from ApplicationController
Upvotes: 0
Reputation: 168
Seems that it is a bad idea to prepare some view-related data in a controller. Maybe, it would be better to provide some kind of presenter for your @post object.
Upvotes: 1
Reputation: 671
You can do it in your application_controller
, with a before_filter:
before_filter :initialize_metas
def initialize_metas
@meta = { title: 'default_title', description: 'default_description', keywords: 'default_keywords' }
end
Then in your controllers than inherit from application_controller
you can override it:
@meta = { title: @page.title, description: @page.description, keywords: @page.keywords }
or just override/add the keys you need:
@meta[:title] = 'another_title'
Upvotes: 2