From cc9862e70ca695112676d48b11e6600773d28e23 Mon Sep 17 00:00:00 2001 From: Bogdanov Anton Date: Tue, 15 Oct 2024 01:48:04 +0300 Subject: [PATCH] feature: partial! api for rendering partials without setting to key (#34) --- README.md | 7 +++++ lib/props_template.rb | 1 + lib/props_template/base.rb | 4 +++ spec/props_template_spec.rb | 60 +++++++++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+) diff --git a/README.md b/README.md index 6c01382..745575c 100644 --- a/README.md +++ b/README.md @@ -337,6 +337,13 @@ json.posts do end ``` +Usage for rendering partial without assigning it to some key: + +```ruby +json.partial! partial: "posts/blog_post", locals: {post: @post} do +end +``` + ### Partial Fragments **Note** This is a [SuperglueJS][1] specific functionality. diff --git a/lib/props_template.rb b/lib/props_template.rb index be82229..9016637 100644 --- a/lib/props_template.rb +++ b/lib/props_template.rb @@ -22,6 +22,7 @@ class << self self.template_lookup_options = {handlers: [:props]} delegate :result!, :array!, + :partial!, :extract!, :deferred!, :fragments!, diff --git a/lib/props_template/base.rb b/lib/props_template/base.rb index 306b5c4..3fcf673 100644 --- a/lib/props_template/base.rb +++ b/lib/props_template/base.rb @@ -105,6 +105,10 @@ def array!(collection, options = {}) nil end + def partial!(**options) + @context.render options + end + # json.id item.id # json.value item.value # diff --git a/spec/props_template_spec.rb b/spec/props_template_spec.rb index baf39d5..b9fd6f6 100644 --- a/spec/props_template_spec.rb +++ b/spec/props_template_spec.rb @@ -297,6 +297,66 @@ end end + context "partial!" do + it "renders with a partial" do + json = render(<<~PROPS) + json.partial! partial: 'simple' + PROPS + + expect(json).to eql_json({ + foo: "bar" + }) + end + + it "renders with locale" do + json = render(<<~PROPS) + json.partial! partial: 'simple', locale: :de + PROPS + + expect(json).to eql_json({ + foo: "Kein" + }) + end + + it "renders with variants" do + json = render(<<~PROPS) + json.partial! partial: 'simple', variants: :grid + PROPS + + expect(json).to eql_json({ + foo: "Grid" + }) + end + + it "renders with a partial with locals" do + json = render(<<~PROPS) + json.partial! partial: 'profile', locals: {email: 'joe@joe.com'} + PROPS + + expect(json).to eql_json({ + email: "joe@joe.com" + }) + end + + it "renders an array of partials" do + json = render(<<~PROPS) + emails = [ + 'joe@j.com', + 'foo@f.com', + ] + + json.array! emails do |email| + json.partial! partial: 'profile', locals: {email: email} + end + PROPS + + expect(json).to eql_json([ + {email: "joe@j.com"}, + {email: "foo@f.com"} + ]) + end + end + context "extract!" do it "extracts values for hash" do object = { :foo => "bar", "bar" => "foo", :wiz => "wiz" }