Module: Snails::SimpleFormat

Included in:
Mailer
Defined in:
lib/snails/util.rb

Instance Method Summary collapse

Instance Method Details

#simple_format(text, options = {}) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
# File 'lib/snails/util.rb', line 61

def simple_format(text, options = {})
  t = options.delete(:tag) || :p
  start_tag = tag(t, options, true)
  text = text.to_s.dup
  text.gsub!(/\r\n?/, "\n")                      # \r\n and \r -> \n
  text.gsub!(/\n\n+/, "</#{t}>\n\n#{start_tag}") # 2+ newline  -> paragraph
  text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />')   # 1 newline   -> br
  text.insert 0, start_tag
  text << "</#{t}>"
  text
end

#tag(name, options = nil, open = false) ⇒ Object



47
48
49
50
# File 'lib/snails/util.rb', line 47

def tag(name, options = nil, open = false)
  attributes = tag_attributes(options)
  "<#{name}#{attributes}#{open ? '>' : ' />'}"
end

#tag_attributes(options) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/snails/util.rb', line 52

def tag_attributes(options)
  return '' unless options
  options.inject('') do |all,(key,value)|
    next all unless value
    all << ' ' if all.empty?
    all << %(#{key}="#{value}" )
  end.chomp!(' ')
end