Skip to content

Instantly share code, notes, and snippets.

@cemeng
Created October 3, 2012 23:06
Show Gist options
  • Save cemeng/3830457 to your computer and use it in GitHub Desktop.
Save cemeng/3830457 to your computer and use it in GitHub Desktop.
Passing Rails variable/data to Coffeescript/Javascript

My problem

I need to access data from rails controller - currently, in my view I do this view.erb

app.factory "preloadedInvoice", ->
  <%= raw @job_invoice.to_json %>.job_invoice;

and this will allow preloadedInvoice to bebe used on the coffee/js file:

class @JobInvoice
  constructor: (credentials, preloadedInvoice, $http) ->
    angular.extend(this, preloadedInvoice)

Having the JS on the view feels wrong - but in this case we need to, because the: a. we can't access rails variables on the coffee file b. we need to access raw helper to generate html escaped JSON (this is a lesser of an issue I guess - could just require action_view probably?)

Some discussion:

Gon gem makes it cleaner from the code point of view - but it is essentially doing similar thing to what my previous approach but just streamlining it a little bit by putting on the application view helper.

Will try that for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment