Class: FixtureKit::FileCache
- Inherits:
-
Object
- Object
- FixtureKit::FileCache
- Defined in:
- lib/fixture_kit/file_cache.rb
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
Instance Method Summary collapse
- #exists? ⇒ Boolean
-
#initialize(path) ⇒ FileCache
constructor
A new instance of FileCache.
- #read ⇒ Object
- #serialize_exposed(exposed) ⇒ Object
- #write(data) ⇒ Object
Constructor Details
#initialize(path) ⇒ FileCache
Returns a new instance of FileCache.
11 12 13 |
# File 'lib/fixture_kit/file_cache.rb', line 11 def initialize(path) @path = path end |
Instance Attribute Details
#path ⇒ Object (readonly)
Returns the value of attribute path.
9 10 11 |
# File 'lib/fixture_kit/file_cache.rb', line 9 def path @path end |
Instance Method Details
#exists? ⇒ Boolean
15 16 17 |
# File 'lib/fixture_kit/file_cache.rb', line 15 def exists? File.exist?(path) end |
#read ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/fixture_kit/file_cache.rb', line 19 def read content = JSON.parse(File.read(path)) data = content.fetch("data").to_h do |coder_name, coder_data| coder = coder_for(coder_name) [coder.class, coder.decode(coder_data)] end exposed = content.fetch("exposed").each_with_object({}) do |(name, value), hash| if value.is_a?(Array) hash[name.to_sym] = value.map { |r| { ActiveSupport::Inflector.constantize(r.keys.first) => r.values.first } } else hash[name.to_sym] = { ActiveSupport::Inflector.constantize(value.keys.first) => value.values.first } end end MemoryCache.new(data: data, exposed: exposed) end |
#serialize_exposed(exposed) ⇒ Object
51 52 53 54 55 56 57 58 59 |
# File 'lib/fixture_kit/file_cache.rb', line 51 def serialize_exposed(exposed) exposed.each_with_object({}) do |(name, record), hash| if record.is_a?(Array) hash[name] = record.map { |record| { record.class => record.id } } else hash[name] = { record.class => record.id } end end end |
#write(data) ⇒ Object
38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/fixture_kit/file_cache.rb', line 38 def write(data) content = { data: data.data.to_h do |coder_class, coder_data| coder = coder_for(coder_class.name) [coder.class, coder.encode(coder_data)] end, exposed: data.exposed, } FileUtils.mkdir_p(File.dirname(path)) File.write(path, JSON.pretty_generate(content)) end |