Class: ViewComponent::Template

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

Direct Known Subclasses

File, Inline, InlineCall

Defined Under Namespace

Classes: DataWithSource, File, Inline, InlineCall

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(component:, details:, lineno: nil, path: nil) ⇒ Template

Returns a new instance of Template.



15
16
17
18
19
20
# File 'lib/view_component/template.rb', line 15

def initialize(component:, details:, lineno: nil, path: nil)
  @component = component
  @details = details
  @lineno = lineno
  @path = path
end

Instance Attribute Details

#detailsObject (readonly)

Returns the value of attribute details.



10
11
12
# File 'lib/view_component/template.rb', line 10

def details
  @details
end

#pathObject (readonly)

Returns the value of attribute path.



10
11
12
# File 'lib/view_component/template.rb', line 10

def path
  @path
end

Instance Method Details

#call_method_nameObject



130
131
132
133
134
# File 'lib/view_component/template.rb', line 130

def call_method_name
  @call_method_name ||=
    ["call", (normalized_variant_name if variant.present?), (format unless default_format?)]
      .compact.join("_").to_sym
end

#compile_to_componentObject



97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/view_component/template.rb', line 97

def compile_to_component
  @component.silence_redefinition_of_method(call_method_name)

  # rubocop:disable Style/EvalWithLocation
  @component.class_eval <<~RUBY, @path, @lineno - 1
    def #{call_method_name}
      @view_context.instance_variable_set(:@virtual_path, virtual_path)
      #{compiled_source}
    end
  RUBY
  # rubocop:enable Style/EvalWithLocation

  @component.define_method(safe_method_name, @component.instance_method(@call_method_name))
end

#default_format?Boolean Also known as: html?

Returns:

  • (Boolean)


125
126
127
# File 'lib/view_component/template.rb', line 125

def default_format?
  format.nil? || format == DEFAULT_FORMAT
end

#inline_call?Boolean

Returns:

  • (Boolean)


121
122
123
# File 'lib/view_component/template.rb', line 121

def inline_call?
  type == :inline_call
end

#normalized_variant_nameObject



140
141
142
# File 'lib/view_component/template.rb', line 140

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

#requires_compiled_superclass?Boolean

Returns:

  • (Boolean)


117
118
119
# File 'lib/view_component/template.rb', line 117

def requires_compiled_superclass?
  inline_call? && !defined_on_self?
end

#safe_method_nameObject



136
137
138
# File 'lib/view_component/template.rb', line 136

def safe_method_name
  "_#{call_method_name}_#{@component.name.underscore.gsub("/", "__")}"
end

#safe_method_name_callObject



112
113
114
115
# File 'lib/view_component/template.rb', line 112

def safe_method_name_call
  m = safe_method_name
  proc { send(m) }
end