Module: HasUuid::Mixin::ClassMethods

Defined in:
lib/has_uuid.rb

Instance Method Summary collapse

Instance Method Details

#has_uuid(options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/has_uuid.rb', line 14

def has_uuid(options = {})
  self.class_eval do
    cattr_accessor :has_uuid_options
    self.has_uuid_options = options
    options[:primary_uuid] ||= :uuid

    if options[:primary_uuid] != :uuid
      class_eval do
        include ActiveUUID::UUID

        def uuid
          self.send self.class.primary_uuid
        end

        def uuid=(uuid)
          self.send "#{self.class.primary_uuid}=".to_sym, uuid
        end
      end
    end

    class_eval do
      before_create :generate_uuids_if_needed

      def generate_uuids_if_needed
        unless self.uuid
          begin
            self.uuid = UUIDTools::UUID.random_create
          end while !HasUuid.check_uuid(self)
        end
      end
    end
  end
end

#primary_uuidObject



48
49
50
# File 'lib/has_uuid.rb', line 48

def primary_uuid
  self.has_uuid_options[:primary_uuid]
end