Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access sinatra class variable in coffeescript template

How can I access ruby instance variable from within coffeescript template?

In sinatra documentation it's said that templates are evaluated within same scope as rout that invoke that template.

So, I have following sinatra app:

server.rb:

require "sinatra"
require "coffee-script"

get '/app.js' do
  @str = "Hello"
  coffee :app
end

and in views/app.coffe file I would like to use @strvariable. Is it possible? If so, how can I access @str variable?

like image 723
K. Kiełkowicz Avatar asked May 15 '26 17:05

K. Kiełkowicz


1 Answers

It could be possible only if you'll process coffee source file with something like erb. So if you'd use rails assets pipeline you can just append .erb to file extension and the file will be processed with erb before sending it to coffee I think in sinatra you'll have to wrap up something similar yourself.

The idea will be close to this one - http://www.sinatrarb.com/intro#Textile%20Templates

P.S: accessing variables from different layers of application is bad idea anyway.

EDIT

You have amultistage template compilation process in RAILS driven by a gem called sprockets. You start with a file for example called /app/views/foo/show.js.coffee.erb

class <%= @magic %>
    doSomthing: ->
        console.log "hello"

In your controller you add the instance variable

@magic = "Crazy"

Rails first processes the erb file and generates

class Crazy
    doSomething: ->
        console.log "hello"

Secondly it processes the coffeescript file to generate

var Crazy;
Crazy = (function() {
  function Crazy() {}
  Crazy.prototype.doSomething = function() {
    return console.log("hello");
  };
  return Crazy;
})();

That is why it is called the asset pipeline. More conventionally you could call it a compilation pipeline. If you know what you are doing you might be able to get sprockets running with Sinatra. However your life would be easier if you just used Rails 3.1 from the start.

like image 138
iafonov Avatar answered May 18 '26 10:05

iafonov