Class: Jason::Encoding::PersistenceHandler::Persistable
- Inherits:
-
PersistenceObject
- Object
- PersistenceObject
- Jason::Encoding::PersistenceHandler::Persistable
- Includes:
- Operations::File
- Defined in:
- lib/jason/encoding/persistable.rb
Instance Attribute Summary
Attributes inherited from PersistenceObject
Instance Method Summary collapse
-
#initialize(obj, options = {}) ⇒ Persistable
constructor
A new instance of Persistable.
- #process_persistence ⇒ Object
Methods inherited from PersistenceObject
Constructor Details
#initialize(obj, options = {}) ⇒ Persistable
Returns a new instance of Persistable.
9 10 11 12 |
# File 'lib/jason/encoding/persistable.rb', line 9 def initialize(obj,={}) @update = .fetch(:update, false) super(obj) end |
Instance Method Details
#process_persistence ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/jason/encoding/persistable.rb', line 15 def process_persistence persisted = true begin persisted_file_content = load_from_file(where_to_persist) r_objects = ActiveSupport::JSON.decode(persisted_file_content) rescue MultiJson::DecodeError => de r_objects = [] ensure # There was something persisted before. Search for id and replace. # (Only if update is true) # If not updated, append to objects array. unless @update as_json = @persistable_obj.send(:as_json) # persist with relations if given. # persist belongs_to if @persistable_obj.class.ancestors.map(&:to_s).include?("Jason::Relation") as_json[@root].each_pair do |key,value| next unless key.to_s.include?("_id") relation = key.to_s.split("_id").first.to_sym reflection = @persistable_obj.class.reflect_on_relation(relation) if reflection process_method = instance_method("process_#{reflection.type}") process_method.bind(self).call(reflection,value) end end end r_objects << as_json else r_objects.each do |object| if object[@root]["id"] == @persistable_obj.send(:id) # persist with relations if given. object[@root] = @persistable_obj.send(:as_json)[@root] break end end end persisted = save_to_file(ActiveSupport::JSON.encode(r_objects)) end return persisted end |