Class: DriveTime::ModelStore

Inherits:
Object
  • Object
show all
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

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
43
# 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



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/drive_time/model_store.rb', line 45

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]
  unless model.present?
    raise NoModelOfClassWithKeyInStoreError, "No model of class #{clazz} with a key of #{key} in model store"
  end

  return model
end

#save_allObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/drive_time/model_store.rb', line 62

def save_all
  @logger.log_as_header "Saving Models"
  @store.each do |key, models|
    models.each do |key, model|
      @logger.debug "Saving Model: #{key} #{model.inspect}"
      begin
        model.save!
      rescue Exception => error
          @logger.warn "Failed To Save Model: #{key}"
          @logger.warn "Error: #{error}"
          @logger.warn "#{model.inspect}"
          raise error
        end
    end
  end
end