Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow render_elements to take a block #2321

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions app/helpers/alchemy/elements_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ module ElementsHelper
# A class instance that will return elements that get rendered.
# Use this for your custom element loading logic in views.
#
def render_elements(options = {})
def render_elements(options = {}, &blk)
options = {
from_page: @page,
render_format: "html",
Expand All @@ -86,11 +86,12 @@ def render_elements(options = {})

elements = finder.elements(page_version: page_version)

buff = []
elements.each_with_index do |element, i|
buff << render_element(element, options, i + 1)
end
buff.join(options[:separator]).html_safe
default_rendering = ->(element, i) { render_element(element, options, i + 1) }
if block_given?
elements.map.with_index(&blk)
else
elements.map.with_index(&default_rendering)
end.join(options[:separator]).html_safe
end

# This helper renders a {Alchemy::Element} view partial.
Expand Down
12 changes: 12 additions & 0 deletions spec/helpers/alchemy/elements_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,18 @@ module Alchemy
end
end

context "with a block" do
subject do
helper.render_elements(separator: ", ") do |element|
element.name
end
end

it "renders the block" do
is_expected.to eq("headline, article")
end
end

context "with from_page option" do
context "is a page object" do
let(:another_page) { create(:alchemy_page, :public) }
Expand Down