module CorrespondenceMarkup::Helpers

Helper functions used when generating HTML

Constants

TAGS_AND_TEXT_REGEX

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

Public Class Methods

split_tags_and_text(html) click to toggle source

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.)

# File lib/correspondence-markup/types.rb, line 20
def self.split_tags_and_text(html)
  html.scan(TAGS_AND_TEXT_REGEX).to_a
end

Public Instance Methods

text_to_html(text, options) click to toggle source

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.

# 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