Class: Ruby::Tags::Attribute

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Attribute

Returns a new instance of Attribute.



9
10
11
# File 'lib/ruby/tags/attribute.rb', line 9

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

Class Method Details

.blank?(s) ⇒ Boolean

Returns:

  • (Boolean)


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

def self.blank?(s)
  s.nil? || s.to_s.strip.empty? || s.empty?
end

Instance Method Details

#==(other) ⇒ Object



45
46
47
48
# File 'lib/ruby/tags/attribute.rb', line 45

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

#add(attribute) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/ruby/tags/attribute.rb', line 13

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



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ruby/tags/attribute.rb', line 27

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



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

def render
  @attributes.reject{ |k,v| [k,v].any? { |x| Attribute.blank? x } }
             .reduce(@attributes.empty? && "" || " ") { |m, (k, a)| "#{m}#{k}='#{sanitize(a)}' " }
             .delete_suffix(" ")
end