Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Javascript: How to inject rails variables into (very) simple javascript

I want to write up a very simple javascript calculator in rails which multiplies the quantity of an input field by a number stored in a rails variable (@item.base_price)

So, on the javascript/coffeescript side of things, it's crudely this:

# app/assets/javascript/items.js.coffee
$ -> 
  $('#item_quantity').change ->
    quantity_val = $(this).val()
    $('#total_amount').html(quantity_val * <%= [email protected]_PRICE_HERE %>)

I'm aware of how I can do this via an ajax call on each change() call, but I figure there has to be an elegant, hopefully unobtrusive rails way which doesn't hit the server each time.

Any suggestions very appreciated

like image 655
PlankTon Avatar asked Feb 22 '23 22:02

PlankTon


1 Answers

If you are using rails 3.1 you can take advantage of the assets pipeline to do some pre-processing on the javascript files before you serve them up. To do this just change the file extension from:

items.js.coffee

to

items.js.coffee.erb

then you can add ruby to your javascript just like in your view with <%= %> tags. The only gotcha you might run into, is that your items.js file will be served to every request to any of your app's controller methods. So its best to write a helper method that will return the value only if the instance variable is initialized

For example in items_helper.rb

def item_price
    if @item
        @item.base_price
    else
        0
    end
end

EDIT: more about assets pipeline here:

http://guides.rubyonrails.org/asset_pipeline.html

like image 112
Matthew Avatar answered Feb 25 '23 17:02

Matthew