class Forme::Serializer
Default serializer class used by the library. Any other serializer classes that want to produce html should probably subclass this class.
Registered as :default.
Constants
- SELF_CLOSING
Which tags are self closing (such tags ignore children).
Public Instance Methods
Serialize the tag object to an html string. Supports Tag
instances, Input
instances (recursing into call
with the result of formatting the input), arrays (recurses into call
for each entry and joins the result), and (html escapes the string version of them, unless they include the Raw
module, in which case no escaping is done).
# File lib/forme/transformers/serializer.rb 19 def call(tag) 20 case tag 21 when Tag 22 if SELF_CLOSING.include?(tag.type) 23 "<#{tag.type}#{attr_html(tag.attr)}/>" 24 else 25 "#{serialize_open(tag)}#{call(tag.children)}#{serialize_close(tag)}" 26 end 27 when Input 28 call(tag.format) 29 when Array 30 tag.map{|x| call(x)}.join 31 when DateTime, Time 32 format_time(tag) 33 when Date 34 format_date(tag) 35 when BigDecimal 36 tag.to_s('F') 37 when Raw 38 tag.to_s 39 else 40 Forme.h(tag) 41 end 42 end
Returns the closing part of the given tag.
# File lib/forme/transformers/serializer.rb 50 def serialize_close(tag) 51 "</#{tag.type}>" 52 end
Returns the opening part of the given tag.
# File lib/forme/transformers/serializer.rb 45 def serialize_open(tag) 46 "<#{tag.type}#{attr_html(tag.attr)}>" 47 end
Private Instance Methods
Transforms the tag
‘s attributes into an html string, sorting by the keys and quoting and html escaping the values.
# File lib/forme/transformers/serializer.rb 78 def attr_html(attr) 79 attr = attr.to_a.reject{|k,v| v.nil?} 80 " #{attr.map{|k, v| "#{k}=\"#{attr_value(v)}\""}.sort.join(' ')}" unless attr.empty? 81 end
Join attribute values that are arrays with spaces instead of an empty string.
# File lib/forme/transformers/serializer.rb 68 def attr_value(v) 69 if v.is_a?(Array) 70 v.map{|c| attr_value(c)}.join(' ') 71 else 72 call(v) 73 end 74 end
Return a string in ISO format representing the Date
instance.
# File lib/forme/transformers/serializer.rb 57 def format_date(date) 58 date.strftime("%F") 59 end
Return a string in ISO format representing the Time
or DateTime
instance.
# File lib/forme/transformers/serializer.rb 62 def format_time(time) 63 time.is_a?(Time) ? (time.strftime('%Y-%m-%dT%H:%M:%S') + sprintf(".%03d", time.usec)) : (time.strftime('%Y-%m-%dT%H:%M:%S.') + time.strftime('%N')[0...3]) 64 end