Class: Poro::Contexts::HashContext

Inherits:
Poro::Context show all
Defined in:
lib/poro/contexts/hash_context.rb

Overview

Not a practical real world context manager, this is a simple in-memory store that uses a normal Ruby Hash. The intended use for this context is for building and testing code before a more realistic persistence backing is available for your application.

Instance Attribute Summary

Attributes inherited from Poro::Context

#data_store, #klass, #primary_key

Instance Method Summary collapse

Methods inherited from Poro::Context

configure_for_class, factory, factory=, factory?, fetch, managed_class?, #primary_key_value, #set_primary_key_value

Methods included from Poro::Context::CallbackMethods

#callbacks, #clear_callbacks, #register_callback

Methods included from Poro::Context::FindMethods

#data_store_find, #find, included

Constructor Details

#initialize(klass) ⇒ HashContext

Returns a new instance of HashContext.



9
10
11
12
# File 'lib/poro/contexts/hash_context.rb', line 9

def initialize(klass)
  self.data_store = {}
  super(klass)
end

Instance Method Details

#convert_to_data(obj) ⇒ Object



57
58
59
60
61
62
# File 'lib/poro/contexts/hash_context.rb', line 57

def convert_to_data(obj)
  transformed_obj = callback_transform(:before_convert_to_data, obj)
  data = transformed_obj
  callback_event(:after_convert_to_data, data)
  return data
end

#convert_to_plain_object(data) ⇒ Object



50
51
52
53
54
55
# File 'lib/poro/contexts/hash_context.rb', line 50

def convert_to_plain_object(data)
  transformed_data = callback_transform(:before_convert_to_plain_object, data)
  obj = transformed_data
  callback_event(:after_convert_to_plain_object, obj)
  return obj
end

#fetch(id) ⇒ Object



14
15
16
17
18
# File 'lib/poro/contexts/hash_context.rb', line 14

def fetch(id)
  obj = convert_to_plain_object( data_store[clean_id(id)] )
  callback_event(:after_fetch, obj)
  return obj
end

#remove(obj) ⇒ Object

Remove the object from the underlying hash.



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/poro/contexts/hash_context.rb', line 37

def remove(obj)
  callback_event(:before_remove, obj)
  
  pk_id = self.primary_key_value(obj)
  if( pk_id != nil )
    data_store.delete(pk_id)
    self.set_primary_key_value(obj, nil)
  end
  
  callback_event(:after_remove, obj)
  return obj
end

#save(obj) ⇒ Object

Save the object in the underlying hash, using the object id as the key.



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/poro/contexts/hash_context.rb', line 21

def save(obj)
  callback_event(:before_save, obj)
  
  pk_id = self.primary_key_value(obj)
  if(pk_id.nil?)
    pk_id = obj.object_id
    self.set_primary_key_value(obj, pk_id)
  end
  
  data_store[pk_id] = convert_to_data(obj)
  
  callback_event(:after_save, obj)
  return obj
end