Method: Hash#to_style_attr

Defined in:
lib/html_attributes/hash.rb

#to_style_attrObject

Returns a string containing a style attribute, or returns nil if no values remains.

Examples

{ :padding => { :top => "8px", :right => "15px" }, :font_size => "12pt" }.to_style_attr
# => "font-size: 12pt; padding-right: 15px; padding-top: 8px;"

visible = true
{ :display => visible ? nil : 'none' }.to_style_attr
# => nil


50
51
52
53
54
55
56
# File 'lib/html_attributes/hash.rb', line 50

def to_style_attr
  self.flatten { |keys| keys.join('_').gsub('_', '-') }.  # build CSS like key names
       select { |key, value| !value.nil? }.               # remove properties with nil value
       map { |key, value| "#{key}: #{value}" }.           # build property
       sort.                                              # sort alphabetically
       to_style_attr                                      # join with '; ' or return nil if empty
end