Middleman i18n not working - ruby-on-rails

I'm newbie using ruby and middleman, I've created my project and all are working fine, but when I go to /es path I don't get any translation. I've searched for info without any results and tried to move code between folders testing configs and nothing.
My folder structure is:
|locales
|---en.yml
|---es.yml
|source
|es
|---index.html.haml
|layouts
|---layout.html.haml
|partials
|_header.html.haml
|_navigation.html.haml
|---index.html.haml
My YAML files
en.yml
en:
home: 'Home'
es.yml
es:
home: 'Inicio'
My HAML
%nav
= link_to t(:home), '/', class: "#{'active' if current_page.url == '/'}"
= link_to 'Portfolio', '/portfolio', class: "#{'active' if current_page.url == '/portfolio/'}"
= link_to t(:skills), '/skills', class: "#{'active' if current_page.url == '/skills/'}"
= link_to t(:about), '/about', class: "#{'active' if current_page.url == '/about/'}"
= link_to t(:contact), '/contact', class: "#{'active' if current_page.url == '/contact/'}"
My config
config.rb
###
# Page options, layouts, aliases and proxies
###
# Per-page layout changes:
#
# With no layout
page '/*.xml', layout: false
page '/*.json', layout: false
page '/*.txt', layout: false
# With alternative layout
# page "/path/to/file.html", layout: :otherlayout
# Proxy pages (http://middlemanapp.com/basics/dynamic-pages/)
# proxy "/this-page-has-no-template.html", "/template-file.html", locals: {
# which_fake_page: "Rendering a fake page with a local variable" }
# General configuration
set :partials_dir, 'partials'
activate :i18n, :templates_dir => 'partials'
activate :directory_indexes
# Reload the browser automatically whenever files change
configure :development do
activate :livereload
end
###
# Helpers
###
# Methods defined in the helpers block are available in templates
# helpers do
# def some_helper
# "Helping"
# end
# end
# Build-specific configuration
configure :build do
# Minify CSS on build
activate :minify_css
# Minify Javascript on build
activate :minify_javascript
end

I couldn't write a comment, but I think this might be the reason, your es.yml is wrong, since it starts en:
en:
home: 'Inicio'
Shouldn't it be
es:
home: 'Inicio'

I know this question is months old but I just had the same problem, looked all over the web for hours trying to find and answer and managed to fix the issue by adding these parameters after activating i18n:
config.rb
configure :build do
activate :i18n,
:mount_at_root => 'en',
:lang_map => { :'en' => 'en', :'es' => 'es' },
:path => '/'
end
Obviously, if you want "es" to be your default, change mount_at_root.
Hope this helps.

I achieved localized paths with separate URLs for English and Spanish by
adding index.es.html.erb in the root of the source directory
and setting activate :i18n, :path => "/:locale/" in the config.rb
In the browser, my language selector sends users to / or /es:
English
http://website.com/
Spanish
http://website.com/es
Folder structure
|data
|---home.json
|locales
|---en.yml
|---es.yml
|source
|---index.html.erb
|---index.es.html.erb
|---_slide.erb
|---config.rb
config.rb
configure :build do
activate :i18n, :path => "/:locale/"
activate :directory_indexes
...
end
slide.erb
Using t as a shortcut for I18n.t, I dynamically reference the translated value through the data.
<%= link_to t([data.link.text]),
data.link.href,
:id => data.link.id,
:class => 'btn btn-primary btn-lg btn-dark'
%>
home.json
The value of "text" correlates to the key in the .yml files.
{
"slides": [
{
"text": "slides.learnMore",
...
},
...
]
}
en.yml
en:
slides:
learnMore: "LEARN MORE"
...
es.yml
es:
slides:
learnMore: "APRENDE MÁS"
...

Move all your .erb.html that require to be duplicated per language to the folder: /source/localizable as explained in the docs:
https://middlemanapp.com/advanced/localization/#localizable-templates
You can change this folder name using the modifier: templates_dir:
# Look in `source/language_specific` instead
activate :i18n, :templates_dir => "language_specific"

Related

Local jekyll cannot load unicode urls

