Rails 4 Manage File based Translations at Admin End - ruby-on-rails-4

I am working on a rails website and I need to make it multilingual. I have created yml files for the languages needed for translation.
What I want is to provide the Admin access to files to edit them instead of browsing through the files, by a section in Admin panel. Is there any gem for managing translations through Admin end.
I have never implemented translations before.

By default Rails uses YAML files to store internationalization information. But we are not restricted to use YAML (that is only capable of reading translations but cannot dynamically store them). We can use any database as backend.
To start, you can use this gem: https://github.com/svenfuchs/i18n-active_record
You can change the default backend like that:
I18n.backend = Globalize::Backend::Static.new
You can also use Chan backend to chain multiple backends together.
# config/initializers/locale.rb
I18n.backend = I18n::Backend::Chain.new(I18n::Backend::ActiveRecord.new, I18n.backend)
But, As the translations are accessed frequently in every request page, ActiveRecord is not the best approach. For these reason, a key-value store is the way to go.
You can use Redis database for this:
First install Redis
$ brew install redis
Install redis gem:
# Gemfile
source 'http://rubygems.org'
# ...
gem 'redis'
Now you can change the backend like that:
# config/initializers/locale.rb
I18n.backend = I18n::Backend::KeyValue.new(Redis.new)
Code to add translation:
# /app/views/admin/translations/index.html.erb
<%= form_tag admin_translations_path do %>
<p>
<%= label_tag :locale %><br>
<%= text_field_tag :locale %>
</p>
<p>
<%= label_tag :key %><br>
<%= text_field_tag :key %>
</p>
<p>
<%= label_tag :value %><br>
<%= text_field_tag :value %>
</p>
<p><%= submit_tag "Submit" %></p>
<% end %>
This form will POST to admin/TranslationsController's create action:
# /app/controllers/admin/translations_controller.rb
module Admin
class TranslationsController < ApplicationController
# ....
def create
I18n.backend.store_translations(params[:locale]), {params[:key] => params[:value]}, escape: false)
redirect_to admin_translations_path, notice: "Translation Added"
end
end
end
You can also use redis-i18n gem to do the same: https://github.com/redis-store/redis-i18n

Related

PDF rendering hangs rails 4 server

