Skip to content

Commit 84b290a

Browse files
authored
Merge pull request sinatra#1225 from iguchi1124/flush-content-for
Add flush option for Sinatra::ContentFor flush content
2 parents d83845e + d75c242 commit 84b290a

File tree

2 files changed

+23
-3
lines changed

2 files changed

+23
-3
lines changed

sinatra-contrib/lib/sinatra/content_for.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,12 @@ module ContentFor
128128
#
129129
# Your blocks can also receive values, which are passed to them
130130
# by <tt>yield_content</tt>
131-
def content_for(key, value = nil, &block)
131+
def content_for(key, value = nil, options = {}, &block)
132+
key = key.to_sym
133+
132134
block ||= proc { |*| value }
133-
content_blocks[key.to_sym] << capture_later(&block)
135+
clear_content_for(key) if options[:flush]
136+
content_blocks[key] << capture_later(&block)
134137
end
135138

136139
# Check if a block of content with the given key was defined. For
@@ -172,10 +175,11 @@ def clear_content_for(key)
172175
# Would pass <tt>1</tt> and <tt>2</tt> to all the blocks registered
173176
# for <tt>:head</tt>.
174177
def yield_content(key, *args, &block)
178+
key = key.to_sym
175179
if block_given? && !content_for?(key)
176180
haml? ? capture_haml(*args, &block) : yield(*args)
177181
else
178-
content = content_blocks[key.to_sym].map { |b| capture(*args, &b) }
182+
content = content_blocks[key].map { |b| capture(*args, &b) }
179183
content.join.tap do |c|
180184
if block_given? && (erb? || erubi? || erubis?)
181185
@_out_buf << c

sinatra-contrib/spec/content_for_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,22 @@ def render(engine, template)
7070
content_for(:foo, "foo")
7171
expect(yield_content(:foo)).to eq("foo")
7272
end
73+
74+
context 'when flush option was disabled' do
75+
it 'append content' do
76+
content_for(:foo, "foo")
77+
content_for(:foo, "bar")
78+
expect(yield_content(:foo)).to eq("foobar")
79+
end
80+
end
81+
82+
context 'when flush option was enabled' do
83+
it 'flush first content' do
84+
content_for(:foo, "foo")
85+
content_for(:foo, "bar", flush: true)
86+
expect(yield_content(:foo)).to eq("bar")
87+
end
88+
end
7389
end
7490

7591
# TODO: liquid radius markaby builder nokogiri

0 commit comments

Comments
 (0)