Monday 15 September 2014

ruby on rails - If today, display "today", once 1 day has passed display actual date in an efficient way -



ruby on rails - If today, display "today", once 1 day has passed display actual date in an efficient way -

what want whenever user viewing post, if current date today, should today @ 3:35pm, if viewing same post tomorrow should nov 8, 2014 @ 3:35pm.

i know simple if statement...but concerned on every page load (especially instance post#index 20 posts shown @ once) have doing date.today if check.

is there more elegant way doesn't give me performance hit?

in other words, trying avoid pseudo-n+1 problem hitting date.today on every page load. i.e. there counter_cache solution problem?

here current version:

<% if post.created_at == date.today %> today @ <%= post.created_at.strftime("%l:%m %p") %> <% else %> <%= "#{post.created_at.strftime("%b %e, %y")} @ #{post.created_at.strftime("%l:%m %p")}" %> <% end %>

i don't think performance real issue here. in case can implement logic in model

def display_created_at if created_at.today? "today @ #{created_at.strftime('%l:%m %p')" else created_at.strftime("%b %e, %y @ %l:%m %p") end end

now utilize caching here, cache 1 hr expiration, per record,

def cached_display_created_at rails.cache.fetch(["post", id, "display_created_at"], expires_in: 1.hour) display_created_at end end

but (again) not think help performance wise.

ruby-on-rails ruby ruby-on-rails-4

No comments:

Post a Comment