Module: FriendlyUUID::Class

Defined in:
lib/friendly_uuid.rb

Instance Method Summary collapse

Instance Method Details

#adapterObject



80
81
82
83
84
85
86
# File 'lib/friendly_uuid.rb', line 80

def adapter
  if respond_to?(:connection_db_config)
    connection_db_config.configuration_hash[:adapter]
  else
    connection_config[:adapter]
  end
end

#compact(uuid) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/friendly_uuid.rb', line 42

def compact(uuid)
  (0..uuid.length).each do |length|
    candidate = uuid[0..length]
    return candidate if self.expand(candidate) == uuid
  end
  raise ValueError("Cannot find expansion for UUID #{uuid}")
end

#expand(short_uuids) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/friendly_uuid.rb', line 29

def expand(short_uuids)
  if short_uuids.is_a?(String)
    self.expand_to_record(short_uuids)&.id
  elsif short_uuids[0].is_a?(String) && short_uuids.length == 1
    self.expand_to_record(short_uuids.join)&.id
  elsif short_uuids.is_a?(Array)
    short_uuids.flatten!
    short_uuids.map do |uuid|
      self.expand_to_record(uuid.to_s)&.id
    end
  end
end

#expand_to_record(short_uuid) ⇒ Object



50
51
52
# File 'lib/friendly_uuid.rb', line 50

def expand_to_record(short_uuid)
  self.possible_expansions(short_uuid).first
end

#find(*ids) ⇒ Object



23
24
25
26
27
# File 'lib/friendly_uuid.rb', line 23

def find(*ids)
  ids = self.expand(ids) if ids.flatten.any? { |id| id.present? }

  super(ids)
end

#find_by(arg, *args) ⇒ Object



58
59
60
61
62
63
64
65
# File 'lib/friendly_uuid.rb', line 58

def find_by(arg, *args)
  if arg.respond_to?(:[])
    arg[:id] = self.expand(arg[:id]) if arg[:id]
    arg["id"] = self.expand(arg["id"]) if arg["id"]
  end

  super
end

#possible_expansions(short_uuid) ⇒ Object



54
55
56
# File 'lib/friendly_uuid.rb', line 54

def possible_expansions(short_uuid)
  self.where(substr_query, short_uuid.length, short_uuid).order(created_at: :asc)
end

#substr_queryObject



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/friendly_uuid.rb', line 67

def substr_query
  case adapter
  when "mysql2"
    raise ValueError("Sorry, FriendlyUUID does not support MySQL")
  when "postgresql"
    "LEFT(#{self.table_name}.id::text, ?) = ?"
  when "sqlite3"
    "SUBSTR(#{self.table_name}.id, 0, ?) = ?"
  else
    raise ValueError("Unknown database type; FriendlyUUID cannot support it")
  end
end