Skip to content

Instantly share code, notes, and snippets.

@ritikesh
Created March 9, 2019 20:09
Show Gist options
  • Save ritikesh/5dea584ac694875ab5153bbc00554fb3 to your computer and use it in GitHub Desktop.
Save ritikesh/5dea584ac694875ab5153bbc00554fb3 to your computer and use it in GitHub Desktop.
Memoize Method calls based on params
module MemoizeExtensions
def memoize_methods(method_name, *params)
@@hash ||= {}
return @@hash[params] if @@hash[params]
@@hash[params] = send(method_name, *params)
end
end
class User < ActiveRecord::Base
extend MemoizeExtensions
scope :visible, -> { where(deleted: false) }
scope :active, -> { where(active: true) }
def self.fetch_all_users(filter)
public_send(filter).all
end
end
class UsersController < ApplicationController
def index
User.memoize_methods(:fetch_all_users, params[:filter_type].to_sym)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment