femalemoustache
femalemoustache

Reputation: 591

How to initialize and show meta tags in Rails app

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

Answers (3)

ppascualv
ppascualv

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

Plugataryov Yura
Plugataryov Yura

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

iMacTia
iMacTia

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

Related Questions