Module: PrettyId::Core::ClassMethods

Defined in:
lib/pretty_id/core.rb

Instance Method Summary collapse

Instance Method Details

#has_pretty_id(options = {}) ⇒ Object



8
9
10
11
12
13
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
47
48
49
50
51
52
53
54
55
# File 'lib/pretty_id/core.rb', line 8

def has_pretty_id(options = {})
  default_options = {
    column: :pretty_id,
    method: :pretty,
    uniq: true
  }

  options = default_options.merge(options)

  case options[:method]
  when :pretty
    options[:length] ||= 8
    options[:generate_proc] = -> {
      chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
      Array.new(options[:length]) { chars[rand(chars.length)] }.join
    }
  when :urlsafe_base64
    options[:length] ||= 21
    options[:generate_proc] = -> {
      SecureRandom.urlsafe_base64(options[:length] / 1.333)
    }
  else
    fail 'Unknown :method passed to has_pretty_id'
  end

  define_method(:"generate_#{options[:column]}") do
    new_pretty_id = loop do
      random_pretty_id = options[:generate_proc].call
      break random_pretty_id if !options[:uniq]
      exists_hash = {}
      exists_hash[options[:column]] = random_pretty_id
      break random_pretty_id unless self.class.exists?(exists_hash)
    end

    self.send "#{options[:column]}=", new_pretty_id
  end

  define_method(:"regenerate_#{options[:column]}") do
    self.send("generate_#{options[:column]}")
  end

  define_method(:"regenerate_#{options[:column]}!") do
    self.send("generate_#{options[:column]}")
    self.save
  end

  before_create :"generate_#{options[:column]}"
end