4

I am working on Localization concept in Rails and need to get some of the localization values in HTML pages. So i generated array in controller like below format.,

#array use to store all localization values 
@alertMessages = []

#array values...
{:index=>"wakeUp", :value=>"Wake Up"}
{:index=>"tokenExpired", :value=>"Token Expired"}
{:index=>"timeZone", :value=>"Time Zone"}
{:index=>"updating", :value=>"Updating"}
{:index=>"loadMore", :value=>"Load More"} 
#....more

In HTML pages i want to get localization values like below or some other type,

<%= @alertMessages['wakeUp'] %>

so, it will display value is 'Wake Up',

But its not working.. Can any one please...

4 Answers 4

4

It's easier to use a hash for this (http://api.rubyonrails.org/classes/Hash.html), which is like an array with named indexes (or keys).

So do this:

@alert_messages = {
   wake_up: "Wake Up",
   token_expired: "Token Expired",
   .
   .
   .
}

you can also extend your hash this way:

@alertMessages[:loadMore] = "Load More"

Access it by using:

@alert_messages[:loadMore]

Also you should check i18n to do Internationalization, which is a more robust and flexible way: http://guides.rubyonrails.org/i18n.html

Sign up to request clarification or add additional context in comments.

2 Comments

Able to access by using @alertMessages['loadMore']..., without specifying quotes unable to access value
oh thanks for pointing out the error, i think you can either use "strings" or :symbols.
2
# Hash to store values
@alertMessages = {}

#hashvalues...
alertMessages[:wakeUp] = "Wake Up"
alertMessages[:tokenExpired] = "Token Expired"
alertMessages[:timeZone] = "Time Zone"
alertMessages[:updating] = "Updating"
alertMessages[:loadMore] = "Load More"

#....more
In HTML pages i want to get localization values like below or some other type,

<%= @alertMessages[:wakeUp] %>
so, it will display value is 'Wake Up',

And try to use always symbols because lookup will be fast

3 Comments

and you can convert from symbol to string with to_s and the reverse with to_symbol.
while trying your method i am getting this error NoMethodError (undefined method `<<' for {}:Hash):
where? cause it works in my computer ... Maybe its in other part of your code that is still using alertMessages as an array?
1

An array doesn't seem really appropriate here but if you still want to use it, proceed ths way:

array.find{|el| el[:index] == "wakeUp"}[:value]

You should abstract this though.

Comments

0

try this:

<% 
    @alertMessages.each_with_index do |alertMessage, index|
    alertMessage[:value] if index == "wakeUp"
    end 
%>

Thanks.

2 Comments

Why we need to run full length of array...?
yes you are right. then @apneadiving's answer is the best one: array.find{|el| el[:index] == "wakeUp"}[:value]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.