Class: DriveTime::ModelStore
- Inherits:
-
Object
- Object
- DriveTime::ModelStore
- Defined in:
- lib/drive_time/model_store.rb
Overview
Store model instances by class and link This way we can look them up as needed to satisfy dependencies and avoid duplication
Defined Under Namespace
Classes: ModelAddedTwiceError, NoModelOfClassWithKeyInStoreError, NoModelsOfClassInStoreError
Instance Method Summary collapse
-
#add_model(instance, key, clazz) ⇒ Object
Store the model by class to avoid key collisions.
- #get_model(clazz, key) ⇒ Object
-
#initialize(log_level = Log4r::INFO) ⇒ ModelStore
constructor
A new instance of ModelStore.
- #save_all ⇒ Object
Constructor Details
#initialize(log_level = Log4r::INFO) ⇒ ModelStore
Returns a new instance of ModelStore.
17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/drive_time/model_store.rb', line 17 def initialize(log_level=Log4r::INFO) @store = {} # Set up logging formatter = Log4r::PatternFormatter.new(:pattern => "[%c] %M") outputter = Log4r::Outputter.stdout outputter.formatter = formatter @logger = Log4r::Logger.new ' Model Store ' @logger.level = log_level @logger.outputters = outputter end |
Instance Method Details
#add_model(instance, key, clazz) ⇒ Object
Store the model by class to avoid key collisions
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/drive_time/model_store.rb', line 31 def add_model(instance, key, clazz) class_string = clazz.to_s # Sanitise key key = DriveTime.underscore_from_text(key) @logger.debug "Adding model with key #{key} of class #{clazz}" if !@store[class_string] @store[class_string] = {} elsif @store[class_string][key] raise ModelAddedTwiceError, "#{instance} has already been added to model store" end @store[class_string][key] = instance end |
#get_model(clazz, key) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/drive_time/model_store.rb', line 44 def get_model(clazz, key) @logger.debug "Request for model with key #{key} of class #{clazz}" models_for_class = @store[clazz.to_s] # Are there any classes of this type in the store? if models_for_class.nil? raise NoModelsOfClassInStoreError, "No classes of type: #{clazz} in model store" end # Is there an instance model = models_for_class[key] if !model raise NoModelOfClassWithKeyInStoreError, "No model of class #{clazz} with a key of #{key} in model store" end return model end |
#save_all ⇒ Object
63 64 65 66 67 68 69 |
# File 'lib/drive_time/model_store.rb', line 63 def save_all @store.each do |key, models| models.each do |key, model| model.save! end end end |