Class: SingleTag

Inherits:
Object
  • Object
show all
Defined in:
lib/objective_elements/single_tag.rb

Overview

Collection of HTML element tags Describes a basic, self-closing HTML tag.

Direct Known Subclasses

DoubleTag

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(element, attributes: nil) ⇒ SingleTag

Attributes are a hash. Keys are symbols, values are arrays. Will render as key=“value1 value2 value3”



12
13
14
15
# File 'lib/objective_elements/single_tag.rb', line 12

def initialize(element, attributes: nil)
  @element = element
  reset_attributes(attributes)
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



4
5
6
# File 'lib/objective_elements/single_tag.rb', line 4

def attributes
  @attributes
end

#elementObject

Returns the value of attribute element.



5
6
7
# File 'lib/objective_elements/single_tag.rb', line 5

def element
  @element
end

Instance Method Details

#add_attributes(new) ⇒ Object Also known as: add_attribute

This is the only way we add new attributes. Flexible about what you give it– accepts both strings and symbols for the keys, and both strings and arrays for the values.



27
28
29
30
31
32
33
# File 'lib/objective_elements/single_tag.rb', line 27

def add_attributes(new)
  if new.is_a? String
    add_string_attributes(new)
  else
    add_hash_attributes(new)
  end
end

#add_parent(parent) ⇒ Object

Returns parent, with self added as a child



46
47
48
# File 'lib/objective_elements/single_tag.rb', line 46

def add_parent(parent)
  parent.add_content(self)
end

#opening_tagObject



50
51
52
53
54
# File 'lib/objective_elements/single_tag.rb', line 50

def opening_tag
  output =  '<' + @element
  output << ' ' + render_attributes unless @attributes.empty?
  output << '>'
end

#render_attributesObject

Turns attributes into a string we can insert.



37
38
39
40
41
42
43
# File 'lib/objective_elements/single_tag.rb', line 37

def render_attributes
  attribute_string = ''
  @attributes.each_pair do |k, v|
    attribute_string << "#{k}=\"#{v.join ' '}\" "
  end
  attribute_string.strip
end

#reset_attributes(new = nil) ⇒ Object

Deletes all current attributes, overwrites them with supplied hash.



18
19
20
21
# File 'lib/objective_elements/single_tag.rb', line 18

def reset_attributes(new = nil)
  @attributes = {}
  add_attributes(new) if new
end

#to_aObject



56
57
58
# File 'lib/objective_elements/single_tag.rb', line 56

def to_a
  [opening_tag]
end

#to_sObject

Renders our HTML.



61
62
63
# File 'lib/objective_elements/single_tag.rb', line 61

def to_s
  opening_tag + "\n"
end