Skip to content

Commit

Permalink
Support variants with dots in their names (#1585)
Browse files Browse the repository at this point in the history
This follows the same principles as commit 95ceed1. Quoting that
commit:

> ViewComponent defines variant method calls with `def
> call_#{variant}`, which results in invalid Ruby code when the variant
> contains a [dash or dot].

Replacing dots with triple underscores in the method definition (similar
to what Bundler does when converting hostnames to environment variables
[1]) and modifying the code getting the variant so it includes dots in
the variant name solves the issue.

[1] https://bundler.io/man/bundle-config.1.html#CONFIGURE-BUNDLER-DIRECTORIES
  • Loading branch information
javierm authored Nov 23, 2022
1 parent e1b9b47 commit 4f2c93c
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 4 deletions.
4 changes: 4 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ nav_order: 5

## main

* Support variants with dots in their names.

*Javi Martín*

## 2.77.0

* Support variants with dashes in their names.
Expand Down
4 changes: 2 additions & 2 deletions lib/view_component/compiler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def templates
pieces = File.basename(path).split(".")
memo << {
path: path,
variant: pieces.second.split("+").second&.to_sym,
variant: pieces[1..-2].join(".").split("+").second&.to_sym,
handler: pieces.last
}
end
Expand Down Expand Up @@ -254,7 +254,7 @@ def call_method_name(variant)
end

def normalized_variant_name(variant)
variant.to_s.gsub("-", "__")
variant.to_s.gsub("-", "__").gsub(".", "___")
end

def should_compile_superclass?
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Mini Watch
Mini Watch with dash
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Mini Watch with dot
10 changes: 9 additions & 1 deletion test/sandbox/test/rendering_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,15 @@ def test_renders_component_with_variant_containing_a_dash
with_variant :"mini-watch" do
render_inline(VariantsComponent.new)

assert_text("Mini Watch")
assert_text("Mini Watch with dash")
end
end

def test_renders_component_with_variant_containing_a_dot
with_variant :"mini.watch" do
render_inline(VariantsComponent.new)

assert_text("Mini Watch with dot")
end
end

Expand Down

0 comments on commit 4f2c93c

Please sign in to comment.