Skip to content

Instantly share code, notes, and snippets.

@dacook
Created March 16, 2022 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacook/515d85785699a96119f3dbbfa04f4f64 to your computer and use it in GitHub Desktop.
Save dacook/515d85785699a96119f3dbbfa04f4f64 to your computer and use it in GitHub Desktop.
Rails Duration cheat sheet

I constantly find it hard to know how to express a duration, but once I figure it out, it's abundantly clear. So here's some helpful examples.

There are multiple methods that do the same thing, to help you express the intent the way that makes sense to you.

Past: ago/before/until

1.week.ago           # same as Time.current - 1.week
1.week.before(@date) # same as @date - 1.week

I can't think of a use for until

Future: from_now/after/since

1.week.from_now     # same as Time.current + 1.week
1.week.after(@date) # same as @date + 1.week

I can't think of a use for since

See: Duration reference

Bonus: Range#step

Loop through each week:

(@from..@to).step(7).each {} # Assuming magic number of 7 days in week
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment