suresh gopal
suresh gopal

Reputation: 3156

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

Upvotes: 4

Views: 11347

Answers (4)

Roland Studer
Roland Studer

Reputation: 4415

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

Upvotes: 4

rony36
rony36

Reputation: 3339

try this:

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

Thanks.

Upvotes: 0

trompa
trompa

Reputation: 2007

# 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

Upvotes: 2

apneadiving
apneadiving

Reputation: 115521

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.

Upvotes: 1

Related Questions