Created
July 11, 2016 02:48
-
-
Save ttanimichi/e501baa83c91e8df81cb528b2f496d56 to your computer and use it in GitHub Desktop.
AR::Base のテーブルをキャッシュするサンプルコード
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ApplicationRecord | |
def self.all | |
s = Struct.new(:code, :v) | |
[s.new(42, "hoge"), s.new(43, "fuga")] | |
end | |
end | |
ApplicationRecord.singleton_class.class_eval do | |
def CachedRecords(key: :id) | |
Module.new do | |
define_method :cached_records do | |
@cached_records ||= self.all.map {|r| [r.send(key), r] }.to_h | |
end | |
def clear_cache | |
@cached_records = nil | |
end | |
end | |
end | |
end | |
class MasterHoge < ApplicationRecord | |
extend CachedRecords(key: :code) | |
end | |
code = 43 | |
p MasterHoge.cached_records[code] #=> #<MasterHoge> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO