mixing clientside javascript template with rails logic for backbone.js - ruby-on-rails

I've worked a while now with Backbone.js, and one of the things I nowadays run into is; Sometimes you need to have serverside logic into a .eco.jst template
For example
an i18n translation (currently look at i18n.js gem for this)
a path a route without hardcoding it (somemodel_path(somemodel))
authorisation (for example, show a delete button if the user can destroy this model). Atm I solve this by passing in some rights object in the json that gets filled in.
Rendering a html helper like simple_form or S3_file_uploader (atm I solve this with rendering it serverside, and put the display on none)
As you know, .eco get parsed by node.js, so I can't call ruby in the eco files. Most of these problems I solve by basicly creating a "data" object in the head. Similar to this:
window.data = {
some_translation = "<%= t('cool') %>",
<%= "can_destoy_model = true," if can?('destroy', Model) %>
post_edit_link = "<%= post_path(#post) %>
}
Besides this being bulky (this is just an example, normally this would be more ordened or I add a html5 data attribute to some dom element), It's time consuming, sometimes you have to recreate complete business logic which otherwise would be a oneliner in rails (take for example the S3_file_uploader, which requires encoded amazon policyfile and a token)
What are your thoughts about this? Should I perhaps not use .eco (although I like templates in seperate files instead of poluting the view). Would I able to use serverside logic if I for instance used mustache or handlebars and which gem would you recommend if so?

My experience with Backbone.js is kind of limited, but I've managed to setup an environment with logic-less templates using the following gems:
handlebars_assets
haml_assets
And a bunch of other stuff, even a mini-framework I'm currently working on (you can find it here)
I picked this approach for building Single Page Applications using Backbone.
Basically, the haml_assets gem provides sprockets with the ability to parse .haml files, this is not needed but I love HAML syntax. The handlebars_assets gem provides means to parse Handlebars templates, both on the server-side and the client-side. You can use Ruby code inside the templates and you would solve both the i18n and the path methods problems you mentioned.
I've found these tools to be excellent to help DRY an application's templates, and it can really save you from adding logic inside templates. If you use Backbone Views to take, for example, decisions on whether to show a delete button or not, you can keep the logic inside the Backbone View, and use that logic to render the proper Handlebars template (or partial).
Using your example:
Coffeescript:
class ProjectShowView extends Backbone.View
template: (context) -> HandlebarsTemplates['projects/show'](context)
deleteButtonTemplate: (context) -> HandlebarsTemplates['projects/shared/delete_button'](context)
render: (canDelete = false) ->
#$el.html(#template(#model.toJSON()))
#$('.delete_button_container').append(#deleteButtonTemplate()) if canDelete
#
The example is quite primitive and basic, but can hopefully point in the right direction. I hope it helps!

Related

How to allow users to edit dynamic slim page templates in production for rails 4?

Essentially I'm trying to implement a way so that users can edit slim that is stored in the database.
For example they would use the form to create a new page and insert the html for that page in a text field which would be saved in the database. I want to allow them to edit that page in slim. By the way the html stored is slim not plain html.
If I store slim in the database how do I get rails to render the html properly on the client side in production? So in other words would rails automatically do this since the view is being render like so:
views/page/view.html.slim
page.header
page.content
page.footer
or would I have to figure out a way to convert on the fly? I might be making this more complicated then I should but I'm new to this
If I understand you correctly you want to convert the slim to Html and output that in your views.
This is directly from slims doc. This is how it processes slim files and outputs it.
Tilt.new['template.slim'].render(scope)
Slim::Template.new('template.slim', optional_option_hash).render(scope)
Slim::Template.new(optional_option_hash) { source }.render(scope)
so in short
Slim::Template.new(page/view.html.slim).render
put that in a module to make it prettier and I think you're good. You may want to use rails path helper to get the direct link for the view. You may also want to consider figuring out a way to catch the errors in indentation so that your output doesn't bug out in production. Some kind of validation that prevents it from saving if not properly formatted should help.

Backbone With Rails

I'm getting my data from a service and then setting the data to my bean object and want to using the same data in my view displaying it in a form in rails view now. Now I want to validate this form using backbone.
I'm new to both Rails and Backbone.
Kindly give me an idea on how to proceed on this.
I think perhaps you are confused about how web applications work. Backbone is a client-side framework; it uses Javascript code that is run in your users' browsers. Rails is a server-side framework; it uses Ruby code that runs on your server.
Given all that, your Backbone code and your Rails code by definition have to be completely separate. The two can communicate in only two ways:
1) Your Rails code can write <script> tags to the page (inside a .html.erb file) and put variable data there; for instance:
<script>
var myVarFromRails = '<%= someRailsVariable %>';
</script>
When that comes back from the server (ie. when you view source the page) that will get converted to:
<script>
var myVarFromRails = 'foo';
</script>
(assuming 'foo' was the value of someRailsVariable).
2) Your Javacript code can make AJAX requests to Rails URLs, and whatever the Rails code spits out there will come back as the response to your AJAX request. In other words you can do:
$.ajax({url: someRailsUrl, complete: function(response) {
// whatever the server sent back will be inside the "response" variable
}});
Other than that the two are pretty much entirely separate, and if you want to do the same thing in both of them (eg. validate a form) you essentially have to write the code twice, once for Ruby and once for Javascript.
I say "essentially" because there are Rails plug-ins which do #1 and #2 for you in different ways. I'm not a Rails expert, and even if I was there are so many of these plug-ins that you really need to look for yourself to find out what exists and what makes sense for your codebase.
Hope that helps.
* EDIT *
I know I just said I wouldn't list libraries, but then I realized it'd be more helpful if I at least provided a few to get you started. Just don't take these as canon; they're simply some popular libraries at the moment, but they may or may not be right for you.
https://github.com/codebrew/backbone-rails
https://github.com/meleyal/backbone-on-rails
https://github.com/aflatter/backbone-rails
https://learn.thoughtbot.com/products/1-backbone-js-on-rails
http://kiranb.scripts.mit.edu/backbone-slides/
That last two aren't actually libraries, they're a book/presentation, but I thought they might be useful.

Approach for AngularJS template translations with Rails server

I need to implement an application with multi-language support using an AngularJS front-end and a Ruby on Rails server.
I am looking for a reasonable approach to render translated templates in multiple languages. I have come up with an approach I would like feedback on.
In the Angular routes definitions, set the template property to an html partial that just has an ng-include with the src attribute value set by the controller. This approach is needed to dynamically modify the path to the template to be fetched from the server; it is described here:
AngularJS - How to use $routeParams in generating the templateUrl?
So the Angular route config would look like:
angular.module('myApp', []).
config(function ($routeProvider) {
$routeProvider.when('/sites/new', {
template: '<div ng-include src="templateUrl"></div>',
controller: 'RouteController'
});
});
And the controller would look like:
// Set a prefix on the URL path, something like “es”
function RouteController($scope, $routeParams) {
$scope.templateUrl = $routeParams.locale + "/template/sites/site";
}
Here $routeParams.locale is used to set the locale, but could be a variable set by user action. The approach for dynamically modifying the template URL path to add a locale prefix seems a bit convoluted, but I know of no other way.
On the Rails side, in routes.rb, add a route:
match '/:locale/template/*template' => 'template#get'
The route uses route globbing so the params[:template] value can be a multi-level path.
The TemplateController#get action just renders the partial determined by params[:template]
The Template controller code is something like:
class TemplateController < ApplicationController
layout false
caches_page :get
def get
render(template: "template/#{params[:template]}")
end
end
The Rails I18n support for translations is used in the erb templates, translating according to the locale parameter.
In production, caching would be turned on. This would avoid incurring translation overhead. The locale prefix of the URL path would result in a per language set of translated templates to be cached.
This approach pushes translations processing to the server side as much as possible.
Is there any fundamental problems with this approach?
Could it be done better?
You may be interested in the angular-translate module.
We achieved client side internationalization in AngularJS with the i18next JQuery plugin http://i18next.com/ and created a filter called i18n.
When you initialize the Angular Application, you initialize the i18n plugin where you can provide a pattern to locate the file containing labels, and in the template use this as an example for binding labels and values.
{{'mynamespace:labels.firstname' | i18n}}
where "mynamespace" is used to separate your labels logically and used to locate JSON files with the labels. Within json files you can have one or more JSON objects with labels as properties. In the above example, the file called mynamespace-i18n-en-US.js if you provided a pattern __ns-i18n-__lng__.js
Is there a reason why the translation has to happen on the server?
Do you really need to translate the entire template?

Ember.js Handlebars globalization approach

I am trying to use ember.js in my Rails app.
Have a question specific to globalizing the handlerbars view template content.
Should I try to create myview.handlebars.erb and get the strings translated on the server side (havent tried this) or should I create seperate handlebars templates per each language (doesnt sound like really DRY unless there is a cleaner way)?
Whats the ideal way to go about it?
Did you get this working to your satisfactioin?
Another alternative (what we use at http://travis-ci.org) is i18n-js.
We like it because it lets you keep all your localizations in the same place (config/locales/[x].yml) and automatically adds them into your assets path.
Part of that DRY thing ;)
The syntax in your handlebars is pretty much the same, we just us a handlebars helper
Handlebars.registerHelper('i18n', function(key) {
return new Handlebars.SafeString(I18n.t(key))
});
and then {{i18n "path.to.translation"}} in the handlebars view.
Ember-I18n provides a solution: https://github.com/jamesarosen/ember-i18n

Rails: generating URLs for actions in JSON response

In a view I am generating an HTML canvas of figures based on model data in an app. In the view I am preloading JSON model data in the page like this (to avoid an initial request back):
<script type="text/javascript" charset="utf-8">
<% ActiveRecord::Base.include_root_in_json = false -%>
var objects = <%= #objects.to_json(:include => :other_objects) %>;
...
Based on mouse (or touch) interaction I want to redirect to other parts of my app that are controller specific (such as view, edit, delete, etc.).
Rather than hard code the URLs in my JavaScript I want to generate them from Rails (which means it always adapts the latest routes).
It seems like I have one of three options:
Add an empty attr to the model that the controller fills in with the appropriate URL (we don't want to use routes in the model) before the JSON is generated
Generate custom JSON where I add the different URLs manually
Generate the URL as a template from Rails and replace the IDs in JavaScript as appropriate
I am starting to lean towards #1 for ease of implementation and maintainability.
Are there any other options that I am missing? Is #1 not the best?
Thanks!
Chris
I wrote a bit about this on my blog: Rails Dilemma: HATEOAS in XML/JSON Responses.
I came to similar conclusions. There's no incredibly clean way to do it as far as I know, because by default the model is responsible for creating a JSON representation of itself, but generating URLs is strictly a controller/view responsibility.
Feel free to look over my thoughts/conclusions and add comments here or there.

Resources