Module: Polaroid::ClassMethods
- Defined in:
- lib/polaroid.rb
Instance Method Summary collapse
-
#build_from_snapshot(snapshot, format = :auto) ⇒ Object
This method will try its damnedest to give you a meaningful snapshot object, but first it needs to somehow get it into a Hash.
Instance Method Details
#build_from_snapshot(snapshot, format = :auto) ⇒ Object
This method will try its damnedest to give you a meaningful snapshot object, but first it needs to somehow get it into a Hash. Either you can let it autodetect and give it a Hash-like, JSON String-like, or something which responds to #to_h or #to_s, or you can explicitly pass it the format as :hash or :json.
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/polaroid.rb', line 40 def build_from_snapshot(snapshot, format = :auto) symbolize_keys = ->((key, val), hash) { hash[key.to_sym] = val } from_hash = ->(snap) { snap.each.with_object({}, &symbolize_keys) } from_json = ->(snap) { JSON.parse(snap).each.with_object({}, &symbolize_keys) } snapshot_hash = if :auto == format && snapshot.is_a?(Hash) from_hash.call(snapshot) elsif :auto == format && snapshot.is_a?(String) from_json.call(snapshot) elsif :hash == format from_hash.call(snapshot) elsif :json == format from_json.call(snapshot) elsif snapshot.respond_to?(:to_h) from_hash.call(snapshot) else from_json.call(snapshot.to_s) end self::Snapshot.new(snapshot_hash) end |