Module: Uuid::Uuidable

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/models/uuid.rb', line 8

def self.included(base)
  base.class_eval do
    # Lazy uuid generation disables uuid generation on record creation. For the most part this is
    # undesireable (see below) but is useful for aliquots, as we do not expose the uuids via the API
    # and only require them asynchronously.
    class_attribute :lazy_uuid_generation
    self.lazy_uuid_generation = false
    # Ensure that the resource has a UUID and that it's always created when the instance is created.
    # It seems better not to do this but the performance of the API is directly affected by having to
    # create these instances when they do not exist.
    has_one :uuid_object, class_name: 'Uuid', as: :resource, dependent: :destroy, inverse_of: :resource
    after_create :ensure_uuid_created, unless: :lazy_uuid_generation?

    # Some named scopes ...
    scope :include_uuid, ->() { includes(:uuid_object) }
    scope :with_uuid, ->(uuid) { joins(:uuid_object).where(uuids: { external_id: uuid }) }
  end
end

Instance Method Details

#unsaved_uuid!Object

Marks a record as being unsaved and hence the UUID is not present. This is not something we want to actually happen without being explicitly told; hence, the 'uuid' method below will error if the record is unsaved as that's exactly what should happen.

It also means that marking a record by calling this method, and then attempting to save it, will result in another validation exception. Again, exactly what we want.


48
49
50
# File 'app/models/uuid.rb', line 48

def unsaved_uuid!
  self.uuid_object = Uuid.new(external_id: nil)
end

#uuidObject

– You cannot give a UUID to something that hasn't been saved, which means that the UUID can't be relied on to actually be present, nor can it be relied on to be output into any JSON in the API. ++


56
57
58
# File 'app/models/uuid.rb', line 56

def uuid
  (uuid_object || create_uuid_object).uuid
end