Question

I'm developing a social network like a mix of Twitter and Facebook based on sports. I have a model called Post (id, user_id, receiver_id, message, created_at) and I want to cache the Post views.

app/views/posts/_post.haml

- cache post do
  %div
    .author= link_to post.user.full_name, post.user
    .message= post.message
    .timestamp= timestamp_for_post(post.created_at)

All worked perfectly yesterday but when I visited my "home feed" I realized that timestamp is cached. Let me show you an example:

Berna Castro
test
Less than a minute ago - Comment  Props  Delete

The thing is it shouldn't display "Less than a minute ago", it should display "Yesterday". Is there any way to don't cache the timestamp? What do you recommend to fix that?

I thought to make an AJAX call for getting the timestamp but that's very weird and not good.

Was it helpful?

Solution

Instead of rendering a relative timestamp, render the actual, non-relative timestamp in your template, and then use something like Moment.js to convert it to a relative timestamp client-side.

This also has the advantage that the timestamp will update itself if the user has the page open for a long enough period that the relative timestamp would change.

You should also consider not caching anything until you actually understand what on your site is slow. Caching has a lot of gotchas like this, and prematurely optimization isn’t always worth it.

OTHER TIPS

You could just move the timestamp out of the cache block

  %div
   - cache post do
      .author= link_to post.user.full_name, post.user
      .message= post.message
   .timestamp= timestamp_for_post(post.created_at)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top