2013-02-05 14:16:51 -05:00
require 'open-uri'
require_dependency 'oneboxer/base_onebox'
module Oneboxer
class HandlebarsOnebox < BaseOnebox
2013-05-03 19:06:05 -04:00
unless defined? MAX_TEXT
MAX_TEXT = 500
end
2013-02-05 14:16:51 -05:00
2013-05-01 02:37:27 -04:00
def self . template_path ( template_name )
2013-02-05 14:16:51 -05:00
" #{ Rails . root } /lib/oneboxer/templates/ #{ template_name } .hbrs "
end
2013-05-01 02:37:27 -04:00
def template_path ( template_name )
HandlebarsOnebox . template_path ( template_name )
end
2013-02-05 14:16:51 -05:00
def template
template_name = self . class . name . underscore
template_name . gsub! ( / oneboxer \/ / , '' )
template_path ( template_name )
end
def default_url
" <a href=' #{ @url } ' target='_blank'> #{ @url } </a> "
end
def http_params
{ 'User-Agent' = > 'Mozilla/5.0 (iPhone; CPU iPhone OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3' }
end
2013-06-12 19:39:18 -04:00
def fetch_html
open ( translate_url , http_params ) . read
end
2013-02-05 14:16:51 -05:00
def onebox
2013-06-12 19:39:18 -04:00
html = fetch_html
2013-02-05 14:16:51 -05:00
args = parse ( html )
return default_url unless args . present?
2013-09-30 13:09:57 -04:00
2013-02-05 14:16:51 -05:00
args [ :original_url ] = @url
args [ :lang ] = @lang || " "
2013-09-30 13:09:57 -04:00
args [ :favicon ] = ActionController :: Base . helpers . asset_path ( self . class . favicon_file , digest : false ) if self . class . favicon_file . present?
2013-03-01 18:46:55 -05:00
args [ :host ] = nice_host
2013-02-05 14:16:51 -05:00
2013-05-01 02:37:27 -04:00
HandlebarsOnebox . generate_onebox ( template , args )
2013-02-05 14:16:51 -05:00
rescue = > ex
# If there's an exception, just embed the link
2013-02-25 11:42:20 -05:00
raise ex if Rails . env . development?
default_url
2013-02-05 14:16:51 -05:00
end
2013-09-30 13:09:57 -04:00
def self . generate_onebox ( template , args = { } )
2013-05-01 02:37:27 -04:00
Mustache . render ( File . read ( template ) , args )
end
2013-02-05 14:16:51 -05:00
end
end