Skip to content

Instantly share code, notes, and snippets.

@ttanimichi
Created July 11, 2016 02:48
Show Gist options
  • Save ttanimichi/e501baa83c91e8df81cb528b2f496d56 to your computer and use it in GitHub Desktop.
Save ttanimichi/e501baa83c91e8df81cb528b2f496d56 to your computer and use it in GitHub Desktop.
AR::Base のテーブルをキャッシュするサンプルコード
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>
@ttanimichi
Copy link
Author

TODO

  • 複合キーでインデックスする場合への対応
  • 複数のインデックスを貼る場合への対応

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment