Module: ActiveRecord::Acts::HasUuid

Defined in:
lib/has_uuid.rb

Overview

has_uuid adds a UUID to your models. See the README for details.

Defined Under Namespace

Modules: InstanceMethods

Constant Summary collapse

GENERATORS =
[:random, :timestamp]
DEFAULT_OPTIONS =
{:auto => true, :generator => :random, :column => :uuid}

Instance Method Summary collapse

Instance Method Details

#generate_uuidObject



35
36
37
# File 'lib/has_uuid.rb', line 35

def generate_uuid
  UUIDTools::UUID.send("#{uuid_generator}_create").to_s
end

#has_uuid(options = {}) ⇒ Object

Class Macro which actually lets models use has_uuid

  • column: The column in which to store the UUID (default: uuid).

  • auto: Assign a UUID on create (default: true).

  • generator The UUID generator. Possible values are ‘random` default) and `timestamp`.

Parameters:

  • options:

Raises:

  • (ArgumentError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/has_uuid.rb', line 15

def has_uuid(options = {})
  options.reverse_merge! DEFAULT_OPTIONS
  raise ArgumentError, "Invalid UUID generator #{options[:generator]}" unless GENERATORS.include?(options[:generator])

  class_eval do
    include InstanceMethods

    if options[:auto]
      before_validation(:on => :create) { assign_uuid }
      before_save(:on => :create) { assign_uuid }
    end

    class_attribute :uuid_column
    self.uuid_column = options[:column]

    class_attribute :uuid_generator
    self.uuid_generator = options[:generator]
  end
end