Class: HTML::AutoAttr

Inherits:
Object
  • Object
show all
Defined in:
lib/HTML/AutoAttr.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}, sorted = 0) ⇒ AutoAttr

expects the following arguments

* hash
    Contains attribute keys and values

* sorted
    Boolean. Whether or not to render attributes in alphabetical order.


14
15
16
17
# File 'lib/HTML/AutoAttr.rb', line 14

def initialize( hash = {}, sorted = 0 )
    @hash   = hash
    @sorted = sorted
end

Instance Attribute Details

#hashObject

Returns the value of attribute hash.



5
6
7
# File 'lib/HTML/AutoAttr.rb', line 5

def hash
  @hash
end

#sortedObject

Returns the value of attribute sorted.



5
6
7
# File 'lib/HTML/AutoAttr.rb', line 5

def sorted
  @sorted
end

Instance Method Details

#key(key) ⇒ Object

expects one argument: the key to scrub



43
44
45
46
47
# File 'lib/HTML/AutoAttr.rb', line 43

def key( key )
    key = key.gsub( /\s+/, '' )
    key = key.gsub( /["'>=\/]/, '' )
    return key
end

#rotate(array) ⇒ Object

expects one argument: the array to rotate

returns the first element before array is rotated



60
61
62
63
64
# File 'lib/HTML/AutoAttr.rb', line 60

def rotate( array )
    val = array.shift
    array.push( val )
    return val
end

#stringify(hash) ⇒ Object

expects one argument: the hash to ‘stringify’



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/HTML/AutoAttr.rb', line 68

def stringify( hash )

    keys = @sorted ? hash.keys.sort : hash.keys
    vals = keys.map{ |key|
        val = ''
        if hash[key].kind_of?( Array ) 
            val = rotate( hash[key] )
        elsif hash[key].kind_of?( Hash )
            val = @sorted ? hash[key].keys.sort[0] : hash[key].keys[0]
        else
            val = hash[key]
        end
        "#{key}: #{val}"
    }
    return vals.join( '; ' ) + (vals.length ? ';' : '')

end

#to_sObject

expects no arguments, emits string containing rendered key/value pairs



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/HTML/AutoAttr.rb', line 21

def to_s

    return '' unless @hash.kind_of?( Hash )
    keys = @sorted ? @hash.keys.sort : @hash.keys
    str  = ''
    seen = {}

    keys.each do |key|
        unless seen.has_key?( key )
            val = @hash[key]
            val = stringify( val )  if val.kind_of?( Hash )
            val = rotate( val )     if val.kind_of?( Array )
            str += sprintf( ' %s="%s"', key( key ), val( val ) )
        end
        seen[key] = 1
    end

    return str
end

#val(val) ⇒ Object

expects one argument: the value to scrub



50
51
52
53
54
# File 'lib/HTML/AutoAttr.rb', line 50

def val( val )
    return '' if val.to_s.match( /^\s+$/ )
    val = val.to_s.gsub( /"/, '' )
    return val
end