I’m attempting to build an ETA class, essentially identical to Time, but
where new accepts a number of seconds from now and generates the
underlying Time object accordingly. Obviously I can’t re-assign self, so
how should I do this?
What I’d like to do:
class ETA < Time
def initialize(seconds)
self = Time.new + seconds
end
end
There were a few other methods I needed - have a look:
I realise its potentially overkill making a whole new class for this,
but some of the scripts I’m now using this in have boths times and ETAs,
and a quick ‘is_a?’ allows me to distinguish them easily.
Let me know if you think you can improve it!
I realise its potentially overkill making a whole new class for this,
but some of the scripts I’m now using this in have boths times and ETAs,
and a quick ‘is_a?’ allows me to distinguish them easily.
Let me know if you think you can improve it!
Not much change - you don’t need all the “selfs”:
class ETA < Time
Takes a number of seconds until the event
def self.relative(seconds)
at Time.now.to_i + seconds
end
method to self.relative? Is that personal preference, or is there a
reason you’ve kept Time’s original .new and .now?
Your ETA.new does something different than Time.new and because of that
a new name would help avoid confusion. Also, by that means you can
still use the “old” new with the old semantics, i.e. you can do ETA.new
and get an instance with the current timestamp.
You could even put relative in class Time and use it both ways:
def self.relative(seconds)
at Time.now.to_i + seconds
end
…
end
Thanks for the tips! Out of interest, why did you change my self.new
method to self.relative? Is that personal preference, or is there a
reason you’ve kept Time’s original .new and .now?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.