discourse/lib/oneboxer/handlebars_onebox.rb

52 lines
1.4 KiB
Ruby
Raw Normal View History

2013-02-05 14:16:51 -05:00
require 'open-uri'
require_dependency 'oneboxer/base_onebox'
module Oneboxer
class HandlebarsOnebox < BaseOnebox
MAX_TEXT = 500
def template_path(template_name)
"#{Rails.root}/lib/oneboxer/templates/#{template_name}.hbrs"
end
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
def onebox
html = open(translate_url, http_params).read
args = parse(html)
return default_url unless args.present?
args[:original_url] = @url
args[:lang] = @lang || ""
args[:favicon] = ActionController::Base.helpers.image_path(self.class.favicon_file) if self.class.favicon_file.present?
begin
parsed = URI.parse(@url)
args[:host] = parsed.host.split('.').last(2).join('.')
rescue URI::InvalidURIError
# In case there is a problem with the URL, we just won't set the host
end
Mustache.render(File.read(template), args)
rescue => ex
# If there's an exception, just embed the link
raise ex if Rails.env.development?
default_url
end
end
end