Vee
Vee

Reputation: 1841

Creating dynamic variable in Ruby on rails

I'm trying to generate a variable name based on day of week. In my html.erb file, I have the following code:

<%= "@selected_venue.open_time_"+Time.now.strftime('%a').downcase %>

I'm trying to create a variable such as "@selected_venue.open_time_mon", "@selected_venue.open_time_tue", "@selected_venue.open_time_wed", etc. As you can see, I'm appending the day of week to the generic variable name "@selected_venue.open_time_" so I can get the value of the dynamically generated variable.

Instead of getting the value that the variable represents (which is a time such as 2:00PM), I keep getting the literal result: "@selected_venue.open_time_wed".

Is there a method that I can use to get the value of the dynamically generated variable?

Upvotes: 1

Views: 2305

Answers (3)

Mori
Mori

Reputation: 27779

Cleaner to move the logic to a helper, e.g.:

# in a helper
def open_time
  var = "open_time_" + Time.now.strftime('%a').downcase
  @selected_venue.send(var)
end

# in the template
<%= open_time %>

I agree with @Bubbles that it's better to have a collection like a hash or an array in open_time than having to metaprogram like this.

Upvotes: 2

Ajedi32
Ajedi32

Reputation: 48318

Note that if @selected_venue is an ActiveRecord object (and open_time_mon is an attribute of that object), you can just use it like a hash:

@selected_venue["open_time_#{Time.now.strftime('%a').downcase}"]

Otherwise, as others have said you'll need to use send:

@selected_venue.send("open_time_#{Time.now.strftime('%a').downcase}")

Upvotes: 0

Bubbles
Bubbles

Reputation: 3815

This is more a general ruby thing, but sure it's possible. You can access a variable like so:

@selected_venue.send(:"open_time_#{Time.now.strftime('%a').downcase}")

That said, in a situation like this I'd first consider if I could replace the dynamic variable with a hash - if open_time could be a hash and if you could set :wed on it, I'd personally find it tidier (of course, I don't know the full situation here - if you have seven variables in the venue table for daily opening times, this solution would make sense).

Upvotes: 2

Related Questions