Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array values in Ruby On Rails

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...

like image 690
suresh.g Avatar asked Mar 25 '23 04:03

suresh.g


2 Answers

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

like image 173
Roland Studer Avatar answered Apr 06 '23 06:04

Roland Studer


# 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

like image 35
trompa Avatar answered Apr 06 '23 08:04

trompa