Jaqx
Jaqx

Reputation: 826

Check if element in array was created_at within last 5 seconds

I have an array @user.photos which will return something like:

[#<Photo id: 53, photo_file_name: "Freedom-Tower", 
photo_content_type: "image/jpeg", photo_file_size: 1937702, 
photo_updated_at: "2013-04-23 23:57:22", user_id: 1, 
created_at: "2013-04-23 23:57:23", updated_at: "2013-04-23 23:57:23">, 
#<Photo id: 52, photo_file_name: "sunset-Courtsey",
photo_content_type: "image/jpeg", photo_file_size: 1937702, 
photo_updated_at: "2013-04-23 23:51:22", user_id: 1, 
created_at: "2013-04-23 23:51:24", updated_at: "2013-04-23 23:51:24">

I want to create a conditional that will check if a user has recently created a photo

Something like: @user.photos.any? { |x| x.created_at btw Time.now..-5 seconds }??

Upvotes: 2

Views: 1131

Answers (2)

Shawn Balestracci
Shawn Balestracci

Reputation: 7530

You can use 5.seconds.ago:

@user.photos.any? {|x| x.created_at > 5.seconds.ago }

Upvotes: 8

patrickmcgraw
patrickmcgraw

Reputation: 2495

How about:

@user.photos.any? { |x| x.created_at > (Time.now-5.seconds) }

Is there a reason for the upper bound? Can photos be created in the future?

Upvotes: 3

Related Questions