Reputation:
<% if post.created_at < 30.days.ago %>
<%= post.created_at.strftime("%b %d, %Y") %>
<% else %>
<%= time_ago_in_words(post.created_at) %>
<% end%>
The post is created less than 30 days ago but the second condition runs. It is quiet weird and when i change the first line and make it post.created_at > 30.days.ago
it returns the first condition even though it is false cause the posts were created far more earlier.
Please if anyone could explain why that is and what can i do to change it(if at all).
Upvotes: 1
Views: 79
Reputation: 106027
This code makes sense in English:
post.created_at < 30.days.ago
Your brain reads it as:
If this post was created less than 30 days ago...
Ruby, however, reads it as:
If the date this post was created is less than (before) the date 30 days ago...
Remember that 30.days.ago
returns a DateTime, not a duration. Let's suppose that post.created_at
is two weeks ago, i.e. 2016-01-06 (it's actually a DateTime, but we'll disregard the time for the sake of demonstration). Two weeks is less than 30 days, so you might expect your expression to evaluate to true
. However, 30.days.ago
returns the date 2015-12-22. Put those values into our expression (pseudocode now):
2016-01-06 < 2015-12-22
This evaluates to false
, because the date on the left is not before (read: not less than) the date on the right.
In order to test whether post.created_at
is after (read: greater than) 30.days.ago
, we have to turn the operator around:
if post.created_at > 30.days.ago
P.S. Another way to think about it is whether the date 30 days ago is before (less than) post.created_at
. This is basically (if not exactly) equivalent:
if post.created_at > (DateTime.now - 30.days)
Or you could consider whether post.created_at
is between 30.days.ago
and today:
if post.created_at.between?(30.days.ago, DateTime.now)
Or, whether the time elapsed since post.created_at
is less than 30 days:
if (DateTime.now - post.created_at) < 30.days
(Note that whereas 30.days.ago
returns a DateTime, 30.days
returns a duration.)
Upvotes: 1
Reputation: 10898
I think you're misunderstanding how your condition works.
In this situation, the if statement succeeds if date_1
is before date_2
:
if date_1 < date_2
# do something
end
In your code, the if statement succeeds if the post is created before 30 days ago.
What you probably want is it to be after 30 days ago?
Upvotes: 1