Class: Ruby::Tags::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby/tags/attribute.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Attribute

Returns a new instance of Attribute.



5
6
7
# File 'lib/ruby/tags/attribute.rb', line 5

def initialize(attributes = {})
  @attributes = attributes.to_h { |k,v| [k, v.to_s.split] }
end

Instance Method Details

#==(other) ⇒ Object



41
42
43
44
# File 'lib/ruby/tags/attribute.rb', line 41

def ==(other)
  @attributes.keys.sort == var(other).keys.sort &&
  @attributes.values.flatten.sort == var(other).values.flatten.sort
end

#add(attribute) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/ruby/tags/attribute.rb', line 9

def add(attribute)
  if attribute.is_a? Hash
    attribute.each do |k, v|
      key = k&.to_sym
      @attributes[key] = [] unless @attributes[key]
      enum(v).each do |e|
        @attributes[key] << e unless @attributes[key].include? e
      end
    end
  end
  add var(attribute) if attribute.is_a? Attribute
  self
end

#remove(attribute) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/ruby/tags/attribute.rb', line 23

def remove(attribute)
  if attribute.is_a? Hash
    attribute.each do |k, v|
      key = k&.to_sym
      enum(v).each { |e| @attributes[key].delete e } if @attributes[key]
    end
  end
  remove var(attribute) if attribute.is_a? Attribute
  @attributes.delete attribute if [String, Symbol].any? { |x| attribute.is_a? x }
  self
end

#renderObject



35
36
37
38
39
# File 'lib/ruby/tags/attribute.rb', line 35

def render
  @attributes.reject{ |k, _| blank? k }
             .reduce(@attributes.empty? && "" || " ") { |m, (k, a)| "#{m}#{k}='#{sanitize(a)}' " }
             .delete_suffix(" ")
end