module Convert::Converters

Autoload for faster loading

Constants

SKIP

Public Instance Methods

convert(string, options = {}) click to toggle source

Loop converters and convert

# File lib/converters/nokogiri.rb, line 24
def convert(string, options = {})
  options[:converters].each{|c| string = send(c, string)}
  string
end
convertable?(node) click to toggle source

Checks if a node is convertable by scanning the parents

# File lib/converters/nokogiri.rb, line 30
def convertable?(node)
  while(node = node.parent) do
    return false if SKIP.include?(node.name)
  end
  true
end
dailymotion(string, options = {}) click to toggle source
# File lib/converters/dailymotion.rb, line 4
def dailymotion(string, options = {})
  # http://www.dailymotion.com/video/x3gpxwp_first-person-view-of-a-downhill-ice-cross-course-red-bull-crashed-ice-2015_sport

  # Original 480 360
  options = {:width => 590, :height => 335}.merge(options)

  @regex = /http:\/\/www\.dailymotion\.com.*\/video\/(.+)_*/

  string.gsub(@regex) do
    video_id = $1
    %{<object type="application/x-shockwave-flash" data="http://www.dailymotion.com/swf/#{video_id}&related=0" width="#{options[:width]}" height="#{options[:height]}"><param name="movie" value="http://www.dailymotion.com/swf/#{video_id}&related=0"></param><param name="allowFullScreen" value="true"></param><param name="allowScriptAccess" value="always"></param><a href="http://www.dailymotion.com/video/#{video_id}?embed=1"><img src="http://www.dailymotion.com/thumbnail/video/#{video_id}" width="#{options[:width]}" height="#{options[:height]}"/></a></object>}
  end
end
decode(string, options = {}) click to toggle source
# File lib/converters/decode.rb, line 4
def decode(string, options = {})
  HTMLEntities.new.decode(string)
end
email_escape(string, options = {}) click to toggle source

Remove stuff from email body that is going to be stripped anyway.