I have a Rails app, in which I need to render one of the views as a downloadable PDF. The view itself is composed of many partials, which in turn are composed of more partials and so on. This is the top-level view:
<meta charset="utf-8" />
<%= javascript_include_tag "jquery-ui.min", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "report", media: "all", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag "report_style", media: "all", "data-turbolinks-track" => true %>
<div class="report">
<%= render partial: "details", locals: { examinee: #examinee, te: #test_event } %>
<div class="page-break"></div>
<%= render partial: "grades", locals: { scores: #test_event.scores, tasks: Task.tasks_for_report(#test_event.language) } %>
<div class="page-break"></div>
<%= render partial: "ld", locals: { test_event: #test_event } %>
<%= render partial: "review", locals: { test_event: #test_event } %>
<div class="page-break"></div>
<%= render partial: "appendix" %>
</div>
Due to the complexity of the rendered view, I prefer generating a PDF from html over writing everything twice, once as .html.erb and again as pdf.erb.
I have tried both pdfkit and wickedpdf, but in both cases I have failed:
pdfkit gets my Thin server hanged, no matter what I tried - None of the solutions suggested here, here and here had any impact, things still suck.
wicked_pdf has actually managed to generate a PDF, but then again it ignored all of my css and js code, even when called with wicked_pdf_javascript_include_tag and its corresponding css twin. This can't go as I need my page breaks and all of the content created by the various js scripts (for example, some plots which are made by chartist).
Any Ideas?
If you are running Rails with a single-threaded webserver (like webrick), and your PDF generation process involves getting data from another endpoint in your app (like AJAX in your JavaScript), it is going to hang in a deadlock, because the request for the asset to build your PDF is queued behind the actual building of the PDF.
It should work just fine in production because most production environments are setup to run multiple web workers (with passenger or unicorn or something), but to properly test this in development mode, you'll need to configure your app to run multiple web workers, so your Ajax request can happen in another thread and return back to your main request.
I would suggest you add the puma gem to your Gemfile, and run your dev server with rails server Puma --workers 3 (by the way, puma is included by default in new Rails 5 apps because people were having this same issue with ActionCable requests).
wicked_pdf_javascript_include_tag is provided to read from disk for extra speed in building your PDF, and does have some issues with a few libraries, and depending on your config, may require your JS and CSS to be named in the config.assets.precompile list.

Rails controller specific assets for selected controllers only

I want to use the controller specific assets only for some controllers, but not for all. Hence, I didn't add the assets for which I don't need separate files. But this leads to 404 for those resources as they are not present, e.g. my app/views/layouts/dashboard.html.erb file contains the following piece of code to generate the controller specific js/css:
<%= stylesheet_link_tag 'dashboard', params[:controller], media: 'all' %>
<%= javascript_include_tag 'dashboard', params[:controller] %>
However, I do not want to create separate files for Admin controller, as the admins page has no new css/js required. But, app tries to locate the assets for the controller and since not found it returns the 404 as follows:
GET http://dashboard.localhost.com:3000/stylesheets/dashboard/admins.css 404 (Not Found)
GET http://dashboard.localhost.com:3000/javascripts/dashboard/admins.js 404 (Not Found)
What should be done to prevent this?
Moreover, there are a few controllers for which the assets are obviously not required, e.g. Registrations controller, leading to 404 for http://0.0.0.0:3000/stylesheets/store/registrations.css for http://0.0.0.0:3000/account/edit page
Here is what I did to fix this in my application.html.erb:
<%= stylesheet_link_tag 'dashboard' %>
<%= stylesheet_link_tag params[:controller] if InmonarchWebsite::Application.assets.find_asset("#{params[:controller]}.css") %>
<%= javascript_include_tag 'dashboard' %>
<%= javascript_include_tag params[:controller] if InmonarchWebsite::Application.assets.find_asset("#{params[:controller]}.js") %>

Uploading a file without a form - Rails

Ruby 2.1
Rails 4.1
It should be pretty simple to upload a file without using any gems. I would include in a form something like this:
<% form_for #upload, :multipart => true do |f| %>
<%= f.file_field :uploaded_file %>
<%= f.submit "Upload file" %>
<% end %>
What I want to do is upload the file through a single menu action. How do I go about doing this?

Showing Spree taxonomy tree on product page

I'm running Spree 2.2. I'm trying to get the standard taxonomy/filter list to appear on each individual product page in Spree, but I cannot find where it decides that there's sidebar content to be displayed. If anyone can shed any light on where/how that's decided I'd be most grateful.
On the front-end part of spree, more specific, on the index view of the products controller, route spree_frontend/app/views/spree/products/index.html.erb at the beginning of the file, it get's decided whether there will be displayed the taxons or not:
<% content_for :sidebar do %>
<div data-hook="homepage_sidebar_navigation">
<% if "spree/products" == params[:controller] && #taxon %>
<%= render :partial => 'spree/shared/filters' %>
<% else %>
<%= render :partial => 'spree/shared/taxonomies' %>
<% end %>
</div>
<% end %>
So what you can do is to write an override pointing at any part of the products/show view, in particular i suggest after the product_left_part_wrap" data-hook, wich is a wrapper for the sidebar on the products show view, so your deface could look something like this:
Deface::Override.new(
:virtual_path => 'spree/products/show',
:name => 'add_map_to_product_show',
:insert_after => '[data-hook="product_left_part_wrap"]',
:partial => "spree/products/the_taxons_and_filters"
)
And inside the file named _the_taxons_and_filters.html.erb located on app/views/spree/products/ you can add the code from above and include the taxons filters. Hope this was helpful.

Dropdown select list won't display items with custom forms of Zurb Foundation 4 and Rails 4

I've been having this annoying problem in which I click over a select dropdown input of my custom form, styled with Zurb Foundation 4 in my Rails application, and the list won't show its elements.
I thought at a start that was a problem with simple form, but I changed the f.association for f.collection_select, my code looks like this:
<h2><%= I18n.t(".sign_up") %></h2>
<%= simple_form_for(resource, :html => {:class => "custom"}, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<%= devise_error_messages! %>
<%= f.input :rut %>
<%= f.input :name %>
<%= f.input :email %>
<div>
<%= f.label :supplier_type_id %>
<%= f.collection_select :supplier_type_id, SupplierType.all, :id, :name %>
</div>
<%= f.input :password %>
<%= f.input :password_confirmation %>
<%= f.error :base %>
<%= f.submit I18n.t(".sign_up"), :class => "button" %>
<% end %>
<%= render "devise/shared/links" %>
The most strange thing is that sometimes I'm able to see the items when refreshing the page, but when I get to the page navigating from other view of the app then it won't work. I've also noticed this when using hints for forms (i.e: If I have two hints in the same form, in different inputs, only one would show, but the same one message displays in both inputs when each message should show in their respective input. When reloading the page sometimes it shows one hint, and sometimes the other)
The styling looks good, so I think that it might be a foundation javascript problem.
Another thing I've noticed is that when I load the page the styling does a kind of "blinking" when using custom forms. This blinking it looks likes foundation takes a while to load the styling, I've also noticed this on their own custom form documentation site. This may indicate that is a form styled with javascript events or something similar, so this might mean that javascript is working well.
In addition, the checkboxes are having a similar problem, they only can be checked just when you reload the page, it might have some relation with this problem.
I'm very lost, some help would become very handy. Thanks!
--edit: Foundation 5 doesn't include custom forms and works better--
You might need to refresh dropdowns on each page:change event. Try something like this:
$(document).on("page:change", function() {
// SELECTOR_TO_CUSTOM_DROPDOWNS should select any Zurb custom dropdowns you
// are using.
$(SELECTOR_TO_CUSTOM_DROPDOWNS).trigger("change");
});
That's from the documentation on Zurb custom form JS.
Yes, this is caused by turbolinks. It stops $(document).ready from firing on page load, which is required by foundation's custom forms.
Using ssorallen's answer and to be more unobtrusive than the OPs, add this to application.js:
$(function(){ $(document).foundation(); });
$(document).on("page:change", function() {
if ($('form.custom').length > 0) {
$(document).foundation('forms');
}
});
Also, if you have jquery/coffeescript that relies on document ready being fired, add jquery turbolinks to your Gemfile.
Ok, so I just figured out that I have repeated asset load on my browser. This is causing a javascript error. It appears that deleting in the manifest
//= require turbolinks
Solves the problem.
I solved my multiple asset problem changing
<%= javascript_include_tag "application" %>
To the head in my application layout.
After watching the turbolinks railscast I noticed that besides my multiple asset loading, turbolinks and foundation 4 may not be compatible, it might be a solution on this post. But still doesn't work perfect for me.
I also noticed that navbar is also affected by turbolinks.
I think that this is rather a turbolinks problem and not an specific foundation dropdown. I will close this question and open a new on turbolinks and foundation.
Thanks to some Nick Reed insights I found out that the foundation gem was initializing foundation in application.js like this:
$(function(){ $(document).foundation(); });
So I checked the docs and I used this:
<script>
$(document).foundation();
</script>
After the "/body" tag in the application layout and everything seems to be working like a charm!