Class: Machinist::Caching::Shop

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/machinist/caching/shop.rb

Overview

The shop takes care of caching database objects.

Calling make! on a class requests objects from the shop; you don’t normally access the shop directly.

Read more about object caching on the wiki.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeShop

:nodoc:



17
18
19
# File 'lib/machinist/caching/shop.rb', line 17

def initialize #:nodoc:
  reset!
end

Instance Attribute Details

#warehouseObject

Returns the value of attribute warehouse.



15
16
17
# File 'lib/machinist/caching/shop.rb', line 15

def warehouse
  @warehouse
end

Instance Method Details

#buy(blueprint, attributes = {}) ⇒ Object

Buy a (possibly cached) object from the shop.

This is just like constructing an object by calling Blueprint#make!, but it will return a previously cached object if one is available.

Raises:

  • (BlueprintCantSaveError)


30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/machinist/caching/shop.rb', line 30

def buy(blueprint, attributes = {})
  raise BlueprintCantSaveError.new(blueprint) unless blueprint.respond_to?(:make!)

  cached = warehouse[blueprint, attributes]

  if cached.nil?
    blueprint.make!(attributes).tap do |object|
      warehouse[blueprint, attributes] = blueprint.box(object)
    end
  else
    blueprint.unbox(cached)
  end
end

#reset!Object

Throw out the entire collection of cached objects.



22
23
24
# File 'lib/machinist/caching/shop.rb', line 22

def reset!
  self.warehouse = Warehouse.new
end