Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get escape_javascript and other helpers in my sprockets pre-processed js file (not a view)?

I'm using Rails 3.1 and the sprockets stuff.

I want to use ERB to pre-process a js file that will then be included using javascript_include_tag. It is generated from code, and so I'm pre-processing it with ERB, but I can't get to the helpers like escape_javascript from ActionView::Helpers::JavaScriptHelper

Say my file is called dynamic.js.erb, and it contains

obj = {
 name: "test",
 tag: "<%= escape_javascript( image_tag( "logo.png" ) )%>"
};

How do I stop it from producing the error:

throw Error("NoMethodError: undefined method `escape_javascript' for #<#<Class:0x1067da940>:0x116b2be18>
(in /Users/me/site/app/assets/javascripts/dynamic.js.erb)")

When I hit my local server and ask for /assets/dynamic.js

like image 518
nocache Avatar asked Jul 27 '11 01:07

nocache


1 Answers

You can include the rails JS helpers into your own class.

class Helper
  include ActionView::Helpers::JavaScriptHelper

  def self.escape_js( text )
    @instance ||= self.new
    return @instance.escape_javascript( text )
  end
end

Then use it in your ERB file:

obj = {
 name: "test",
 tag: "<%= Helper.escape_js( image_tag( "logo.png" ) ) )%>"
};
like image 152
cammm Avatar answered Sep 29 '22 12:09

cammm