Class: Spark::Component::Attr

Inherits:
Hash
  • Object
show all
Defined in:
lib/spark/component/attr.rb

Direct Known Subclasses

TagAttr

Instance Method Summary collapse

Constructor Details

#initialize(*args, prefix: nil) ⇒ Attr

Returns a new instance of Attr.



6
7
8
9
# File 'lib/spark/component/attr.rb', line 6

def initialize(*args, prefix: nil)
  super(*args)
  @prefix = prefix
end

Instance Method Details

#add(hash) ⇒ Object



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

def add(hash)
  return self if hash.nil? || hash.keys.empty?

  deep_compact!(hash)
  dasherize_keys(hash)
  merge!(hash)
  self
end

#to_sObject

Output all attributes as [prefix-]name=“value”



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/spark/component/attr.rb', line 21

def to_s
  each_with_object([]) do |(name, value), array|
    if value.is_a?(Component::Attr)
      # Flatten nested hashs and inject them unless empty
      value = value.to_s
      array << value unless value.empty?
    else
      name = [@prefix, name].compact.join("-").gsub(/[\W_]+/, "-")
      array << %(#{name}="#{value}") unless value.nil?
    end
  end.sort.join(" ")
end