foodsoft/plugins/uservoice/lib/foodsoft_uservoice.rb

53 lines
1.9 KiB
Ruby
Raw Permalink Normal View History

require 'content_for_in_controllers'
require 'foodsoft_uservoice/engine'
2014-12-16 22:43:46 +01:00
module FoodsoftUservoice
# enabled when configured, but can still be disabled by use_uservoice option
def self.enabled?
FoodsoftConfig[:use_uservoice] != false && FoodsoftConfig[:uservoice]
2014-12-16 22:43:46 +01:00
end
module LoadUservoice
def self.included(base) # :nodoc:
base.class_eval do
before_action :add_uservoice_script
2014-12-16 22:43:46 +01:00
protected
def add_uservoice_script
return unless FoodsoftUservoice.enabled?
# include uservoice javascript
api_key = FoodsoftConfig[:uservoice]['api_key']
js_pre = 'UserVoice=window.UserVoice||[];'
2014-12-16 22:43:46 +01:00
js_load = "var uv=document.createElement('script');uv.type='text/javascript';uv.async=true;uv.src='//widget.uservoice.com/#{view_context.j api_key}.js';var s=document.getElementsByTagName('script')[0];s.parentNode.insertBefore(uv,s);"
# configuration
sections = FoodsoftConfig[:uservoice].except('api_key')
sections.each_pair do |k, v|
2014-12-16 22:43:46 +01:00
if k == 'identify'
v['id'] = current_user.try(:id) if v.include?('id')
v['name'] = current_user.try(:display) if v.include?('name')
v['email'] = current_user.try(:email) if v.include?('email')
v['created_at'] = current_user.try { |u| u.created_on.to_i } if v.include?('created_at')
2014-12-16 22:43:46 +01:00
elsif k == 'set'
v['locale'] = I18n.locale
end
js_load += "UserVoice.push(#{[k, v].to_json});"
end
# skip uservoice when serving mobile pages (using jquery mobile, a bit of a hack)
js_load = "$(function() { if(!$('[data-role=page]')[0]){#{js_load}} });"
# include in layout
content_for :javascript, view_context.javascript_tag(js_pre + js_load)
2014-12-16 22:43:46 +01:00
end
end
end
end
end
ActiveSupport.on_load(:after_initialize) do
ApplicationController.include FoodsoftUservoice::LoadUservoice
2014-12-16 22:43:46 +01:00
end