Class: Arbre::Html::Attributes

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/arbre/html/attributes.rb

Overview

HTML attributes hash. Behaves like a hash with some minor differences:

  • Indifferent access: everything is stored as strings, but also values.

  • Setting an attribute to true sets it to the name of the attribute, as per the HTML standard.

  • Setting an attribute to false or nil will remove it.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Attributes

Returns a new instance of Attributes.



12
13
14
15
# File 'lib/arbre/html/attributes.rb', line 12

def initialize(attributes = {})
  @attributes = {}
  update attributes
end

Class Method Details

.[](*args) ⇒ Object



17
18
19
# File 'lib/arbre/html/attributes.rb', line 17

def self.[](*args)
  Attributes.new(Hash[*args])
end

Instance Method Details

#==(other) ⇒ Object



52
53
54
# File 'lib/arbre/html/attributes.rb', line 52

def ==(other)
  to_hash == other.to_hash
end

#[](attribute) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/arbre/html/attributes.rb', line 21

def [](attribute)
  if attribute.to_s == 'class'
    @attributes['class'] ||= ClassList.new
  else
    @attributes[attribute.to_s]
  end
end

#[]=(attribute, value) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/arbre/html/attributes.rb', line 28

def []=(attribute, value)
  if attribute.to_s == 'class'
    if value.present?
      @attributes['class'] = ClassList.new(value)
    else
      remove 'class'
    end
  elsif value == true
    @attributes[attribute.to_s] = attribute.to_s
  elsif value
    @attributes[attribute.to_s] = value.to_s
  else
    remove attribute
  end
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/arbre/html/attributes.rb', line 56

def eql?(other)
  other.is_a?(Attributes) && self == other
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/arbre/html/attributes.rb', line 60

def has_key?(key)
  @attributes.has_key?(key.to_s)
end

#pairsObject



67
68
69
70
71
72
# File 'lib/arbre/html/attributes.rb', line 67

def pairs
  map do |name, value|
    next if name == 'class' && value.blank?
    "#{html_escape(name)}=\"#{html_escape(value)}\""
  end
end

#remove(attribute) ⇒ Object



44
45
46
# File 'lib/arbre/html/attributes.rb', line 44

def remove(attribute)
  @attributes.delete attribute.to_s
end

#to_hashObject



74
75
76
# File 'lib/arbre/html/attributes.rb', line 74

def to_hash
  @attributes
end

#to_sObject



78
79
80
# File 'lib/arbre/html/attributes.rb', line 78

def to_s
  pairs.join(' ').html_safe
end

#update(attributes) ⇒ Object



48
49
50
# File 'lib/arbre/html/attributes.rb', line 48

def update(attributes)
  attributes.each { |k, v| self[k] = v }
end