Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created January 19, 2017 19:32
Show Gist options
  • Save timuruski/b1ea5c6d19ec87cc978f43c99394953e to your computer and use it in GitHub Desktop.
Save timuruski/b1ea5c6d19ec87cc978f43c99394953e to your computer and use it in GitHub Desktop.
Two possible ways to implement a basic in-memory cache for DB queries. One is more idiomatic, but I wonder if it's too idiomatic.
class UserImporter < ImporterBase
def import_user
user_name = @data[:user_name]
# Which is easier to understand?
users_by_name[user_name]
# -- OR --
find_user_by_name(user_name)
end
def users_by_name
@users_by_name ||= Hash.new do |hash, key|
users = User.where(name: name).all
hash[name] = users.first
end
end
def find_user_by_name(name)
@users_by_name ||= {}
if @users_by_name.key?(name)
@users_by_name[name]
else
users = User.where(name: name).all
hash[name] = users.first
@users_by_name[name] = users.first
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment