CoffeeControllers::Rails

By Ima Bold.

With CoffeeControllers, you can define your CoffeeScript scripts that are going to be ran specifically to the action being executed at the current request. So your scripts are better organized following convention over configuration.

Installation

Add this line to your application's Gemfile:

gem 'coffee_controllers-rails'

And then execute:

$ bundle install

Or install it yourself as:

$ gem install coffee_controllers-rails

It depends of coffee-rails that is also going to be installed.

Setup

In your application.js file, add:

//= require coffee_controllers/all

In your views layout file, say application.html.erb, add this to the body tag:

<body data-controller="<%= controller.controller_path %>"
      data-action="<%= controller.action_name %>">

This is required to keep track of which controller#action corresponds to the current request.

Usage

Suppose you have a rails controller HomeController with the action index:

class HomeController < ApplicationController
  def index
    # code...
  end
end

You can add a home.js.coffee file with:

# app/assets/javascripts/home.js.coffee

class HomeController
  index: ->
    alert 'Hello, world!'

setController 'home', new HomeController()

So, for every request to the index action, as soon as the DOM is ready, the index function will be ran, displaying the alert.

Remind

For every coffee controller defined, you need to attach it through the setController function.

# setController controllerName, controllerObject

setController 'foo', new FooController()

The controllerName has to be the name of the controller underscored. For example:

# class FooController < ApplicationController
setController 'foo', new FooController()

# class FooBarController < ApplicationController
setController 'foo_bar', new FooBarController()

# class Foo::BarHomeController < ApplicationController
setController 'foo_bar_home', new FooBarHomeController()

Init

You can define a init function to your coffee controllers that is going to be executed before every action function. For example:

class HomeController
  init: ->
    alert 'initializing...'

  index: ->
    alert 'index action'

  show: ->
    alert 'show action'

Reference

jerodsanto.net

Todo

  • Lacking some JS tests
  • Get rid of the setController step

Contributing

Questions or problems? Please post them on the issue tracker.

You can contribute by doing the following:

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

To test the application run bundle install and then rake test. It needs PhantomJS to be installed.

License

MIT License.