Module: FriendlyUUID::Class

Defined in:
lib/friendly_uuid.rb

Instance Method Summary collapse

Instance Method Details

#adapterObject



84
85
86
87
88
89
90
# File 'lib/friendly_uuid.rb', line 84

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

#compact(uuid) ⇒ Object



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

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



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

def expand(short_uuids)
  # If a single ID passed as a string
  return self.expand_to_record(short_uuids).id if short_uuids.class == String

  # If a single ID passed as a non-nested array
  if short_uuids[0].class != Array && short_uuids.length == 1
    return self.expand_to_record(short_uuids.join).id
  end

  short_uuids.flatten!

  short_uuids.map do |uuid|
    self.expand_to_record(uuid).id
  end
end

#expand_to_record(short_uuid) ⇒ Object

Raises:

  • (ActiveRecord::RecordNotFound)


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

def expand_to_record(short_uuid)
  raise ActiveRecord::RecordNotFound unless short_uuid
  record = self.possible_expansions(short_uuid).first
  raise ActiveRecord::RecordNotFound unless record
  record
end

#find(*ids) ⇒ Object



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

def find(*ids)
  super(self.expand(ids))
end

#find_by(arg, *args) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/friendly_uuid.rb', line 62

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



58
59
60
# File 'lib/friendly_uuid.rb', line 58

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

#substr_queryObject



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/friendly_uuid.rb', line 71

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