With ActiveSupport's extensions to Numeric, one can write the following to obtain two minutes: 2.minutes
.
There are some situations, though, where only a few time units are important. Suppose there's a task that your application can run every one day, week, or month, depending on some input:
@frequency = :day # can be any of the following: [:day, :month, :week]
Using ActiveSupport's extensions to Numeric naively, we could do this to determine when to run the task:
def run_every
1.send(@frequency)
end
Which will call the days
instance method in Numeric
(the day
method is an alias).
In this scenario we're only interested in one minute, day, week, month, year, etc. Is there a nicer way to instantiate a single unit of time other than the one I described?
# can be any of the following: [:day, :month, :week]
I'd use a hash instead, something like:
DURATIONS = { day: 1.day, week: 1.week, month: 1.month }.freeze
def run_every
DURATIONS[@frequency]
end