Abhilash
Abhilash

Reputation: 2953

Best place to store angular files in rails

I am planning to convert my current app to an angular app. I never got a chance to work with angular along with rails before. I am planning to implement angular in the rails app feature by feature. But I am still concerned about the folder structure.

Is there any convention on where to keep the angular files inside rails application?

Also is angular a good candidate for this kind of development(feature by feature) or should I look into another technologies?

Upvotes: 1

Views: 42

Answers (1)

Mihai Dinculescu
Mihai Dinculescu

Reputation: 20033

FDD (feature by feature development) works well with MVC frameworks, and Angular is one of them.

It's generally advisable to store the JS files (any JS files, not just Angular) in app/assets/javascripts so that the Rails asset pipeline picks them up automatically. Other than this there's no convention, store them in whatever structure makes sense to you.

I am saying generally because if your Angular code grows large, you may be better off extracting it out of the app folder. You will then have to configure the asset pipeline to work with your new structure.

For small projects, I like to keep my Angular javascript files in app/assets/javascripts/angular

app/assets/javascripts/angular
    /controllers/
    /directives/
    /helpers/
    /models/
    /services/
    apps.js
    templates.js.erb

The views go in app/assets/templates.

One big hurdle that I've encountered was getting the Angular views to work with Rails' asset pipeline. In development you don't notice anything, but once you deploy in production, and the asset pipeline kicks in, Angular can't find the views anymore.

In order to make the asset pipeline serve the AngularJS views, I had to create a template cache.

// templates.js.erb
(function(){
    'use strict';

    // version 0.01
    // increase this every-time you deploy to production

    angular.module('templates', []).run(['$templateCache', function($templateCache) {
        <%
          environment.context_class.instance_eval { include ActionView::Helpers::JavaScriptHelper }
          app_root  = File.expand_path('../../../', __FILE__)
          templates = File.join(app_root, %w{templates ** *.html})

          Dir.glob(templates).each do |f|
            key  = f.gsub(%r(^#{app_root}/templates/), '')
            html = File.read(f).squish
        %>
        $templateCache.put("<%= key %>", "<%= escape_javascript(html) %>");
        <% end %>
    }]);
}());

You then have to inject templates in your modules

angular.module("myModule", ['templates']);

Upvotes: 1

Related Questions