My Local Jekyll's version is 4.0.0. and OS is Windows 10
I wanna access to 'http://localhost:4000/문제풀이/문제풀이/', but I can't. only shows 404page.
On the other hand, github pages's blog url 'https://neomindstd.github.io/문제풀이/문제풀이/' is accessible.
Below is Yaml Front Matter of '2020-02-11-문제풀이.md'
---
title: "문제풀이 테스트"
excerpt: "테스트다"
categories:
- 문제풀이
tags:
- Blog
date: 2020-02-09 KST 04:34 +0900
toc: true
toc_sticky: true
toc_label: "목차"
published: true
---
part of _config.yml
# Outputting
permalink: /:categories/:title/
paginate: 5 # amount of posts to show
paginate_path: /page:num/
timezone: Asia/Seoul # https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
so, created: .site/문제풀이/문제풀이/index.html
I've tried solution.
add the _plugins/post.rb.
# https://github.com/jekyll/jekyll-help/issues/129#issuecomment-61255284
# https://stackoverflow.com/questions/41941320/jekyll-encoding-name-of-category-special-characters
# _plugins/post.rb
module Jekyll
class Post
# override post method in order to return categories names as slug
# instead of strings
#
# An url for a post with category "category with space" will be in
# slugified form : /category-with-space
# instead of url encoded form : /category%20with%20space
#
# #see utils.slugify
def url_placeholders
{
:year => date.strftime("%Y"),
:month => date.strftime("%m"),
:day => date.strftime("%d"),
:title => slug,
:i_day => date.strftime("%-d"),
:i_month => date.strftime("%-m"),
:categories => (categories || []).map { |c| Utils.slugify(c) }.join('/'),
:short_month => date.strftime("%b"),
:short_year => date.strftime("%y"),
:y_day => date.strftime("%j"),
:output_ext => output_ext
}
end
end
end
but It doesn't work.
So, how to access unicode url on local?

How to fix: i18n always translate to default locale

I'm trying out the internationalization of a Rails app with i18n. I did some small tests with 2 languages: english and french.
The problem I have is that i18n always translate to the default locale. So if it's english, everything will be in english, and the same with french.
Here is what I tried:
config/initializers/locales.rb
# Permitted locales available for the application
I18n.available_locales = [:en, :fr]
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def default_url_options
{ locale: I18n.locale }
end
end
config/application.rb
module LanguageApp
class Application < Rails::Application
...
config.i18n.load_path += Dir["#{Rails.root.to_s}/config/locales/**/*.{rb,yml}"]
config.i18n.default_locale = :en
# I change the default locale here to :fr or :en
end
end
config/routes.rb
root to: "home#index"
get '/:locale/about' => 'about#index'
get '/:locale' => 'home#index'
I organized my yml files like this:
config/locales/views/about/en.yml
en:
about: "This page is about us."
config/locales/views/about/fr.yml
fr:
about: "Cette page est à propos de nous."
config/locales/views/home/en.yml
en:
welcome: "Hello world"
config/locales/views/home/fr.yml
fr:
welcome: "Bonjour le monde"
And finally my views:
app/views/about/index.html.erb
About us page. <%= t(:about) %>
app/views/home/index.html.erb
This is the homepage. <%= t(:welcome) %>
I think the problem may come from the way I organized my yml files but I don't understand why i18n only translate to the default locale and 'ignore' the other language.
EDIT:
To try this out in the browser with the rails server running, I tried to visit these URL:
localhost:3000
localhost:3000/en
localhost:3000/fr
These 3 URL give me the same content, so the :fr locale doesn't actually work (it returns the same translation as :en)
Same for
localhost:3000/en/about
localhost:3000/fr/about
I also tried it in the rails console:
> I18n.t(:welcome, :en)
"Hello world"
> I18n.t(:welcome, :fr)
"Hello world"
First set the locale for the request:
class ApplicationController < ActionController::Base
around_action :switch_locale
def switch_locale(&action)
I18n.with_locale(params[:locale] || I18n.default_locale, &action)
end
def default_url_options
{ locale: I18n.locale }
end
end
Don't use I18n.locale= as many older answers / tutorials do.
I18n.locale can leak into subsequent requests served by the same
thread/process if it is not consistently set in every controller. For
example executing I18n.locale = :es in one POST requests will have
effects for all later requests to controllers that don't set the
locale, but only in that particular thread/process. For that reason,
instead of I18n.locale = you can use I18n.with_locale which does not
have this leak issue.
Rails Guides
If you want to create translations for specific views you should nest the keys instead of just using flat hashes:
en:
home:
welcome: "Hello World"
fr:
home:
welcome: "Bonjour le monde"
And then use an implicit lookup in the view:
<h1><%= t('.welcome') %></h1>
This resolves the key to home.welcome.

