Class: TinyComponent::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/tiny_component/base.rb

Direct Known Subclasses

TestComponent

Constant Summary collapse

COMPILED_CACHE =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#block_contentObject (readonly)

Returns the value of attribute block_content.



3
4
5
# File 'lib/tiny_component/base.rb', line 3

def block_content
  @block_content
end

Class Method Details

.compileObject



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/tiny_component/base.rb', line 26

def compile
  return if COMPILED_CACHE.include?(self)

  class_eval "    def render_template\n      eval(self.class.compiled_source)\n    end\n  RUBY\n\n  COMPILED_CACHE << self\nend\n", __FILE__, __LINE__ + 1

.compiled_sourceObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tiny_component/base.rb', line 46

def compiled_source
  extension = :erb
  template_format = :html
  source = File.read(path)

  handler = ActionView::Template.handler_for_extension(extension)
  this_source = source

  short_identifier = defined?(Rails.root) ? path.sub("#{Rails.root}/", "") : path
  type = ActionView::Template::Types[template_format]

  data = Struct.new(:format, :identifier, :short_identifier, :type, keyword_init: true)

  handler.call(
    data.new(format: template_format, identifier: path, short_identifier: short_identifier, type: type),
    this_source
  )
end

.component_nameObject



42
43
44
# File 'lib/tiny_component/base.rb', line 42

def component_name
  name.underscore.sub(/_component$/, "")
end

.pathObject



38
39
40
# File 'lib/tiny_component/base.rb', line 38

def path
  Rails.root.join("app/views/components/#{component_name}.html.erb").to_s
end

Instance Method Details

#render(options = {}, args = {}) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/tiny_component/base.rb', line 17

def render(options = {}, args = {}, &)
  if options.respond_to?(:render_in)
    options.render_in(self, &)
  else
    super
  end
end

#render_in(view_context, &block) ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'lib/tiny_component/base.rb', line 7

def render_in(view_context, &block)
  @view_context = view_context
  @output_buffer = ActionView::OutputBuffer.new

  @block_content = view_context.capture(&block) if block

  self.class.compile
  render_template
end