Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cache methods in ruby?

I have a ruby workflow which makes few expensive API calls. I know we have a easier way to cache things in Ruby on Rails but haven't found any common ruby gem for ruby scripts.

What is the simplest and easiest way to cache results for a method which depends on input for a pure ruby application?

//pseudo code
def get_information (id)
  user_details = expensive_api_call(id)
  return user_details
end
like image 489
amair Avatar asked Feb 08 '23 02:02

amair


1 Answers

The easiest way is to use a Hash:

class ApiWithCache

  def initialize
    @cache = {}
  end

  def do_thing(id)
    expensive_api_call(id)
  end

  def do_thing_with_cache(id)
    @cache[id] ||= do_thing(id)
  end
end

Now this poses some problems that you might want to look into:

  • expiry of cached data
  • size of cache (will grow unless you also remove items. this could cause problems in long running processes)
like image 134
Pascal Avatar answered Feb 21 '23 04:02

Pascal