Skip to content

Commit

Permalink
Merge pull request #2049 from tvdeyen/build-new-contents-automatically
Browse files Browse the repository at this point in the history
Create new contents on demand
  • Loading branch information
tvdeyen authored Mar 22, 2021
2 parents 10b1747 + e7b8e14 commit 94190bb
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
25 changes: 25 additions & 0 deletions app/decorators/alchemy/element_editor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,17 @@ def to_partial_path
"alchemy/admin/elements/element"
end

# Returns content editor instances for defined contents
#
# Creates contents on demand if the content is not yet present on the element
#
# @return Array<Alchemy::ContentEditor>
def contents
element.definition.fetch(:contents, []).map do |content|
Alchemy::ContentEditor.new(find_or_create_content(content[:name]))
end
end

# CSS classes for the element editor partial.
def css_classes
[
Expand Down Expand Up @@ -78,5 +89,19 @@ def deprecation_notice
default: Alchemy.t(:element_deprecated))
end
end

private

def find_or_create_content(name)
find_content(name) || create_content(name)
end

def find_content(name)
element.contents.find { |content| content.name == name }
end

def create_content(name)
Alchemy::Content.create(element: element, name: name)
end
end
end
2 changes: 1 addition & 1 deletion app/views/alchemy/admin/elements/_element.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<div id="element_<%= element.id %>_errors" class="element_errors"></div>

<div id="element_<%= element.id %>_content" class="element-content-editors">
<%= render element.contents.map { |content| Alchemy::ContentEditor.new(content) } %>
<%= render element.contents %>
</div>

<% if element.taggable? %>
Expand Down
38 changes: 38 additions & 0 deletions spec/decorators/alchemy/element_editor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,44 @@
end
end

describe "#contents" do
let(:element) { create(:alchemy_element, :with_contents, name: "headline") }

subject(:contents) { element_editor.contents }

it "returns a ContentEditor instance for each content defined" do
aggregate_failures do
contents.each do |content|
expect(content).to be_an(Alchemy::ContentEditor)
end
end
end

context "with a content defined but not existing yet" do
before do
expect(element).to receive(:definition).at_least(:once) do
{
name: "headline",
contents: [
{
name: "headline",
type: "EssenceText",
},
{
name: "foo",
type: "EssenceText",
},
],
}.with_indifferent_access
end
end

it "creates the missing content" do
expect { subject }.to change { element.contents.count }.by(1)
end
end
end

describe "#to_partial_path" do
subject { element_editor.to_partial_path }

Expand Down

0 comments on commit 94190bb

Please sign in to comment.