Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to periodically fetch/update value in rails?

Let's take a scenario:

counter 10 seconds
  • User visited show.html.erb page
  • show.html.erb fetch the value from database using <%= @post.value %>.
  • Counter started and each iteration of counter is for 10 seconds.
  • After every 10 seconds I wanted to change the @post.value using utility class.
  • update the @post.value in database.
  • Refresh the show.html.erb automatically and <%= @post.value %> will show the updated value
  • Above process will be run in loop until user move to other pages.

If I have to simplify the problem in code then it would like this:

View Page

<%= @post.value %>
<%= @post.name %>

Controller Method

def show
 @post = Post.find(params[:id])
end

def update
....   #It's empty right now
end

def fetching_value_from_PostUpdate(current_value)
 .. # Now I need to update the value in database
end

Utility class

I want to update the post.value on the basis of method written in this class. Pseudo code:

class PostUpdate
 @@instance_variable   

 def initialize(post_value)
   @@instance_variable = Marshal.load(Marshal.dump(post_value))
 end

  #Method required to calculate the value
def update_data_in_database
 ...
return data
end

Questions

  • Where do I have to put the counter? client side or server side? I don't want to use background jobs in rails.
  • What changes do I need to make in show method so that after every interval page will refresh automatically and pass the updated value in @post.value?

Thanks for your help!

like image 237
Amit Pal Avatar asked Jul 01 '15 04:07

Amit Pal


2 Answers

I would go with Firebase as opposed to polling the server.

However, if you're wanting to poll the server periodically, I would just have a JavaScript method which executes every 10 seconds, or at whatever interval you'd like, and fetches whatever data you'd like asynchronously and subsequently updates the DOM.

Also, ruby wrapper for firebase api, in case that may be of interest

like image 93
Drew Avatar answered Oct 02 '22 13:10

Drew


I would say the easiest approach doing it would be using ActionController::Live. Using it you'll be able to send SSE(Server Sent Event) to your client while having js script there to catch and update your <%= @post.value %>. Here's a pretty nice manual on using it.

Still from my point of view the most appropriate way to implement things you want to do will be using something like Faye. It is a publish/subscribe messaging system which will allow you to update your client with new data as soon as it appears, e.g., you can set an after_save in your model and publish an update to all subscribed clients. And of course there is a gem also called faye to wrap its usage.

like image 40
Glupo Avatar answered Oct 02 '22 14:10

Glupo