Search code examples
ruby-on-railsrpcjson-rpc

Keep an instance of an object for the whole Rails server?


Essentially, I have a simple class that interacts with a local RPC server. Call it RPC_Class. Every user the website will host will make requests that require the rails server to make calls to the RPC client.

This class needs to be instantiated as such

rpc = RPC_Class.new('localhost:4325')

And then I make calls to it

puts rpc.getbalance

Now, there are three options:

  • Create a new instance for every request needed (obviously a bad solution)
  • Create a new instance for every user's session
  • Create one instance for the whole server

I think option three is the most performative option. Where do I initialize this class such that I can use it throughout the server code?


Solution

  • I think you should go with Rails caching for handling this use case. You can cache the response when you make the API call the first time and use the cached response for all the calls you receive after that. You can write a method like this:

    def fetch_rpc_balance
      Rails.cache.fetch("rpc_balance", expires_in: 24.hours)
        rpc = RPC_Class.new('localhost:4325')
        puts rpc.getbalance
      end
    end
    

    Now, if you use the fetch_rpc_balance method in your logic, it will make the API call only the first time and return the cached response from second call onwards.