slarti42uk
slarti42uk

Reputation: 451

How do I add variable times to Time.now in Rails (eval?)

Well this seems like it should be a simple thing but I can't seem to find what I need. Currently I have two variables: frequency and period. frequency is set to a number (eg 1) and period is set to "month" or "year". What I want to do is is use these variables to calculate x months from now.

I've seen the 1.month.from_now and 1.year.from_now but what I need is something like:

eval("#{frequency}.#{period.downcase}.from_now")

but I'm not sure about the use of eval as I'm new to Rails/Ruby and in PHP the use of eval usually means you're doing something wrong.

Is eval evil in Rails?

Upvotes: 0

Views: 887

Answers (3)

Thilo
Thilo

Reputation: 17735

It's really just a ruby question, not Rails specific. Use this:

frequency.send(period.downcase).from_now

that simply invokes a method called "month" of "year" on frequency.

Upvotes: 0

Vasiliy Ermolovich
Vasiliy Ermolovich

Reputation: 24617

eval is pretty slow. You can use Object#send:

irb(main):003:0> frequency = 1
irb(main):004:0> period = "month"
irb(main):005:0> frequency.send(period).from_now
=> Mon, 30 May 2011 16:57:12 UTC +00:00

And you can read about the speed here.

Upvotes: 3

bor1s
bor1s

Reputation: 4113

You can simply add your own method and use your variables to calculate your x month from for example:

def my_x_month(period,frequency)
  case period
   when "month"
    period.month.from_now
   when "year"
    period.year.from_now
  end
end

Upvotes: 0

Related Questions