Module: Spark::Component::Element

Included in:
Base
Defined in:
lib/spark/component/element.rb

Defined Under Namespace

Modules: ClassMethods Classes: Base, Error

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/spark/component/element.rb', line 10

def self.included(base)
  base.extend(Spark::Component::Element::ClassMethods)

  %i[_name _parent _block view_context].each do |name|
    base.define_method(:"#{name}=") { |val| instance_variable_set(:"@#{name}", val) }
    base.define_method(:"#{name}")  { instance_variable_get(:"@#{name}") }
  end
end

Instance Method Details

#blank?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/spark/component/element.rb', line 66

def blank?
  self.yield.nil? || self.yield.strip.empty?
end

#initialize(attrs = nil) ⇒ Object

Initialize method on components must call super



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/spark/component/element.rb', line 20

def initialize(attrs = nil)
  # Extract core element attributes
  # Ensure that elements have references to their:
  #  - parent: enables elements to interact with their parent component
  #  - block: used in render_self
  #  - view_context, sets the view context for an element (in Rails)
  #
  unless attrs.nil? || attrs.empty?
    @_name        = attrs.delete(:_name)
    @_parent      = attrs.delete(:_parent)
    @_block       = attrs.delete(:_block)
    @view_context = attrs.delete(:_view)
  end

  initialize_elements

  # Call Attributes.initialze
  super
end

#present?Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/spark/component/element.rb', line 62

def present?
  !blank?
end

#render_block(view, &block) ⇒ Object



54
55
56
# File 'lib/spark/component/element.rb', line 54

def render_block(view, &block)
  block_given? ? view.capture(self, &block) : nil
end

#render_selfObject



40
41
42
43
44
45
46
47
48
# File 'lib/spark/component/element.rb', line 40

def render_self
  # Guard with `rendered?` boolean in case render_block returns `nil`
  return @render_self if rendered?

  @render_self = render_block(@view_context, &_block)
  validate! if defined?(ActiveModel::Validations)
  @rendered = true
  @render_self
end

#rendered?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/spark/component/element.rb', line 50

def rendered?
  @rendered == true
end

#yieldObject



58
59
60
# File 'lib/spark/component/element.rb', line 58

def yield
  render_self
end