Including helper methods in javascript

I’m working on an app and found myself needing set an initial position for a map.
The most reasonable thing seems to be to geocode the IP in the controller and use it in my javascript.
So in my controller I tried creating a method that did what I needed. I figured declaring it as a helper_method and adding a .erb to the file name so it would be preprocessed would be all I would need to do.
For some reason it was not so simple…

If you call in your javascript file you get a decendent of Sprockets::Context. For reasons I don’t understand, Rails helper menthods don’t seem to be included in it.
My need was just to pass in my geocoded lat/long values, and using a gem felt like a little much so created a JsVars module that behaves like a hash and included it in the context class with an initializer:

config/initializers/sprockets_helpers.rb 

Rails.application.assets.context_class.class_eval do
  include AssetMethods
end

My little hash module looks like this:

module AssetMethods
  module JsVars
    @vars = {}

    def self.[]=(k, v)
      @vars[k]=v
    end

    def self.[](k)
      @vars[k].to_json
    end
  end
end

And that lets me do this in my whatever.js.erb:

var test = ;

which comes out as:
var test = {“fizz”:”buzz”};

I think I would have to take a hard look at json escaping if/when I start using that for user supplied data, but for now it fits the bill nicely. While I am happy to have figured out a workable solution, I have a suspicion there was a much easier way to have done it.
For the moment… onwards!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s