Brakeman not skipping Gemfile.lock with --skip-files param

I'm adding Brakeman to a Rails product but I'm running into an issue. I want it to ignore my Gemfile and Gemfile.lock but when I run it with a command like
brakeman --skip-files Gemfile.lock,Gemfile
it's still touching the files. We use other systems to monitor our gems, but is it not possible to ignore the gem files completely? I can use a brakeman.ignore file of course but would prefer not to. Thanks for any assistance.
I believe this is the check to which you are referring:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/scanner.rb#L39-L40
Brakeman.notify "Processing gems..."
process_gems
The process_gems function is defined here:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/scanner.rb#L131-L152
#Process Gemfile
def process_gems
gem_files = {}
if #app_tree.exists? "Gemfile"
gem_files[:gemfile] = { :src => parse_ruby(#app_tree.read("Gemfile")), :file => "Gemfile" }
elsif #app_tree.exists? "gems.rb"
gem_files[:gemfile] = { :src => parse_ruby(#app_tree.read("gems.rb")), :file => "gems.rb" }
end
if #app_tree.exists? "Gemfile.lock"
gem_files[:gemlock] = { :src => #app_tree.read("Gemfile.lock"), :file => "Gemfile.lock" }
elsif #app_tree.exists? "gems.locked"
gem_files[:gemlock] = { :src => #app_tree.read("gems.locked"), :file => "gems.locked" }
end
if gem_files[:gemfile] or gem_files[:gemlock]
#processor.process_gems gem_files
end
rescue => e
Brakeman.notify "[Notice] Error while processing Gemfile."
tracker.error e.exception(e.message + "\nWhile processing Gemfile"), e.backtrace
end
The AppTree::exists? function is defined here:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/app_tree.rb#L82-L84
def exists?(path)
File.exist?(File.join(#root, path))
end
The GemProcessor::process_gems function is defined here:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/processors/gem_processor.rb#L11
...lots of code...
I don't see any code that would skip this functionality if a certain switch is provided to brakeman. It also looks like the AppTree::exists? function does not take into account if a file was provided to the --skip-files option.
Unfortunately, I believe the current answer is that you can not ignore the gem files completely.
You could create a PR to do what you want and see if the Brakeman team includes it in the next build:
https://brakemanscanner.org/docs/contributing/
Let us know if you discover a way to solve your problem.

ArgumentError on application requests

I've written a basic Rails 3 application that shows a form and an upload form on specific URLs. It was all working fine yesterday, but now I'm running into several problems that require fixing. I'll try to describe each problem as best as I can. The reason i'm combining them, is because I feel they're all related and preventing me from finishing my task.
1. Cannot run the application in development mode
For some unknown reason, I cannot get the application to run in development mode. Currently i've overwritten the production.rb file from the environment with the settings from the development environment to get actuall stacktraces.
I've added the RailsEnv production setting to my VirtualHost setting in apache2, but it seems to make no difference. Nor does settings ENV variable to production.
2. ArgumentError on all calls
Whatever call I seem to make, results in this error message. The logfile tells me the following:
Started GET "/" for 192.168.33.82 at
Thu Apr 07 00:54:48 -0700 2011
ArgumentError (wrong number of
arguments (1 for 0)):
Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.erb
(1.0ms) Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
(4.1ms) Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
within rescues/layout (8.4ms)
This means nothing to me really. I have no clue what's going wrong. I currently have only one controller which looks like this:
class SearchEngineController < ApplicationController
def upload
end
def search
#rows = nil
end
# This function will receive the query string from the search form and perform a search on the
# F.I.S.E index to find any matching results
def query
index = Ferret::Index::Index.new :path => "/public/F.I.S.E", :default_field => 'content'
#rows = Array.New
index.search_each "content|title:#{params[:query]}" do |id,score, title|
#rows << {:id => id, :score => score, :title => title}
end
render :search
end
# This function will receive the file uploaded by the user and process it into the
# F.I.S.E for searching on keywords and synonims
def process
index = Ferret::Index::Index.new :path => "public/F.I.S.E", :default_field => 'content'
file = File.open params[:file], "r"
xml = REXML::Document.new file
filename = params[:file]
title = xml.root.elements['//body/title/text()']
content = xml.root.elements['normalize-space(//body)']
index << { :filename => filename, :title => title, :content => content}
file.close
FileUtils.rm file
end
end
The routing of my application has the following setup: Again this is all pretty basic and probably can be done better.
Roularta::Application.routes.draw do
# define all the url paths we support
match '/upload' => 'search_engine#upload', :via => :get
match '/process' => 'search_engine#process', :via => :post
# redirect the root of the application to the search page
root :to => 'search_engine#search'
# redirect all incoming requests to the query view of the search engine
match '/:controller(/:action(/:id))' => 'search_engine#search'
end
If anyone can spot what's wrong and why this application is failing, please let me know. If needed I can edit this awnser and include additional files that might be required to solve this problem.
EDIT
i've managed to get further by renaming one of the functions on the controller. I renamed search into create and now I'm getting back HAML errors. Perhaps I used a keyword...?
woot, finally found the solutions....
Seems I used keywords to define my actions, and Rails didn't like this. This solved issue 2.
Issue 1 got solved by adding Rails.env= 'development' to the environment.rb file

Rails: generate a full URL in an ActionMailer view

I'm using ActionMailer to send a sign up confirmation email. The email needs to contain a link back to the site to verify the user, but I can't persuade Rails to generate a full URL (including the domain etc).
I'm using:
<%= url_for :controller => 'login', :action => 'verify', :guid => #user.new_user.guid, :only_path => false, :host => 'http://plantality.com' %>
in my view
Part b:
In development mode Rails gripes if I don't specify the host explicilty in the link above. But I don't want to do this in production. Any solutions?
To solve the problem to pass a host for generating URLs in ActionMailer, check out this plugin and the reason why I wrote it.
To solve the first issue, use named routes when applicable. Instead of
<%= url_for :controller => 'login', :action => 'verify', :guid => #user.new_user.guid, :only_path => false, :host => 'http://plantality.com' %>
assuming the route is called login, use
<%= login_url(:guid => #user.new_user.guid) %>
Note, I'm using login_url, not login_path.
I'm not sure if it is what you want but in config/environments/development.rb you can specify default options for mailer urls
config.action_mailer.default_url_options = {
:host => "your.host.org",
:port => 3000
}
you can do the same in config/environments/production.rb
I don't know why the previous solutions seem so complicated, but since I'm here why not give my 2 cents...
Go to /config/environments and add:
config.absolute_site_url = 'your site url'
for the respective environment (ie. in development.rb, test.rb, or production.rb). Restart web server.
This allows you to call Rails.application.config.absolute_site_url to get the desired URL. No need for plugins or weird cheat, just store the site url as an application wide variable.
I think its not 100% correct way but this can also be a solution :
See the Using asset hosts section in the documentation. You need to specify an asset_host. You can also construct it dynamically from the request chaining "#{request.protocol}#{request.host_with_port}/login/?guid=#{#user.new_user.guid}"
To generate url, try this
Rails.application.routes.url_helpers.user_url(User.first.id, host: 'yourhost.io')
this will generate url like this:
http://yourhost.io/users/1
As well you can pass some params
expires = Time.now + 2.days
params = {expires: expires}
u = User.first.id
Rails.application.routes.url_helpers.user_url(u, params, host: 'host.com')
will generate:
http://yourhost.io/users/1.expires=2018-08-12+15%253A52%253A15+%252B0300
so you can werifi in action if link is not expired

Resources