First, what you're talking about isn't necessarily UJS, but rather RJS or Ruby JavaScript, or javascript generated on-the-fly from ruby templates.
UJS, very (most?) often, is not done via dynamic javascript, but by returning dynamic data which is then manipulated by static javascript. This has many advantages; relevant to this case: it means that your javascript is already minified (and probably cached) client-side and you're just sending serialized data down the wire.
If you can, you might want to think about using that approach.
If you cannot, you might automagically minify your RJS actions with middleware, something like below (a raw pseudocoded version). But do so with care. You'll also want to consider whether the benefits of minification are worth the cost, e.g. the time/cost of minifying every request vs the time/cost of sending larger files to the client.
For more info on middleware, refer to the docs
module RJSMinifier
def initialize(app)
@app = app
end
def call(env)
status, headers, response = @app.call(env)
# pseudocode: if this is not an RJS request or the request did not
# complete successfully, return without doing anything further
if (this request is not RJS or status is not ok)
return [status, headers, response]
end
# otherwise minify the response and set the new content-length
response = minify(response)
headers['Content-Length'] = response.length.to_s
[status, headers, response]
end
def minify(js)
# replace this with the real minifier you end up using
YourMinifier.minify(js)
end
end