Best ruby-on-rails-3.1 questions in July 2011

Does the asset pipeline rails 3.1 waste cycles?

13 votes

In rails 3.1, does .coffee and //= require files get processed only once or with each asset request?

For example,I have a file


//= require source/main.js.coffee
//= require source/second.js.coffee
//= require source/third.js.coffee

Ideally, the server would compile these to js ONCE, then bundle them, then create a static file. But if it happens on each asset requests,it's going to be wasting cycles repeating it??

Thanks for any guidance on this.

Yes, the assets will be compiled AND cached. So they won't generate additional cycles. You can also pre-compile them before you push them to production.

Here is a good writeup: http://blog.nodeta.com/2011/06/14/rails-3-1-asset-pipeline-in-the-real-world/

How do you write DRY, modular coffeescript with Sprockets in Rails 3.1?

6 votes

I'm in the early stages of trying to write some sensible Javascript. I want to namespace basically everything under the name of my application to avoid globals as much as possible, but still give me a way to access functions declared around the place. However, I don't want to be super verbose in my function definitions.

My ideal CoffeeScript would be something like this:

class @MyApp
  @myClassMethod = ->
    console.log 'This is MyApp.myClassMethod()'

  class @Module1
    @moduleMethod = ->
      console.log 'This is MyApp.Module1.moduleMethod()'

You get the picture. This way I avoid having to write MyApp.Module.submoduleMethod = -> every time I want to define a namespaced function properly - using @ and defining things within my class definition keeps things nice and short.

This is all going well until I want to split my functionality up into multiple CoffeeScript files. Then what I really want is something like this:

// application.js
class @MyApp
  //= require 'module1'
  //= require 'module2'

// module1.js
class @Module1
  @moduleMethod = ->
    console.log 'This is STILL MyApp.Module1.moduleMethod()'

It doesn't seem like Sprockets can do this.

Is there a sensible way to require my CoffeeScript files in the right place in my container files? Or another way to approach writing modular code that is divided into separate files using CoffeeScript, Sprockets and Rails 3.1?

I have a module solution that I use in my code.

I define my modules like below

@module "foo", ->
    @module "bar", ->
        class @Amazing
            toString: "ain't it"

Amazing is available as

foo.bar.Amazing

implementation of the @module helper is

window.module = (name, fn)->
  if not @[name]?
    this[name] = {}
  if not @[name].module?
    @[name].module = window.module
  fn.apply(this[name], [])

It's written up on the coffeescript website here.

https://github.com/jashkenas/coffee-script/wiki/Easy-modules-with-coffeescript