How to use I18n from controller in Rails - ruby-on-rails

I have a PetsController in which a flash message is setted. Something like this:
class PetsController
...
def treat_dog
#do somthing
flash[:success] = 'Your dog is being treated.'
end
...
end
this controller belongs to Admin, so it is located at: app/controllers/admin/pets_controller.rb. I will use I18n, so I replaced the string in controller with t('controllers.admin.pet.treated'), then,I wrote this yml:
en:
controllers:
admin:
pet:
treated: "Your dog is being treated."
located at: config/locales/controllers/admin/pet/en.yml and it did not work. I have attempted locating it at config/locales/controllers/admin/pets/en.yml, config/locales/controllers/admin/en.yml
config/locales/controllers/en.yml
and none of these worked, the translation is not found.
How can I use a translation from this controller?

In controller you use it like this
I18n.t 'controllers.admin.pet.treated'
Using t() directly enables lazy loading:
t(".treated") #loads from key: controllers.admin.pet.treated

def treat_dog
#do somthing
flash[:success] = t('controllers.admin.pet.treated')
end

Put it into config/locales/en.yml and it should work (you may need to restart the server).
This guide should help clear the head about I18n. I'm giving link to relevant section, but read it in full: http://guides.rubyonrails.org/i18n.html#adding-translations
If you insist on using nested files, you need to enable it. Documentation says:
The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further:
# config/application.rb
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]

In callback it should be:
add_breadcrumb proc{ I18n.t('home_page') }, :root_path

Related

Displaying GET request from HTTparty on view

