8

Greetings Rails and Javascript Gurus!

I have a project where I am returning a large javascript file in a

respond_to do |format|
   format.js
end

block.

I am trying to figure out how I can minify or compress the .js response since the .js.erb view is full of comments and varies in size based on the results from the controller.

Anyone have any ideas?

Dustin M.
  • 2,884
  • 3
  • 20
  • 18

3 Answers3

12

For Rails 4:

render js: Uglifier.new.compile(render_to_string)
Sidhannowe
  • 465
  • 5
  • 11
5

well, maybe I have a solution:

respond_to do |format|
  format.js { self.response_body = minify(render_to_string) }
end

This perfectly works. Of course that the key is the minify method. You will find a lot of JS minifiers around. For example you can use this one (well if license permits): http://github.com/thumblemonks/smurf/raw/master/lib/smurf/javascript.rb - it is based on Crockford's jsmin.c.

If you put this file into your lib, require it, your minify method can look like this:

def minify(content)
  min = Smurf::Javascript.new(content)
  min.minified
end

Hope that it helped you.

If you plan to do minifying automatically then you probably should go for a piece of middleware. Surprisingly I was not able to find any (there are many aimed to the CSS/JS but it's about static assets not dynamic content) but it would not be such a problem to write it.

Radek Paviensky
  • 8,316
  • 2
  • 30
  • 14
  • Thanks pawien! This gives me something to think about for sure. :) Passing the result to a block and processing it with a minifier seems to be a good solution. Then I just need to figure out how to cache the output. I will play with this today and tomorrow.. I may bug you. :D – Dustin M. Sep 29 '10 at 16:11
  • 2
    Is there any way to do this in Rails3.2, only using its own builtin features of assets pipeline? – Nazar Hussain Jun 28 '12 at 11:23
  • thanks radek! nice solution. nazar, added my rails 3 modified bit below – djburdick May 05 '13 at 18:39
3

For rails 3 using the built in Uglifier method (the default for the assets pipeline)

See Radek's code above and just swap this in.

  def minify(content)
    Uglifier.new.compile(content)
  end
djburdick
  • 11,762
  • 9
  • 46
  • 64