Class: Rubypivot::HtmlTag

Inherits:
Object
  • Object
show all
Defined in:
lib/rubypivot/html_tag.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tag_name, options = {}) ⇒ HtmlTag

Returns a new instance of HtmlTag.



3
4
5
6
7
# File 'lib/rubypivot/html_tag.rb', line 3

def initialize(tag_name, options = {})
  @tag_name = tag_name
  @options = options
  @class_strings = []
end

Class Method Details

.to_html(tag_name, options = {}) ⇒ Object



75
76
77
78
# File 'lib/rubypivot/html_tag.rb', line 75

def self.to_html(tag_name, options = {})
  instance = self.new(tag_name, body, options = {})
  instance.build(body)
end

Instance Method Details

#add_class(class_string) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/rubypivot/html_tag.rb', line 21

def add_class(class_string)
  if class_string
    class_string.to_s.split(/ +/).each do |str|
      next if str.nil? || @class_strings.include?(str)
      @class_strings << str
    end
  end
  self
end

#add_key(key, value) ⇒ Object



9
10
11
12
# File 'lib/rubypivot/html_tag.rb', line 9

def add_key(key, value)
  @options[key] = value
  self
end

#build(options = {}) ⇒ Object Also known as: to_html



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rubypivot/html_tag.rb', line 57

def build(options = {})
  res = open
  # res << "\n" unless options[:compact]
  if block_given?
    res << yield.to_s
    # res << "\n" unless options[:compact]
    res << close
    # res << "\n" unless options[:compact]
  elsif options[:body]
    res << options[:body]
    # res << "\n" unless options[:compact]
    res << close
    # res << "\n" unless options[:compact]
  end
  res
end

#build_classObject



31
32
33
34
# File 'lib/rubypivot/html_tag.rb', line 31

def build_class
  return '' if @class_strings.empty?
  " class=\"#{@class_strings.join(' ')}\""
end

#closeObject



53
54
55
# File 'lib/rubypivot/html_tag.rb', line 53

def close
  "</#{@tag_name}>"
end

#openObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rubypivot/html_tag.rb', line 36

def open
  add_class(@options[:class])
  res = "<#{@tag_name}"
  res << build_class
  @options.each do |key, value|
    next if value.nil?
    case key
    when :class
      # class was handled first
    else
      res << " #{key}=\"#{value}\""
    end
  end
  res << ">"
  res
end

#sanitize(value) ⇒ Object



14
15
16
17
18
19
# File 'lib/rubypivot/html_tag.rb', line 14

def sanitize(value)
  return nil unless value
  array = value.split(/ +/)
  array.uniq!
  array.join(" ")
end