K. Kiełkowicz
K. Kiełkowicz

Reputation: 31

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?

Upvotes: 3

Views: 1453

Answers (2)

Nate Kidwell
Nate Kidwell

Reputation: 21

I wrote this for Rails: https://github.com/ludicast/ice

but it can be easily adapted for Sinatra.

It lets you use Eco and CoffeeKup templates inside a Rails application, with the ruby models exposed to Coffeescript.

Nate

Upvotes: 1

iafonov
iafonov

Reputation: 5192

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.

Upvotes: 6

Related Questions