Module: WithUid::ClassMethods

Defined in:
lib/with_uid.rb

Instance Method Summary collapse

Instance Method Details

#by_uid(uid) ⇒ ActiveRecord::Base?

Find record by uid

Parameters:

  • uid (String)

Returns:

  • (ActiveRecord::Base, nil)

See Also:

  • #find_by


36
37
38
# File 'lib/with_uid.rb', line 36

def by_uid(uid)
  find_by(uid: uid)
end

#by_uid!(uid) ⇒ ActiveRecord::Base

Find record by uid

Parameters:

  • uid (String)

Returns:

  • (ActiveRecord::Base)

Raises:

  • (ActiveRecord::RecordNotFound)

    if no such record

See Also:

  • #find_by!


26
27
28
# File 'lib/with_uid.rb', line 26

def by_uid!(uid)
  find_by!(uid: uid)
end

#generate_uid(**options, &block) ⇒ void

This method returns an undefined value.

Generate uid for given model

If no block given it will generate uid according RFC 4122. You are free to customize this uid with :prefix.

Examples:

without block

class User < ActiveRecord::Base
  generate_uid(prefix: ->(user) { user.sex })
end

with block using user’s name

class User < ActiveRecord::Base
  generate_uid(prefix: 'user_') do
    WithUid.format(name)
  end
end

RFC 4122 uid

class User < ActiveRecord::Base
  generate_uid
end

Parameters:

  • (Hash)
  • options (Hash)

    a customizable set of options

Options Hash (**options):

  • :prefix (String, Proc) — default: ''

    prefix for uid inserted for each generated uid.

  • :suffix (String, Proc) — default: random string

    for uid inserted if uid is not uniq.

Yield Returns:

  • (String)

    generated uid. So you may specify the way of generating uid.



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

def generate_uid(**options, &block)
  before_validation do
    if block_given?
      generate_uid(**options, &block)
    else
      generate_uid(**options.merge(suffix: '')) do
        SecureRandom.uuid
      end
    end
  end
end

#humanize_uid_with(attr, **options) ⇒ void

This method returns an undefined value.

Generate uid using record’s attribute

Examples:

class User < ActiveRecord::Base
  humanize_uid_with(:name, prefix: 'user_')
end
user = User.create(name: 'Tema Bolshakov')
user.uid #=> "tema_bolshakov"

Parameters:

  • attr (Symbol)

    attribute name

  • options (Hash)

    @see #generate_uid



96
97
98
99
100
101
# File 'lib/with_uid.rb', line 96

def humanize_uid_with(attr, **options)
  generate_uid(**options) do
    value = send(attr)
    WithUid.format(value) if value.present?
  end
end