Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 0d7de0f19e
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 78 lines (69 sloc) 2.718 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
require 'json'

module Jsvars
    def self.included(base)
        base.send(:include, InstanceMethods)
    end

    module InstanceMethods
        def jsvars
            @jsvars ||= Hash.new
        end

        def include_jsvars
            jsvars = @jsvars
            name = 'jsvars'
            return unless jsvars && response && response.content_type && response.content_type[/html|fbml/i]
            js_assignments = []
            jsvars.each do |variable, value|
                js_assignments <<
                    if variable.to_s[/\./]
                        # allows usage like jsvars['myObj.myVar.myValue'] = "number"
                        object_tests = []
                        objects = variable.split('.')
                        (0...objects.length - 1).each do |i|
                            object_name = objects[0..i].join('.')
                            object_tests <<
                                "
if (#{ object_name } === undefined) {
#{ "var" if i == 0 } #{ object_name } = {};
}
"
                        end
                        object_tests.join + "#{ variable } = #{ value.to_json };"
                    else
                        "
if (typeof(#{ variable }) === 'object') {
jsvars.objExtend(#{ variable }, #{ value.to_json });
}
else {
var #{ variable } = #{ value.to_json };
}
"
                    end
            end
            
            methods =
            '
var jsvars = {
objExtend: function (mainObject) {
for (var i = 1; i < arguments.length; i += 1) {
for (prop in arguments[i]){
if (arguments[i].hasOwnProperty(prop)) {
mainObject[prop] = (arguments[i][prop]);
}
}
}
return mainObject;
}
}
'
            methods = methods.gsub(/\n|\r|\t/, ' ').squeeze(' ')

            added_script =
"<!-- added by the #{ name } plugin -->
<script type='text/javascript'>
#{ methods }
#{ js_assignments.join }
</script>
<!-- end #{ name } plugin code -->"
            index = response.body.index(/<\/body>/i) || -1
            response.body.insert index, added_script
        end
    end
end



Something went wrong with that request. Please try again.