Class: ViewComponent::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/view_component/compiler.rb

Instance Method Summary collapse

Constructor Details

#initialize(component_class) ⇒ Compiler

Returns a new instance of Compiler.



5
6
7
# File 'lib/view_component/compiler.rb', line 5

def initialize(component_class)
  @component_class = component_class
end

Instance Method Details

#compile(raise_errors: false) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/view_component/compiler.rb', line 13

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 component_class.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.
  component_class.remove_possible_singleton_method(:collection_parameter)
  component_class.remove_possible_singleton_method(:collection_counter_parameter)
  component_class.remove_possible_singleton_method(:counter_argument_present?)

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

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

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

  component_class.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])
    component_class.send(:undef_method, method_name.to_sym) if component_class.instance_methods.include?(method_name.to_sym)

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

  define_render_template_for

  CompileCache.register(component_class)
end

#compiled?Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/view_component/compiler.rb', line 9

def compiled?
  CompileCache.compiled?(component_class)
end