“Chronic is a natural language date/time parser written in pure Ruby.”
It parses basic language such as ‘next friday’ or ‘last wednesday at midnight’ which is incredibly useful to me right now. It accepts a :now option so you can get a date/time relative to any other.
I have only played with it in irb for a few minutes so far and it appears to be what I need. Some things I tried don’t parse such as ‘two mondays ago’. I don’t need anything like that but it would be cool to have. Something even better than GNU’s accepted date inputs would kick some serious butt.
Something like this works but isn’t exactly optimal and ugly loops will ensue once you go even further back than 2 (weeks|months|whatevers):1 2 |
last_monday = Chronic.parse('last monday') Chronic.parse('last monday', :now => last_monday) |
Despite it’s young age and accompanying immature feature set Chronic certainly does what it claims, and well. I’m storing which weekdays are interesting using the standard integers, so this simple extension to Numeric will load me up with some syntactic sugar.
1 2 3 4 5 6 7 |
class Numeric @@weekdays = %w(sunday monday tuesday wednesday thursday friday saturday) def to_weekday @@weekdays[self] end end |
So my goal tomorrow is to simplify my methods greatly using beautiful code such as:
1 2 3 4 |
# wday comes from the DB somewhere weekday = wday.to_weekday # => 'wednesday', for example some_date = Date.new(2006, 3, 25) next_date = Chronic.parse("last #{weekday} at 7 pm", :now => some_date) |
Eventually I’d like to get Chronic out of there and just include the method in Time or Date so it reads even more nicely. But in any case it’s going to make my life easier. It’s great to see an active community developing gems like this. All I had to do was ‘sudo gem install -y chronic’ and I was good to go. Perhaps extending Rails based on Chronic’s code would be most elegant. I was surprised to find Rails was missing methods such as next_wednesday or similar.
Ruby is definitely my favourite language right now. It may lack Unicode and native threading, for the time being, but despite its shortcomings it still puts some other popular languages to shame. Dynamism is key.
