Module: CorrespondenceMarkup::Helpers

Included in:
Item, NonItem
Defined in:
lib/correspondence-markup/types.rb

Overview

Helper functions used when generating HTML

Constant Summary collapse

TAGS_AND_TEXT_REGEX =

Either 1: a tag enclosed in “<” & “>”, possibly missing the “>”, or, 2: text outside a tag

/([<][^>]*[>]?)|([^<]+)/

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.split_tags_and_text(html) ⇒ Object

Split some HTML source into tags and plain text not in tags. (For example, so that the two can be processed differently, e.g. applying a transformation to text content where you don’t want the transformation to apply to the internals of directly-coded HTML tags.)



20
21
22
# File 'lib/correspondence-markup/types.rb', line 20

def self.split_tags_and_text(html)
  html.scan(TAGS_AND_TEXT_REGEX).to_a
end

Instance Method Details

#text_to_html(text, options) ⇒ Object

Convert text content into HTML according to various true/false options. Note: the text may contain HTML tags

  • :escaped - if true, HTML-escape the text

  • :br - if true, convert end-of-line characters to <br/> tags

  • :nbsp - if true, convert all spaces in the text that is not in tags into &nbsp;

Of these options, :escaped only makes sense if you _don’t_ want to include additional HTML markup in the content; :br and :nbsp make sense for programming languages but not for natural languages.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/correspondence-markup/types.rb', line 32

def text_to_html(text, options)
  html = text
  if options[:escaped]
    html = CGI.escape_html(html)
  end
  if options[:br]
    html = html.gsub("\n", "<br/>")
  end
  if options[:nbsp]
    tags_and_text = Helpers.split_tags_and_text(html)
    html = tags_and_text.map do |tag_or_text| 
      if tag_or_text[0] then tag_or_text[0] else tag_or_text[1].gsub(" ", "&nbsp;") end
    end.join("")
  end
  html
end