I currently have a simple ruby file named example.rb. How can I make a view that allows a user to submit information into a form and then have the information from the GET request returned to them? I understand how to use these requests from the console, but not from the front-end.
Resources on this topic would also be greatly appreciated.
require 'rubygems'
require 'httparty'
class StackExchange
include HTTParty
base_uri 'api.stackexchange.com'
def initialize(service, page)
#options = {query: {site: service}}
end
def questions
self.class.get('/2.2/questions', #options)
end
def users
self.class.get('/2.2/users', #options)
end
end
stack_exchange = StackExchange.new('stackoverflow',1)
puts stack_exchange.users
Make sure the HTTParty gem is in your application's Gemfile.
Take example.rb and put it in /app/models/stack_exchange.rb — yes the file name does matter[0] (this isn't the purists place to put this, but for beginners it's fine and perfectly acceptable). Remove the code at the bottom you're using to test it as well.
in routes.rb add this route: get '/test' => 'application#test'
in your application_controller.rb add this method:
def test
stack_client = StackExchange.new('stackoverflow', 1)
#users = stack_client.users
end
in app/views/application/test.html.erb put the following:
<% #users.each do |user| %><%=user.inspect%><br/><br/><% end %>
Note: I would otherwise recommend adding views to ApplicationController but because I don't know anything about your application, I'll default to it.
hit http://localhost:3000/test and you should see the expected result.
[0] Rails does a lot "magic" under the scenes — it's really not magic but metaprogramming — where it tries to assume a lot of things about your application structure and naming conventions. If your class was named Stackexchange (note the lowercase e), stackexchange.rb would be automatically "mapped" to the class Stackexchange. More info: http://guides.rubyonrails.org/autoloading_and_reloading_constants.html

Localization of custom validations

I'm working on a project in which I'd like to move all strings used in the app to a single file, so they can be easily changed and updated. However I'm having trouble with the custom validation. I have validations in my app as follows:
validate :thing_is_correct
def thing_is_correct
unless thing.is_correct
errors[:base] << "Thing must be correct"
end
end
I'm not sure how to move "Thing must be correct" into my en.yml file and out of the model. Any help would be greatly appreciated.
The Rails Way to do that would be to use the mechanism described in the Guides.
errors is an instance of ActiveModel::Errors. New messages can be added by calling ActiveModel::Errors#add. As you can see in the docs, you can not only pass a message but also a symbol representing the error:
def thing_is_correct
unless thing.is_correct?
errors.add(:thing, :thing_incorrect)
end
end
Active Model will automatically try fetching the message from the namespaces described in the Guides (see the link above). The actual message is generated using ActiveModel::Errors#generate_message.
To sum up:
Use errors.add(:think, :thing_incorrect)
Add thing_incorrect under one of the YAML keys listed in the Guides.
You can access the I18n inside the model.
validate :thing_is_correct
def thing_is_correct
unless thing.is_correct
errors[:base] << I18n.t('mymodel.mymessage')
end
end
Inside config/locales/en.yml
en:
mymodel:
mymessage: "Thing must be correct"
Inside another locale: (config/locales/es.yml)
es:
mymodel:
mymessage: "Esto debe ser correcto"
If you set I18n.locale = :en, the message inside en.yml will be displayed. If you set it to :es, the one inside es.yml will be used instead.

Rails i18n: Translation missing problem, locale not defined

I have a problem with a Rails 2.3.8 application. I'm using rails i18n to make the site in different languages. Everything works perfect, everywhere, except one place.
After successful signup, I do:
flash[:notice] = t 'path.to.locale.key'
Just as I do everywhere else.
But that renders the following:
translation missing: 'locale.path.to.locale.key' not found
It seems it's not loading the current locale (or else it will say 'en', or 'es', or whatever instead of 'locale').
Any idea that could be causing this?
Thanks
Maybe you overwrite it somewhere down that yml file. Maybe you did too many nesting. Maybe that key has subkeys.
Delete everything from that locale.yml and place only that message and see if it works.
The problem you are having happens to me every now and then, and it's always something I messed up in yml file.
Try setting a default locale in your ApplicationController, for example with a before_filter:
I18n.locale = params[:locale] || 'en'
Well, this happened to me in mailer classes after I upgraded to Rails 4.1. It was working correctly on Rails 3 and there was no change on yml files. Somehow i18n did not see the default locale.
So I've added this line on mailer class to fix out.
I18n.locale = I18n.default_locale
class ProviderMailer < ActionMailer::Base
include Resque::Mailer
default from: APP_CONFIG.mailer.from
def registration_email(provider)
#provider = provider
I18n.locale = I18n.default_locale
#provider_url = "#{APP_CONFIG.base_url}/hizmetsgl/#{provider['_id']}"
#howto_url = "#{APP_CONFIG.base_url}/hizmetverenler"
mail(to: provider["business_email"], subject: t('provider_mailer.registration_email.subject'))
end
end

How to use i18n key as default translation in Rails 3?

For example:
I18n.t('something')
should output only
something
if the translation missing.
It is possible:
See section 4.1.2 Defaults at Rails Internationalization (I18n) API.
I18n.t :missing, :default => 'Not here'
# => 'Not here'
On rails 4 you can change the exception handler.
Add the following to config/initializers/i18n.rb:
module I18n
class MissingTranslationExceptionHandler < ExceptionHandler
def call(exception, locale, key, options)
if exception.is_a?(MissingTranslation)
key
else
super
end
end
end
end
I18n.exception_handler = I18n::MissingTranslationExceptionHandler.new
Now on you views you can just do:
<p><%= t "Not translated!" %></p>
Guide on the subject: http://guides.rubyonrails.org/i18n.html#using-different-exception-handlers
side-note:
this might help figuring out what Rails thinks the current scope is (e.g. when using ".something")
http://unixgods.org/~tilo/Rails/which_l10n_strings_is_rails_trying_to_lookup.html
this way you can better avoid having missing translations because of incorrect placing of translations strings in the L10n-file / incorrect keys
David's answer is the right solution to the question, another (more verbose) way to do it is to rescue and return the key:
def translate_nicely(key)
begin
I18n.translate!(key)
rescue
key
end
end
nope, not possible. If you use I18 you need to have a file that corresponds to the language otherwise I18n will complain.
Of course you can set the default language in your environment.rb file. Should be near the bottom and you can set this for whatever language you want but in your locales/ folder you will need to have a corresponding yml translation.

Can a mobile mime type fall back to "html" in Rails?

I'm using this code (taken from here) in ApplicationController to detect iPhone, iPod Touch and iPad requests:
before_filter :detect_mobile_request, :detect_tablet_request
protected
def detect_mobile_request
request.format = :mobile if mobile_request?
end
def mobile_request?
#request.subdomains.first == 'm'
request.user_agent =~ /iPhone/ || request.user_agent =~ /iPod/
end
def detect_tablet_request
request.format = :tablet if tablet_request?
end
def tablet_request?
#request.subdomains.first == 't'
request.user_agent =~ /iPad/
end
This allows me to have templates like show.html.erb, show.mobile.erb, and show.tablet.erb, which is great, but there's a problem: It seems I must define every template for each mime type. For example, requesting the "show" action from an iPhone without defining show.mobile.erb will throw an error even if show.html.erb is defined. If a mobile or tablet template is missing, I'd like to simply fall back on the html one. It doesn't seem too far fetched since "mobile" is defined as an alias to "text/html" in mime_types.rb.
So, a few questions:
Am I doing this wrong? Or, is there a better way to do this?
If not, can I get the mobile and tablet mime types to fall back on html if a mobile or tablet file is not present?
If it matters, I'm using Rails 3.0.1. Thanks in advance for any pointers.
EDIT: Something I forgot to mention: I'll eventually be moving to separate sub-domains (as you can see commented out in my example) so the template loading really needs to happen automatically regardless of which before_filter has run.
Possible Duplicate of Changing view formats in rails 3.1 (delivering mobile html formats, fallback on normal html)
However, I struggled with this exact same problem and came up with a fairly elegant solution that met my needs perfectly. Here is my answer from the other post.
I think I've found the best way to do this. I was attempting the same thing that you were, but then I remembered that in rails 3.1 introduced template inheritance, which is exactly what we need for something like this to work. I really can't take much credit for this implementation as its all laid out there in that railscasts link by Ryan Bates.
So this is basically how it goes.
Create a subdirectory in app/views. I labeled mine mobile.
Nest all view templates you want to override in the same structure format that they would be in the views directory. views/posts/index.html.erb -> views/mobile/posts/index.html.erb
Create a before_filter in your Application_Controller and do something to this effect.
before_filter :prep_mobile
def is_mobile?
request.user_agent =~ /Mobile|webOS|iPhone/
end
def prep_mobile
prepend_view_path "app/views/mobile" if is_mobile?
end
Once thats done, your files will default to the mobile views if they are on a mobile device and fallback to the regular templates if a mobile one is not present.
You need to do several things to wire this up, but the good news is that Rails 3 actually makes this a lot simpler than it used to be, and you can let the router do most of the hard work for you.
First off, you need to make a special route that sets up the correct mime type for you:
# In routes.rb:
resources :things, :user_agent => /iPhone/, :format => :iphone
resources :things
Now you have things accessed by an iphone user agent being marked with the iphone mime type. Rails will explode at you for a missing mime type though, so head over to config/initializers/mime_types.rb and uncomment the iphone one:
Mime::Type.register_alias "text/html", :iphone
Now you're mime type is ready for use, but your controller probably doesn't yet know about your new mime type, and as such you'll see 406 responses. To solve this, just add a mime-type allowance at the top of the controller, using repsond_to:
class ThingsController < ApplicationController
respond_to :html, :xml, :iphone
Now you can just use respond_to blocks or respond_with as normal.
There currently is no API to easily perform the automatic fallback other than the monkeypatch or non-mime template approaches already discussed. You might be able to wire up an override more cleanly using a specialized responder class.
Other recommended reading includes:
https://github.com/plataformatec/responders
http://www.railsdispatch.com/posts/rails-3-makes-life-better
Trying removing the .html from the .html.erb and both iPhone and browser will fallback to the common file.
I have added a new answer for version 3.2.X. This answer is valid for <~ 3.0.1.
I came to this question while looking to be able to have multiple fallbacks on the view. For example if my product can be white-labeled and in turn if my white-label partner is able to sell sponsorship, then I need a cascade of views on every page like this:
Sponsor View: .sponsor_html
Partner View: .partner_html
Default View: .html
The answer by Joe, of just removing .html works (really well) if you only have one level above the default, but in actual application I needed 5 levels in some cases.
There did not seem to be anyway to implement this short of some monkey patching in the same vein as Jeremy.
The Rails core makes some fairly wide ranging assumptions that you only want one format and that it maps to a single extension (with the default of NO extension).
I needed a single solution that would work for all view elements -- layouts, templates, and partials.
Attempting to make this more along the lines of convention I came up with the following.
# app/config/initializers/resolver.rb
module ActionView
class Base
cattr_accessor :extension_fallbacks
##extension_fallbacks = nil
end
class PathResolver < Resolver
private
def find_templates_with_fallbacks(name, prefix, partial, details)
fallbacks = Rails.application.config.action_view.extension_fallbacks
format = details[:formats].first
unless fallbacks && fallbacks[format]
return find_templates_without_fallbacks(name, prefix, partial, details)
end
deets = details.dup
deets[:formats] = fallbacks[format]
path = build_path(name, prefix, partial, deets)
query(path, EXTENSION_ORDER.map {|ext| deets[ext] }, details[:formats])
end
alias_method_chain :find_templates, :fallbacks
end
end
# config/application.rb
config.after_initialize do
config.action_view.extension_fallbacks = {
html: [:sponsor_html, :partner_html, :html],
mobile: [:sponsor_mobile, :partner_mobile, :sponsor_html, :partner_html, :html]
}
# config/initializers/mime_types.rb
register_alias 'text/html', :mobile
# app/controllers/examples_controller.rb
class ExamplesController
respond_to :html, :mobile
def index
#examples = Examples.all
respond_with(#examples)
end
end
Note: I did see the comments around alias_method_chain, and initially did make a call to super at the appropriate spot. This actually called ActionView::Resolver#find_templates (which raises a NotImplemented exception) rather than the ActionView::PathResolver#find_templates in some cases. I wasn't patient enough to track down why. I suspect its because of being a private method.
Plus, Rails, at this time, does not report alias_method_chain as deprecated. Just that post does.
I do not like this answer as it involves some very brittle implementation around that find_templates call. In particular the assumption that you only have ONE format, but this is an assumption made all over the place in the template request.
After 4 days of trying to solve this and combing through the whole of the template request stack its the best I can come up with.
The way that I'm handling this is to simply skip_before_filter on those requests that I know I want to render the HTML views for. Obviously, that will work with partials.
If your site has a lot of mobile and/or tablet views, you probably want to set your filter in ApplicationController and skip them in subclasses, but if only a few actions have mobile specific views, you should only call the before filter on those actions/controllers you want.
If your OS has symlinks you could use those.
$ ln -s show.html.erb show.mobile.erb
I am adding another answer now that we have updated to 3.2.X. Leaving the old answer as it was in case someone needs that one. But, I will edit it to direct people to this one for current versions.
The significant difference here is to make use of the "new" (since 3.1) availability of adding in custom path resolvers. Which does make the code shorter, as Jeroen suggested. But taken a little bit further. In particular the #find_templates is no longer private and it is expected that you will write a custom one.
# lib/fallback_resolver.rb
class FallbackResolver < ::ActionView::FileSystemResolver
def initialize(path, fallbacks = nil)
#fallback_list = fallbacks
super(path)
end
def find_templates(name, prefix, partial, details)
format = details[:formats].first
return super unless #fallback_list && #fallback_list[format]
formats = Array.wrap(#fallback_list[format])
details_copy = details.dup
details_copy[:formats] = formats
path = Path.build(name, prefix, partial)
query(path, details_copy, formats)
end
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
append_view_path 'app/views', {
mobile: [:sponsor_mobile, :mobile, :sponsor_html, :html],
html: [:sponsor_html, :html]
}
respond_to :html, :mobile
# config/initializers/mime_types.rb
register_alias 'text/html', :mobile
Here's a simpler solution:
class ApplicationController
...
def formats=(values)
values << :html if values == [:mobile]
super(values)
end
...
end
It turns out Rails (3.2.11) adds an :html fallback for requests with the :js format. Here's how it works:
ActionController::Rendering#process_action assigns the formats array from the request (see action_controller/metal/rendering.rb)
ActionView::LookupContext#formats= gets called with the result
Here's ActionView::LookupContext#formats=,
# Override formats= to expand ["*/*"] values and automatically
# add :html as fallback to :js.
def formats=(values)
if values
values.concat(default_formats) if values.delete "*/*"
values << :html if values == [:js]
end
super(values)
end
This solution is gross but I don't know a better way to get Rails to interpret a request MIME type of "mobile" as formatters [:mobile, :html] - and Rails already does it this way.
Yes, I'm pretty sure this is the right way to do this in rails. I've defined iphone formats this way before. That's a good question about getting the format to default back to :html if a template for iphone doesn't exist. It sounds simple enough, but I think you'll have to add in a monkeypath to either rescue the missing template error, or to check if the template exists before rendering. Take a look a the type of patches shown in this question. Something like this would probably do the trick (writing this code in my browser, so more pseudo code) but throw this in an initializer
# config/initializers/default_html_view.rb
module ActionView
class PathSet
def find_template_with_exception_handling(original_template_path, format = nil, html_fallback = true)
begin
find_template_without_exception_handling(original_template_path, format, html_fallback)
rescue ActionView::MissingTemplate => e
# Template wasn't found
template_path = original_template_path.sub(/^\//, '')
# Check to see if the html version exists
if template = load_path["#{template_path}.#{I18n.locale}.html"]
# Return html version
return template
else
# The html format doesn't exist either
raise e
end
end
end
alias_method_chain :find_template, :exception_handling
end
end
Here is another example of how to do it, inspired by Simon's code, but a bit shorter and a bit less hacky:
# application_controller.rb
class ApplicationController < ActionController::Base
# ...
# When the format is iphone have it also fallback on :html
append_view_path ExtensionFallbackResolver.new("app/views", :iphone => :html)
# ...
end
and somewhere in an autoload_path or explicitly required:
# extension_fallback_resolver.rb
class ExtensionFallbackResolver < ActionView::FileSystemResolver
attr_reader :format_fallbacks
# In controller do append_view_path ExtensionFallbackResolver.new("app/views", :iphone => :html)
def initialize(path, format_fallbacks = {})
super(path)
#format_fallbacks = format_fallbacks
end
private
def find_templates(name, prefix, partial, details)
fallback_details = details.dup
fallback_details[:formats] = Array(format_fallbacks[details[:formats].first])
path = build_path(name, prefix, partial, details)
query(path, EXTENSION_ORDER.map { |ext| fallback_details[ext] }, details[:formats])
end
end
The above is still a hack because it is using a private API, but possibly less fragile as Simon's original proposal.
Note that you need to take care of the layout seperately. You will need to implement a method that chooses the layout based on the user agent or something similar. The will only take care of the fallback for the normal templates.
Rails 4.1 includes Variants, this is a great feature that allow you to set different views for the same mime. You can now simply add a before_action and let the variant to do the magic:
before_action :detect_device_variant
def detect_device_variant
case request.user_agent
when /iPad/i
request.variant = :tablet
when /iPhone/i
request.variant = :phone
end
end
Then, in your action:
respond_to do |format|
format.json
format.html # /app/views/the_controller/the_action.html.erb
format.html.phone # /app/views/the_controller/the_action.html+phone.erb
format.html.tablet do
#some_tablet_specific_variable = "foo"
end
end
More info here.
You can in this case for the format to html. By example you want always use the html in user show method
class UserController
def show
..your_code..
render :show, :format => :html
end
end
In this case, if you request show on User controller you render all the time the html version.
If you want render JSON too by example you can made some test about your type like :
class UserController
def show
..your_code..
if [:mobile, :tablet, :html].include?(request.format)
render :show, :format => :html
else
respond_with(#user)
end
end
end
I made a monkey patch for that, but now, I use a better solution :
In application_controller.rb :
layout :which_layout
def which_layout
mobile? ? 'mobile' : 'application'
end
With the mobile? method you can write.
So I have a different layout but all the same views, and in the mobile.html.erb layout, I use a different CSS file.
I need the same thing. I researched this including this stack overflow question (and the other similar one) as well as followed the rails thread (as mentioned in this question) at https://github.com/rails/rails/issues/3855 and followed its threads/gists/gems.
Heres what I ended up doing that works with Rails 3.1 and engines. This solution allows you to place the *.mobile.haml (or *.mobile.erb etc.) in the same location as your other view files with no need for 2 hierarchies (one for regular and one for mobile).
Engine and preparation Code
in my 'base' engine I added this in config/initializers/resolvers.rb:
module Resolvers
# this resolver graciously shared by jdelStrother at
# https://github.com/rails/rails/issues/3855#issuecomment-5028260
class MobileFallbackResolver < ::ActionView::FileSystemResolver
def find_templates(name, prefix, partial, details)
if details[:formats] == [:mobile]
# Add a fallback for html, for the case where, eg, 'index.html.haml' exists, but not 'index.mobile.haml'
details = details.dup
details[:formats] = [:mobile, :html]
end
super
end
end
end
ActiveSupport.on_load(:action_controller) do
tmp_view_paths = view_paths.dup # avoid endless loop as append_view_path modifies view_paths
tmp_view_paths.each do |path|
append_view_path(Resolvers::MobileFallbackResolver.new(path.to_s))
end
end
Then, in my 'base' engine's application controller I added a mobile? method:
def mobile?
request.user_agent && request.user_agent.downcase =~ /mobile|iphone|webos|android|blackberry|midp|cldc/ && request.user_agent.downcase !~ /ipad/
end
And also this before_filter:
before_filter :set_layout
def set_layout
request.format = :mobile if mobile?
end
Finally, I added this to the config/initializers/mime_types.rb:
Mime::Type.register_alias "text/html", :mobile
Usage
Now I can have (at my application level, or in an engine):
app/views/layouts/application.mobile.haml
and in any view a .mobile.haml instead of a .html.haml file.
I can even use a specific mobile layout if I set it in any controller:
layout 'mobile'
which will use app/views/layouts/mobile.html.haml (or even mobile.mobile.haml).
I solved this problem by using this before_filter in my ApplicationController:
def set_mobile_format
request.formats.unshift(Mime::MOBILE) if mobile_client?
end
This puts the mobile format to the front of the list of acceptable formats. So, the Resolver prefers .mobile.erb templates, but will fall back to .html.erb if no mobile version is found.
Of course, for this to work you need to implement some kind of #mobile_client? function and put Mime::Type.register_alias "text/html", :mobile into your config/initializers/mime_types.rb

Resources