Skip to content

Commit

Permalink
Merge pull request #501 from github/bmw/compiler
Browse files Browse the repository at this point in the history
Extract template compiler from base
  • Loading branch information
joelhawksley authored Oct 16, 2020
2 parents 88a6a0c + 27a0f87 commit eda4782
Show file tree
Hide file tree
Showing 4 changed files with 224 additions and 173 deletions.
1 change: 1 addition & 0 deletions lib/view_component.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ module ViewComponent
extend ActiveSupport::Autoload

autoload :Base
autoload :Compiler
autoload :Preview
autoload :PreviewTemplateError
autoload :TestHelpers
Expand Down
177 changes: 6 additions & 171 deletions lib/view_component/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def render_in(view_context, &block)
before_render

if render?
send(self.class.call_method_name(@variant))
render_template_for(@variant)
else
""
end
Expand Down Expand Up @@ -208,80 +208,20 @@ def inherited(child)
super
end

def call_method_name(variant)
if variant.present? && variants.include?(variant)
"call_#{variant}"
else
"call"
end
end

def compiled?
CompileCache.compiled?(self)
template_compiler.compiled?
end

# Compile templates to instance methods, assuming they haven't been compiled already.
#
# Do as much work as possible in this step, as doing so reduces the amount
# of work done each time a component is rendered.
def compile(raise_errors: false)
return if compiled?

if template_errors.present?
raise ViewComponent::TemplateError.new(template_errors) if raise_errors
return false
end

if instance_methods(false).include?(:before_render_check)
ActiveSupport::Deprecation.warn(
"`before_render_check` will be removed in v3.0.0. Use `before_render` instead."
)
end

# Remove any existing singleton methods,
# as Ruby warns when redefining a method.
remove_possible_singleton_method(:variants)
remove_possible_singleton_method(:collection_parameter)
remove_possible_singleton_method(:collection_counter_parameter)
remove_possible_singleton_method(:counter_argument_present?)

define_singleton_method(:variants) do
templates.map { |template| template[:variant] } + variants_from_inline_calls(inline_calls)
end

define_singleton_method(:collection_parameter) do
if provided_collection_parameter
provided_collection_parameter
else
name.demodulize.underscore.chomp("_component").to_sym
end
end

define_singleton_method(:collection_counter_parameter) do
"#{collection_parameter}_counter".to_sym
end

define_singleton_method(:counter_argument_present?) do
instance_method(:initialize).parameters.map(&:second).include?(collection_counter_parameter)
end

validate_collection_parameter! if raise_errors

templates.each do |template|
# Remove existing compiled template methods,
# as Ruby warns when redefining a method.
method_name = call_method_name(template[:variant])
undef_method(method_name.to_sym) if instance_methods.include?(method_name.to_sym)

class_eval <<-RUBY, template[:path], -1
def #{method_name}
@output_buffer = ActionView::OutputBuffer.new
#{compiled_template(template[:path])}
end
RUBY
end
template_compiler.compile(raise_errors: raise_errors)
end

CompileCache.register self
def template_compiler
@_template_compiler ||= Compiler.new(self)
end

# we'll eventually want to update this to support other types
Expand Down Expand Up @@ -346,111 +286,6 @@ def provided_collection_parameter
@provided_collection_parameter ||= nil
end

def compiled_template(file_path)
handler = ActionView::Template.handler_for_extension(File.extname(file_path).gsub(".", ""))
template = File.read(file_path)

if handler.method(:call).parameters.length > 1
handler.call(self, template)
else
handler.call(OpenStruct.new(source: template, identifier: identifier, type: type))
end
end

def inline_calls
@inline_calls ||=
begin
# Fetch only ViewComponent ancestor classes to limit the scope of
# finding inline calls
view_component_ancestors =
ancestors.take_while { |ancestor| ancestor != ViewComponent::Base } - included_modules

view_component_ancestors.flat_map { |ancestor| ancestor.instance_methods(false).grep(/^call/) }.uniq
end
end

def inline_calls_defined_on_self
@inline_calls_defined_on_self ||= instance_methods(false).grep(/^call/)
end

def matching_views_in_source_location
return [] unless source_location

location_without_extension = source_location.chomp(File.extname(source_location))

extensions = ActionView::Template.template_handler_extensions.join(",")

# view files in the same directory as the component
sidecar_files = Dir["#{location_without_extension}.*{#{extensions}}"]

# view files in a directory named like the component
directory = File.dirname(source_location)
filename = File.basename(source_location, ".rb")
component_name = name.demodulize.underscore

sidecar_directory_files = Dir["#{directory}/#{component_name}/#{filename}.*{#{extensions}}"]

(sidecar_files - [source_location] + sidecar_directory_files)
end

def templates
@templates ||=
matching_views_in_source_location.each_with_object([]) do |path, memo|
pieces = File.basename(path).split(".")

memo << {
path: path,
variant: pieces.second.split("+").second&.to_sym,
handler: pieces.last
}
end
end

def template_errors
@template_errors ||=
begin
errors = []

if (templates + inline_calls).empty?
errors << "Could not find a template file or inline render method for #{self}."
end

if templates.count { |template| template[:variant].nil? } > 1
errors << "More than one template found for #{self}. There can only be one default template file per component."
end

invalid_variants = templates
.group_by { |template| template[:variant] }
.map { |variant, grouped| variant if grouped.length > 1 }
.compact
.sort

unless invalid_variants.empty?
errors << "More than one template found for #{'variant'.pluralize(invalid_variants.count)} #{invalid_variants.map { |v| "'#{v}'" }.to_sentence} in #{self}. There can only be one template file per variant."
end

if templates.find { |template| template[:variant].nil? } && inline_calls_defined_on_self.include?(:call)
errors << "Template file and inline render method found for #{self}. There can only be a template file or inline render method per component."
end

duplicate_template_file_and_inline_variant_calls =
templates.pluck(:variant) & variants_from_inline_calls(inline_calls_defined_on_self)

unless duplicate_template_file_and_inline_variant_calls.empty?
count = duplicate_template_file_and_inline_variant_calls.count

errors << "Template #{'file'.pluralize(count)} and inline render #{'method'.pluralize(count)} found for #{'variant'.pluralize(count)} #{duplicate_template_file_and_inline_variant_calls.map { |v| "'#{v}'" }.to_sentence} in #{self}. There can only be a template file or inline render method per variant."
end

errors
end
end

def variants_from_inline_calls(calls)
calls.reject { |call| call == :call }.map do |variant_call|
variant_call.to_s.sub("call_", "").to_sym
end
end
end

ActiveSupport.run_load_hooks(:view_component, self)
Expand Down
Loading

0 comments on commit eda4782

Please sign in to comment.