Module: Snails::SimpleFormat

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

Instance Method Summary collapse

Instance Method Details

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



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/snails/util.rb', line 57

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



43
44
45
46
# File 'lib/snails/util.rb', line 43

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

#tag_attributes(options) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/snails/util.rb', line 48

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