Module: PageMeta::ClassMethods

Defined in:
lib/page_meta_for.rb

Instance Method Summary collapse

Instance Method Details

#initialize_metaObject



16
17
18
19
20
# File 'lib/page_meta_for.rb', line 16

def initialize_meta
  before_action do
    @page_meta_for = {}
  end
end

#meta_for(*keys, &block) ⇒ Object

Controller level method to define the part of the meta tags

class ApplicationController < ActionController::Base
  meta_for(:title, :suffix, 'ApplicationName')
  meta_for(:title, :prefix) { action_name }
  meta_for(:description) { 'Lorem ipsum set' }
end

class WelcomeController < ApplicationController
  meta_for(:title) { 'Landing Page' }
  meta_for(:description) { 'Lorem ipsum set2' }
end

Then views and layouts are able to call ‘page_meta_for`:

<title><%= page_meta_for(:title, join_string: ' * ') %></title>
<meta name="description" content="<%= page_meta_for(:description) %>" />

It renders the following:

<title>Index * Landing Page * ApplicationName</title>
<meta name="description" content="Lorem ipsum set2" />

If last argument is Hash, a appropriate method will be called

class ApplicationController < ActionController::Base
  meta_for(:title, :generate_title)

  private

  def generate_title
    'Application Name'
  end
end


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/page_meta_for.rb', line 57

def meta_for(*keys, &block)
  content_proc = if block_given?
                   block
                 else
                   c = keys.pop
                   c.is_a?(Hash) ? proc { send(c) } : proc { c }
                 end

  keys = Array.wrap(keys).flatten
  key = keys.shift
  scope = keys.pop || :value

  before_action do
    @page_meta_for ||= {}
    @page_meta_for[key] ||= {}
    @page_meta_for[key][scope] = instance_exec(&content_proc).presence || nil
  end
end