Module: Uuvula

Defined in:
lib/uuvula.rb

Overview

TODO: Refactor into a gem.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Class Method Details

.convert_uuid_to_raw(value) ⇒ Object



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

def self.convert_uuid_to_raw(value)
  case value
  when UUIDTools::UUID
    value.raw
  when String
    case value.size
    when 36, 32
      value = value.gsub('-','')
      UUIDTools::UUID.parse_hexdigest(value).raw
    when 16
      value
    end
  else
    nil
  end
end

.define_callbacks(mod, column_name) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
# File 'lib/uuvula.rb', line 54

def self.define_callbacks(mod, column_name)
  method_body = <<-EOF
    def _generate_uuid
      if self.#{column_name}.blank?
        self.#{column_name} = UUIDTools::UUID.timestamp_create
      end
    end
  EOF
  mod.send(:class_eval, method_body, __FILE__, __LINE__)
  mod.send(:before_save, :_generate_uuid)
end

.define_uuid_reader(mod, column_name) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/uuvula.rb', line 35

def self.define_uuid_reader(mod, column_name)
  method_body = <<-EOF
    def #{column_name}
      value = read_attribute_before_type_cast('#{column_name}')
      UUIDTools::UUID.parse_raw(value).hexdigest if value
    end
  EOF
  mod.send(:class_eval, method_body, __FILE__, __LINE__)
end

.define_uuid_writer(mod, column_name) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/uuvula.rb', line 45

def self.define_uuid_writer(mod, column_name)
  method_body = <<-EOF
    def #{column_name}=(value)
      write_attribute('#{column_name}', Uuvula.convert_uuid_to_raw(value))
    end
  EOF
  mod.send(:class_eval, method_body, __FILE__, __LINE__)
end

.included(mod) ⇒ Object



11
12
13
14
15
16
# File 'lib/uuvula.rb', line 11

def self.included(mod)
  mod.extend(ClassMethods)
  class << mod
    alias_method_chain :sanitize_sql_hash_for_conditions, :uuid_support
  end
end