Skip to content

Commit

Permalink
clearer control flow
Browse files Browse the repository at this point in the history
  • Loading branch information
joelhawksley committed Aug 26, 2024
1 parent eee9aec commit 1331e41
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/view_component/compiler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ def renders_template_for_variant?(variant)

def define_render_template_for
branches = []
default_method_name = "_call_#{safe_class_name}"

templates.each do |template|
safe_name = +"_call"
Expand All @@ -115,7 +116,16 @@ def define_render_template_for
safe_name << "_#{template[:format]}" if template[:format].present? && template[:format] != :html
safe_name << "_#{safe_class_name}"

component_class.define_method(safe_name, component_class.instance_method(call_method_name(template[:variant], template[:format])))
if safe_name == default_method_name
next
else
component_class.define_method(
safe_name,
component_class.instance_method(
call_method_name(template[:variant], template[:format])
)
)
end

format_conditional =
if template[:format] == :html
Expand All @@ -141,8 +151,6 @@ def define_render_template_for
branches << ["variant&.to_sym == :'#{variant}'", safe_name]
end

default_method_name = "_call_#{safe_class_name}"

component_class.define_method(:"#{default_method_name}", component_class.instance_method(:call))

# Just use default method name if no conditional branches or if there is a single
Expand All @@ -153,8 +161,6 @@ def define_render_template_for
body = +""

branches.each do |conditional, method_body|
next if method_body == default_method_name

body << "#{!body.present? ? "if" : "elsif"} #{conditional}\n #{method_body}\n"
end

Expand Down

0 comments on commit 1331e41

Please sign in to comment.