rails-js-routes
Check out the blog post!
NOTICE: We decided to rename this gem from rails-js
to rails-js-routes
as it was nearly impossible to find.
I worked on several Rails projects and there were many cases when it felt overkill to use a framework like Angular
or Ember
, because javascript was only needed in some parts of the application.
But by not using these frameworks I had to think of a way to structure the code by myself.
I came up with the conclusion to organize the javascript code like the ruby code is organized, that means: Split up in controllers, which are split up in actions.
How it works
- In
rails-js-routes
we are able to define controllers
, as well as helpers
. - Controllers have
actions
which are executed when the matching rails action is executed. - Helpers should be clear. Pretty much like the rails helpers. There are helper per controller and global helpers.
- The gem also provides a
view helper
to use in your layouts, which passes the routing information to rails-js-routes
.
You start by creating an app.
Rails.app({
helper: function() {
}
},
{
foo: 'bar'
},
function() {
console.log('beforeAll() executed');
});
Create controllers accordingly.
Rails.controller('users', {
new: function(h) {
h.awesomeHelper();
},
index: function(h) {
this.index(h);
}
},
{
awesomeHelper: function() {
}
});
Use code from other controllers.
Rails.controller('admin/users', {
new: function(h) {
R.action('users#new');
},
index: function(h) {
R.helper('users', 'awesomeHelper', 1, 2, 3);
R.global('helper', 1, 2, 3);
}
},{});
Global variables without the mess.
R('answer', 42);
R('a.global.variable', 'foo');
console.log(R('a.global.variable'));
Define hooks for namespaces.
Rails.namespace('admin', function() {
console.log('Hello Mr. Admin');
});
For more info...
...just read in app/assets/javascripts/routes.js
. I tried my best and documented nearly every line of code :)
Installing
Install it as any other gem by putting this to your Gemfile
:
gem 'rails-js-routes'
In your layouts, put this line into the head
:
<%= js_routes %>
Also make sure to include routes
in your application.js
. If you are using Turbolinks, make sure to include routes
after turbolinks
.
Testing
Javascript tests are in test/dummy/spec/javascripts/rails-js-routes_spec.js
.
They are executed using rake teaspoon
(by using the teaspoon runner).
I'm still trying to get travis to execute the teaspoon tests properly...
Contributing
Fork -> Commit -> Pull Request
This project uses the Airbnb Styleguide as our coding guideline.
We think this is a good piece of work and worth spreading.
In case of any doubts refer to the style used around.