Class: ViewComponent::Compiler

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(component_class) ⇒ Compiler

Returns a new instance of Compiler.



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

def initialize(component_class)
  @component_class = component_class
  @__vc_compiler_lock = Monitor.new
end

Instance Attribute Details

#__vc_compiler_lockObject (readonly)

Lock required to be obtained before compiling the component



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

def __vc_compiler_lock
  @__vc_compiler_lock
end

Instance Method Details

#compile(raise_errors: false) ⇒ Object



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
69
70
71
72
73
# File 'lib/view_component/compiler.rb', line 17

def compile(raise_errors: false)
  return if compiled?

  __vc_compiler_lock.synchronize do
    CompileCache.invalidate_class!(component_class)

    subclass_instance_methods = component_class.instance_methods(false)

    if subclass_instance_methods.include?(:with_content) && raise_errors
      raise ViewComponent::ComponentError.new(
        "#{component_class} implements a reserved method, `#with_content`.\n\n" \
        "To fix this issue, change the name of the method."
      )
    end

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

      return false
    end

    if subclass_instance_methods.include?(:before_render_check)
      ActiveSupport::Deprecation.warn(
        "`#before_render_check` will be removed in v3.0.0.\n\n" \
        "To fix this issue, use `#before_render` instead."
      )
    end

    if raise_errors
      component_class.validate_initialization_parameters!
      component_class.validate_collection_parameter!
    end

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

      if component_class.instance_methods.include?(method_name.to_sym)
        component_class.send(:undef_method, method_name.to_sym)
      end

      component_class.class_eval "        def \#{method_name}\n          @output_buffer = ActionView::OutputBuffer.new\n          \#{compiled_template(template[:path])}\n        end\n      RUBY\n    end\n\n    define_render_template_for\n\n    component_class._after_compile\n\n    CompileCache.register(component_class)\n  end\nend\n", template[:path], -1

#compiled?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/view_component/compiler.rb', line 13

def compiled?
  CompileCache.compiled?(component_class)
end