# File lib/converters/email_escape.rb, line 5
def email_escape(string, options = {})

  # No options at the moment
  options = {}.merge(options)

  # Youtube videos
  @regex = /<iframe.+src=['"].+\/embed\/(.+)[?].+['"].+iframe>/
  string = string.gsub(@regex, "https://youtu.be/#{'\1'}")

  # Vimeo videos
  # Example: https://vimeo.com/59437462
  @regex = /<iframe.+src=['"]\/\/player\.vimeo.com\/video\/(.+)[?]{1}.+['"].+iframe>/
  string = string.gsub(@regex, "https://vimeo.com/#{'\1'}")
  string
end
encode(string, options = {}) click to toggle source
# File lib/converters/encode.rb, line 4
def encode(string, options = {})
  HTMLEntities.new.encode(string)
end
escape_html(string, options = {}) click to toggle source

Escape html

# File lib/converters/html_escape.rb, line 5
def escape_html(string, options = {})
  options = {:map => {'&' => '&amp;', '>' => '&gt;', '<' => '&lt;', '"' => '&quot;' }}.merge(options)

  @regex = /[&"><]/
  string.gsub(@regex){|m| options[:map][m]}
end
facebook_embed(string, options = {}) click to toggle source

Embed vimeo by id

# File lib/converters/facebook_embed.rb, line 5
def facebook_embed(string, options = {})
  options = {:width => 590, :height => 335}.merge(options)

  %{<iframe src="https://www.facebook.com/plugins/video.php?href=https://www.facebook.com/facebook/videos/#{string}/&width=#{options[:width]}&show_text=false&height=#{options[:height]}" width="#{options[:width]}" height="#{options[:height]}" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowTransparency="true"></iframe>}
end
flickr(string, options = {}) click to toggle source
# File lib/converters/flickr.rb, line 4
def flickr(string, options = {})
  # https://www.flickr.com/photos/fotokunstsusanne/23160248869

  options = {:maxwidth => nil, :maxheight => nil, :link_options => {}}.merge(options)
  @regex = %r{https?://(www\.)?flickr\.com/photos/[^\s<]*}

  string.gsub(@regex) do |match|
    params = { :url => match, :format => "json" }
    [:maxwidth, :maxheight].each{|p| params[p] = options[p] unless options[p].nil? or !options[p] > 0}

    uri = URI("http://www.flickr.com/services/oembed")
    uri.query = URI.encode_www_form(params)

    response = JSON.parse(Net::HTTP.get(uri))

    link_options = Array(options[:link_options]).reject { |k,v| v.nil? }.map { |k, v| %{#{k}="#{REXML::Text::normalize(v)}"} }.join(' ')
    %{<a href="#{match}"#{ ' ' + link_options unless link_options.empty? }><img src="#{response["url"]}" alt="#{response["title"]}" title="#{response["title"]}" /></a>}
  end
end
gist(string, options = {}) click to toggle source
# File lib/converters/gist.rb, line 4
def gist(string, options = {})
  # https://gist.github.com/1710276

  # No options at the moment
  options = {}.merge(options)

  @regex = %r{https?://gist\.github\.com/(\w+/)?(\d+)}

  string.gsub(@regex) do
    gist_id = $2
    %{<script src="https://gist.github.com/#{gist_id}.js"></script>}
  end
end
google_maps(string, options = {}) click to toggle source
# File lib/converters/google_maps.rb, line 4
def google_maps(string, options = {})
  options = {
    :width => 420,
    :height => 315,
    :style => "color:#000;text-align:left",
    :link_text => "View Larger Map",
    :show_info => true,
    :type => :normal,
    :zoom => 18,
    :more => ''
  }.merge(options)

  map_type = {:normal => '&t=m', :satellite => '&t=k', :terrain => '&t=p', :hybrid => '&t=h'}

  @regex = /(https?):\/\/maps\.google\.([a-z\.]+)\/maps\?(.*)/

  string.gsub(@regex) do
    domain_country = $2
    map_query = $3
    width = options[:width]
    height = options[:height]
    style = options[:style]
    link_text = options[:link_text]
    type = options[:type].to_sym
    map_options = (options[:show_info] ? '' : '&iwloc=near')
    map_options << map_type[type] if map_type.has_key?(type)
    map_options << "&z=#{options[:zoom]}"
    map_options << options[:more]
    %{<iframe width="#{width}" height="#{height}" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="//maps.google.#{domain_country}/maps?f=q&source=s_q&#{map_query}&output=embed#{map_options}"></iframe><br><small><a href="//maps.google.#{domain_country}/maps?f=q&source=embed&#{map_query}" style="#{style}">#{link_text}</a></small>}
  end
end
hashtag(string, options = {}) click to toggle source
# File lib/converters/hashtag.rb, line 4
def hashtag(string, options = {})
  options = {:source => :twitter}.merge(options)
  @regex = /#([^\s]+)/

  if options[:source] == :twitter
    string.gsub(@regex, '<a href="http://twitter.com/search?q=%23\1&f=realtime" class="hashtag" target="_blank">#\1</a>')
  elsif options[:source] == :facebook
    string.gsub(@regex, '<a href="https://www.facebook.com/hashtag/\1" class="hashtag" target="_blank">#\1</a>')
  end
end
iframe_embed(url, options = {}) click to toggle source

Iframe embed code

# File lib/converters/iframe_embed.rb, line 5
def iframe_embed(url, options = {})
  options = {:width => 231, :height => 436, :scrolling => 'no', :frameborder => 0}.merge(options)

  %{<iframe frameborder="#{options[:frameborder]}" scrolling="#{options[:scrolling]}" height="#{options[:height]}" width="#{options[:width]}" src="#{url}"></iframe>}
end
image_tag(src, options = {}) click to toggle source

Convert image to img html tag

# File lib/converters/image_tag.rb, line 5
def image_tag(src, options = {})
  options = {:alt => ''}.merge(options)
  %{<img src="#{src}" alt="#{options[:alt]}">}
end
instagram(string, options = {}) click to toggle source
# File lib/converters/instagram.rb, line 4
def instagram(string, options = {})
  options = {:height => 714, :width => 616}.merge(options)
  @regex = %r{https?:\/\/(www.)?instagr(am\.com|\.am)/p/.+}

  string.gsub(@regex) do
    string += '/' unless string.end_with?('/')
    %{<iframe src="#{string}embed" height="#{options[:height]}" width="#{options[:width]}" frameborder="0" scrolling="no"></iframe>}
  end
end
kramdown(string, options = {}) click to toggle source
# File lib/converters/kramdown.rb, line 4
def kramdown(string, options = {})
  options = {
    :auto_ids => false,
    :entity_output => :as_char,
    :enable_coderay => true,
    :parse_block_html => true,
    :parse_span_html => true,
    :smart_quotes => ['apos', 'apos', 'quot', 'quot']
  }.merge(options)

  Kramdown::Document.new(string, options).to_html
end
liveleak(string, options = {}) click to toggle source
# File lib/converters/liveleak.rb, line 4
def liveleak(string, options = {})
  options = {
    :width => 420,
    :height => 315,
    :frameborder => 0,
    :wmode => nil,
    :autoplay => false,
    :hide_related => false
  }.merge(options)

  @regex = %r{http://www\.liveleak\.com/(?:ll_embed|view)\?.=(\w+)}

  string.gsub(@regex) do
    a = []
    a << "wmode=#{options[:wmode]}" if options[:wmode]
    a << "autoplay=1" if options[:autoplay]
    a << "rel=0" if options[:hide_related]

    src = "http://www.liveleak.com/ll_embed?f=#{$1}"
    src += "?#{a.join '&'}" unless a.empty?

    %{<iframe width="#{options[:width]}" height="#{options[:height]}" src="#{src}" frameborder="#{options[:frameborder]}" allowfullscreen></iframe>}
  end
end
markdown(string, options = {}) click to toggle source

Converts the string into html

# File lib/converters/markdown.rb, line 5
def markdown(string, options = {})
  options = {
    :autolink => true,
    :fenced_code_blocks => true,
    :disable_indented_code_blocks => true,
    :no_intra_emphasis => true
  }.merge(options)

  Redcarpet::Markdown.new(
    Redcarpet::Render::HTML.new(:filter_html => false, :hard_wrap => true),
    options
  ).render(string)
end
metacafe(string, options = {}) click to toggle source

Convert metacafe movie URL to embedded html

# File lib/converters/metacafe.rb, line 5
def metacafe(string, options = {})
  # Original 440 272
  options = {
    :width => 590,
    :height => 335,
    :show_stats => false,
    :autoplay => false
  }.merge(options)

  @regex = /http:\/\/www\.metacafe\.com\/watch\/([A-Za-z0-9._%-]*)\/([A-Za-z0-9._%-]*)(\/)?/

  string.gsub(@regex) do
    metacafe_id = $1
    metacafe_slug = $2
    width  = options[:width]
    height = options[:height]
    show_stats = options[:show_stats] ? "showStats=yes" : "showStats=no"
    autoplay = options[:autoplay] ? "autoPlay=yes" : "autoPlay=no"
    flash_vars = [show_stats, autoplay].join("|")

    %{<div style="background:#000000;width:#{width}px;height:#{height}px"><embed flashVars="playerVars=#{flash_vars}" src="http://www.metacafe.com/fplayer/#{metacafe_id}/#{metacafe_slug}.swf" width="#{width}" height="#{height}" wmode="transparent" allowFullScreen="true" allowScriptAccess="always" name="Metacafe_#{metacafe_id}" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed></div>}
  end
end
redcarpet(string, options = {}) click to toggle source

Markown converter

# File lib/converters/redcarpet.rb, line 5
def redcarpet(string, options = {})
  options = {:renderer => Redcarpet::Render::HTML, :markdown_options => {}}.merge(options)

  Redcarpet::Markdown.new(options[:renderer], options[:markdown_options]).render(string)
end
sanitize(string, options = {}) click to toggle source

Built in configs: :custom, :full, :linebreaks, :simple, :restricted, :basic, :relaxed

# File lib/converters/sanitize.rb, line 6
def sanitize(string, options = {})
  return string if options[:config] == false
  options = {:config => nil}.merge(options)
  config = Object.const_get("Sanitize::Config::#{options[:config].to_s.upcase}")
  Sanitize.fragment(string, config || {})
end
scan(string, options = {}) click to toggle source

Scan a string with Nokogiri and convert if match string

# File lib/converters/nokogiri.rb, line 7
def scan(string, options = {})
  return string if !options[:converters] or options[:converters].empty?

  doc = Nokogiri::HTML.fragment(string)

  doc.search('.//text()').each do |el|
    t = el.text
    if t.strip.size > 0
      t = convert(t, options) if convertable?(el)
    end
    el.replace(t)
  end

  doc.to_html
end
simple_format(string, options = {}) click to toggle source

Convert newlines to br tags

# File lib/converters/simple_format.rb, line 5
def simple_format(string, options = {})
  options = {:config => :simple}.merge(options)
  sanitize(string.gsub(%r{(\r\n|\n|\r)}, '<br>'), options)
end
soundcloud(string, options = {}) click to toggle source

Convert soundcloud player URL to embedded iframe

# File lib/converters/soundcloud.rb, line 5
def soundcloud(string, options = {})
  options = {
    :width => '100%',
    :height => 166,
    :auto_play => false,
    :theme_color => '00FF00',
    :color => '915f33',
    :show_comments => false,
    :show_artwork => false
  }.merge(options)

  @regex = /(https?:\/\/)?(www.)?soundcloud\.com\/\S*/

  begin
    string.gsub(@regex) do |match|
      new_uri = match.to_s
      new_uri = (new_uri =~ /^https?\:\/\/.*/) ? URI(new_uri) : URI("http://#{new_uri}")
      new_uri.normalize!
      width = options[:width]
      height = options[:height]
      auto_play = options[:auto_play]
      theme_color = options[:theme_color]
      color = options[:color]
      show_artwork = options[:show_artwork]
      show_comments = options[:show_comments]
      %{<iframe width="#{width}" height="#{height}" scrolling="no" frameborder="no" src="http://w.soundcloud.com/player/?url=#{new_uri}&show_artwork=#{show_artwork}&show_comments=#{show_comments}&auto_play=#{auto_play}&color=#{color}&theme_color=#{theme_color}"></iframe> }
    end
  rescue URI::InvalidURIError
    string
  end
end
strip_params(url) click to toggle source

Remove query params

# File lib/converters/strip_params.rb, line 5
def strip_params(url)
  uri = URI.parse(URI.encode(url.strip))
  uri.query = nil
  uri.to_s
end
ted(string, options = {}) click to toggle source

Convert ted movie URL to embedded iframe

# File lib/converters/ted.rb, line 5
def ted(string, options = {})
  # Original: 640 360
  options = {
    :width => 590,
    :height => 335,
    :scrolling => 'no',
    :frameborder => 0,
    :allow_full_screen => false
  }.merge(options)

  @regex = /https?:\/\/(www.|embed.)?ted\.com\/talks\/([A-Za-z0-9._%-]*)\.html((\?|#)\S+)?/

  string.gsub(@regex) do
    ted_page = $2
    width = options[:width]
    height = options[:height]
    frameborder = options[:frameborder]
    scrolling = options[:scrolling]
    allow_full_screen = options[:allow_full_screen]

    %{<iframe width="#{width}" height="#{height}" frameborder="#{frameborder}" scrolling="#{scrolling}" src="http://embed.ted.com/talks/#{ted_page}.html"#{allow_full_screen ? ' webkitAllowFullScreen mozallowfullscreen allowFullScreen' : ''}></iframe>}
  end
end
to_ascii(string) click to toggle source

Convert chinese characters to URL safe format

# File lib/converters/simpleidn.rb, line 5
def to_ascii(string)
  SimpleIDN.to_ascii(string)
end
to_unicode(string) click to toggle source

Reverse safe format back to unicode

# File lib/converters/simpleidn.rb, line 10
def to_unicode(string)
  SimpleIDN.to_unicode(string)
end
twitter(string, options = {}) click to toggle source

Convert twitter URL to embedded html

# File lib/converters/twitter.rb, line 5
def twitter(string, options = {})
  @regex = %r{(?<!href=")https://twitter\.com(/#!)?/[A-Za-z0-9_]{1,15}/status(es)?/\d+(/?)}

  string.gsub(@regex) do |match|
    params = {:url => match}.merge(options)

    uri = URI("https://api.twitter.com/1/statuses/oembed.json")
    uri.query = URI.encode_www_form(params)

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    response = JSON.parse(http.get(uri.request_uri).body)
    response['html']
  end
end
unescape_html(string, options = {}) click to toggle source
# File lib/converters/unescape_html.rb, line 4
def unescape_html(string, options = {})
  @regex = /(&lt;.*?[a-z]{0,12}?&gt;)+/i

  string.gsub(@regex) do |tag|
    tag.gsub("&lt;", "<").gsub("&gt;", ">")
  end
end
video_embed(string, options = {}) click to toggle source

Vimeo and Youtube embed markdown extension

# File lib/converters/video_embed.rb, line 5
def video_embed(string, options = {})
  @regex = /\?\[(youtube|vimeo)\]\(https?:\/\/(www\.)?(vimeo\.com\/|youtu\.be\/|youtube\.com\/watch\?v=)(\S+)\)/

  string.scan(@regex).each do |type, prefix, url, id|
    r = if('vimeo' == type)
      vimeo_embed(options)
    elsif('youtube' == type)
      youtube_embed(options)
    else
      nil
    end
    # Substitute the original text with the embedded version
    # OLD, optional https not supported:
    # @text.gsub!("?[#{type}](https://#{prefix}#{url}#{id})", r) if r
    x = %r{\?\[#{type}\]\(https?:\/\/#{Regexp.escape(prefix)}#{Regexp.escape(url)}#{id}\)}i
    string.gsub!(x, r) if r
  end
  string
end
vimeo(string, options = {}) click to toggle source

Convert vimeo movie URL to embedded iframe

# File lib/converters/vimeo.rb, line 5
def vimeo(string, options = {})
  # Original: 440 248
  options = {
    :width => 590,
    :height => 335,
    :show_title => false,
    :show_byline => false,
    :show_portrait => false,
    :allow_fullscreen => true
  }.merge(options)

  @regex = /https?:\/\/(www.)?vimeo\.com\/([A-Za-z0-9._%-]*)((\?|#)\S+)?/

  string.gsub(@regex) do
    vimeo_id = $2
    width = options[:width]
    height = options[:height]
    show_title = "title=0"    unless options[:show_title]
    show_byline = "byline=0"   unless options[:show_byline]
    show_portrait = "portrait=0" unless options[:show_portrait]
    allow_fullscreen = " allowfullscreen" if options[:allow_fullscreen]
    frameborder = options[:frameborder] || 0
    query_string_variables = [show_title, show_byline, show_portrait].compact.join("&")
    query_string = "?" + query_string_variables unless query_string_variables.empty?

    %{<iframe src="//player.vimeo.com/video/#{vimeo_id}#{query_string}" width="#{width}" height="#{height}" frameborder="#{frameborder}"#{allow_fullscreen}></iframe>}
  end
end
vimeo_embed(string, options = {}) click to toggle source

Embed vimeo by id

# File lib/converters/vimeo_embed.rb, line 5
def vimeo_embed(string, options = {})
  options = {:width => 590, :height => 335}.merge(options)

  %{<iframe src="https://player.vimeo.com/video/#{string}?title=0&byline=0&portrait=0" width="#{options[:width]}" height="#{options[:height]}"></iframe>}
end
worldstar(string, options = {}) click to toggle source

Convert worldstar movie URL to embedded html

# File lib/converters/worldstar.rb, line 5
def worldstar(string, options = {})
  # Original: 448 374
  options = {:width => 590, :height => 335}.merge(options)

  @regex = /http:\/\/www\.worldstarhiphop\.com\/videos\/video\.php\?v\=(wshh[A-Za-z0-9]+)/

  string.gsub(@regex) do
    video_id = $1
    width  = options[:width]
    height = options[:height]
    %{<object width="#{width}" height="#{height}"><param name="movie" value="http://www.worldstarhiphop.com/videos/e/16711680/#{video_id}"><param name="allowFullScreen" value="true"></param><embed src="http://www.worldstarhiphop.com/videos/e/16711680/#{video_id}" type="application/x-shockwave-flash" allowFullscreen="true" width="#{width}" height="#{height}"></embed></object>}
  end
end
youtube(string, options = {}) click to toggle source

Convert youtube movie URL to embedded iframe

# File lib/converters/youtube.rb, line 5
def youtube(string, options = {})
  # Original: 420 315
  options = {
    :width => 590,
    :height => 335,
    :frameborder => 0,
    :wmode => 'transparent',
    :autoplay => false,
    :hide_related => true,
    :fs => true,
    :modestbranding => true,
    :allow_fullscreen => true
  }.merge(options)

  @regex = /(https?:\/\/)?(www.)?(youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/watch\?feature=player_embedded&v=)([A-Za-z0-9_-]*)(\&\S+)?(\?\S+)?/

  string.gsub(@regex) do
    youtube_id = $4
    src = "https://www.youtube.com/embed/#{youtube_id}"
    width = options[:width]
    height = options[:height]
    allow_fullscreen = " allowfullscreen" if options[:allow_fullscreen]
    frameborder = options[:frameborder]

    a = []
    a << "wmode=#{options[:wmode]}" if options[:wmode]
    a << "autoplay=1" if options[:autoplay]
    a << "rel=0" if options[:hide_related]
    a << "modestbranding=1" if options[:modestbranding]
    a << "fs=1" if options[:fs]

    src += "?#{a.join '&'}" unless a.empty?

    %{<iframe width="#{width}" height="#{height}" src="#{src}" frameborder="#{frameborder}"#{allow_fullscreen}></iframe>}
  end
end
youtube_embed(string, options = {}) click to toggle source

Embed youtube by id

# File lib/converters/youtube_embed.rb, line 5
def youtube_embed(string, options = {})
  options = {:width => 590, :height => 335}.merge(options)

  %{<iframe src="https://www.youtube.com/embed/#{string}?wmode=transparent&modestbranding=1&fs=1&rel=0" allowfullscreen="1" webkitallowfullscreen="1" mozallowfullscreen="1" width="#{options[:width]}" height="#{options[:height]}" frameborder="0"></iframe>}
end
youtube_image(string, options = {}) click to toggle source
# File lib/converters/youtube_image.rb, line 4
def youtube_image(string, options = {})
  options = {
    :width => 320,
    :height => 315,
    :style => 'medium',
    :target => 'blank',
    :border => '0'
  }.merge(options)

  styles = {
    'default' => 'default',
    'high' => 'hqdefault',
    'medium' => 'mqdefault',
    'normal' => 'sddefault',
    'max' => 'maxresdefault'
  }

  @regex = /(https?:\/\/)?(www.)?(youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/watch\?feature=player_embedded&v=)([A-Za-z0-9_-]*)(\&\S+)?(\?\S+)?/

  string.gsub(@regex) do
    youtube_id = $4
    video_url = "https://www.youtube.com/watch?v=#{youtube_id}"
    target = options[:target]
    width = options[:width]
    height = options[:height]
    border = options[:border]
    style = styles[options[:style]] rescue styles['default']
    src = "//img.youtube.com/vi/#{youtube_id}/#{style}.jpg"
    %{<div class="thumbnail youtube"><a href="#{video_url}" target="_#{target}"><img src="#{src}" width="#{width}" height="#{height}" border="#{border}"></a></div>}
  end
end
youtube_js_api(string, options = {}) click to toggle source
# File lib/converters/youtube_js_api.rb, line 4
def youtube_js_api(string, options = {})
  # Original: 390 250
  options = {:width => 590, :height => 335}.merge(options)

  @regex = /https?:\/\/(www.)?youtube\.com\/watch\?v=([A-Za-z0-9._%-]*)(\&\S+)?/

  string.gsub(@regex) do
    youtube_id = $2
    width = options[:width]
    height = options[:height]

    %{<object width="#{width}" height="#{height}"><param name="movie" value="//www.youtube.com/v/#{youtube_id}?enablejsapi=1&playerapiid=ytplayer"></param><param name="wmode" value="transparent"></param><param name="allowscriptaccess" value="always"></param><embed src="//www.youtube.com/v/#{youtube_id}?enablejsapi=1&playerapiid=ytplayer" type="application/x-shockwave-flash" wmode="transparent" width="#{width}" height="#{height}" allowscriptaccess="always"></embed></object>}
  end
end