Class: ElementalComponents::Element

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/elemental_components/element.rb

Direct Known Subclasses

Component

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(view, attributes = nil) ⇒ Element

Returns a new instance of Element.



70
71
72
73
74
75
76
# File 'lib/elemental_components/element.rb', line 70

def initialize(view, attributes = nil, &)
  @view = view
  initialize_attributes(attributes || {})
  initialize_elements
  @yield = block_given? ? @view.capture(self, &) : nil
  validate!
end

Class Method Details

.attribute(name, default: nil) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/elemental_components/element.rb', line 15

def self.attribute(name, default: nil)
  attributes[name] = { default: default }

  define_method_or_raise(name) do
    get_instance_variable(name)
  end
end

.attributesObject



11
12
13
# File 'lib/elemental_components/element.rb', line 11

def self.attributes
  @attributes ||= {}
end

.element(name, multiple: false, &config) ⇒ Object

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/MethodLength rubocop:disable Metrics/PerceivedComplexity



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
# File 'lib/elemental_components/element.rb', line 31

def self.element(name, multiple: false, &config)
  plural_name = name.to_s.pluralize.to_sym if multiple

  elements[name] = {
    multiple: plural_name || false, class: Class.new(Element, &config)
  }

  define_method_or_raise(name) do |attributes = nil, &block|
    return get_instance_variable(multiple ? plural_name : name) unless attributes || block

    element = self.class.elements[name][:class].new(@view, attributes, &block)

    if multiple
      get_instance_variable(plural_name) << element
    else
      set_instance_variable(name, element)
    end
  end

  return if !multiple || name == plural_name

  define_method_or_raise(plural_name) do
    get_instance_variable(plural_name)
  end
end

.elementsObject



23
24
25
# File 'lib/elemental_components/element.rb', line 23

def self.elements
  @elements ||= {}
end

.model_nameObject



7
8
9
# File 'lib/elemental_components/element.rb', line 7

def self.model_name
  ActiveModel::Name.new(ElementalComponents::Element)
end

Instance Method Details

#contentObject



82
83
84
# File 'lib/elemental_components/element.rb', line 82

def content
  @yield
end

#content?Boolean

Returns:



78
79
80
# File 'lib/elemental_components/element.rb', line 78

def content?
  content.present?
end