Skip to content

Commit

Permalink
Merge pull request #1225 from iguchi1124/flush-content-for
Browse files Browse the repository at this point in the history
Add flush option for Sinatra::ContentFor flush content
  • Loading branch information
namusyaka committed Dec 21, 2018
2 parents d83845e + d75c242 commit 84b290a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
10 changes: 7 additions & 3 deletions sinatra-contrib/lib/sinatra/content_for.rb
Expand Up @@ -128,9 +128,12 @@ module ContentFor
#
# Your blocks can also receive values, which are passed to them
# by <tt>yield_content</tt>
def content_for(key, value = nil, &block)
def content_for(key, value = nil, options = {}, &block)
key = key.to_sym

block ||= proc { |*| value }
content_blocks[key.to_sym] << capture_later(&block)
clear_content_for(key) if options[:flush]
content_blocks[key] << capture_later(&block)
end

# Check if a block of content with the given key was defined. For
Expand Down Expand Up @@ -172,10 +175,11 @@ def clear_content_for(key)
# Would pass <tt>1</tt> and <tt>2</tt> to all the blocks registered
# for <tt>:head</tt>.
def yield_content(key, *args, &block)
key = key.to_sym
if block_given? && !content_for?(key)
haml? ? capture_haml(*args, &block) : yield(*args)
else
content = content_blocks[key.to_sym].map { |b| capture(*args, &b) }
content = content_blocks[key].map { |b| capture(*args, &b) }
content.join.tap do |c|
if block_given? && (erb? || erubi? || erubis?)
@_out_buf << c
Expand Down
16 changes: 16 additions & 0 deletions sinatra-contrib/spec/content_for_spec.rb
Expand Up @@ -70,6 +70,22 @@ def render(engine, template)
content_for(:foo, "foo")
expect(yield_content(:foo)).to eq("foo")
end

context 'when flush option was disabled' do
it 'append content' do
content_for(:foo, "foo")
content_for(:foo, "bar")
expect(yield_content(:foo)).to eq("foobar")
end
end

context 'when flush option was enabled' do
it 'flush first content' do
content_for(:foo, "foo")
content_for(:foo, "bar", flush: true)
expect(yield_content(:foo)).to eq("bar")
end
end
end

# TODO: liquid radius markaby builder nokogiri
Expand Down

0 comments on commit 84b290a

Please sign in to comment.