Skip to content

Instantly share code, notes, and snippets.

@hiroshi
Created May 22, 2011 13:23
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save hiroshi/985457 to your computer and use it in GitHub Desktop.
Save hiroshi/985457 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
...
# FORCE to implement content_for in controller
def view_context
super.tap do |view|
(@_content_for || {}).each do |name,content|
view.content_for name, content
end
end
end
def content_for(name, content) # no blocks allowed yet
@_content_for ||= {}
if @_content_for[name].respond_to?(:<<)
@_content_for[name] << content
else
@_content_for[name] = content
end
end
def content_for?(name)
@_content_for[name].present?
end
end
class PostsController < ApplicationController
def index
content_for :title, "List of posts"
...
end
end
@phil-monroe
Copy link

Sorry to stir up an old topic, but what about memoizing the view_context? Will that cause other issues? Seems to work for me in rails 4.

  def view_context
    @view_context ||= super
  end
  delegate :content_for, to: :view_context

EDIT
Found out real quick: Don't do this, it breaks instance variable assignment...

@itkin
Copy link

itkin commented Feb 14, 2017

seems broken on rails 4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment