Module: ActiveRecord::KSUID

Defined in:
lib/active_record/ksuid.rb,
lib/active_record/ksuid/type.rb,
lib/active_record/ksuid/railtie.rb,
lib/active_record/ksuid/version.rb,
lib/active_record/ksuid/binary_type.rb,
lib/active_record/ksuid/prefixed_type.rb,
lib/active_record/ksuid/table_definition.rb

Overview

Enables an Active Record model to have a KSUID attribute

Since:

  • 0.5.0

Defined Under Namespace

Modules: TableDefinition Classes: BinaryType, PrefixedType, Railtie, Type

Constant Summary collapse

VERSION =

The version of the activerecord-ksuid gem

Returns:

  • (String)

Since:

  • 0.5.0

'1.0.0'

Class Method Summary collapse

Class Method Details

.[](field, auto_gen: true, created_at: false, binary: false, prefix: nil) ⇒ Module

Builds a module to include into the model

Examples:

Add a ‘#ksuid` attribute to a model

class Event < ActiveRecord::Base
  include ActiveRecord::KSUID[:ksuid]
end

Add a ‘#remote_id` attribute to a model and overrides `#created_at` to use the KSUID

class Event < ActiveRecord::Base
  include ActiveRecord::KSUID[:remote_id, created_at: true]
end

Add a prefixed ‘#ksuid` attribute to a model

class Event < ActiveRecord::Base
  include ActiveRecord::KSUID[:ksuid, prefix: 'evt_']
end

Parameters:

  • auto_gen (Boolean) (defaults to: true)

    whether to generate a KSUID upon initialization

  • field (String, Symbol)

    the name of the field to use as a KSUID

  • created_at (Boolean) (defaults to: false)

    whether to override the ‘#created_at` method

  • binary (Boolean) (defaults to: false)

    whether to store the KSUID as a binary or a string

  • prefix (String, nil) (defaults to: nil)

    a prefix to prepend to the KSUID attribute

Returns:

  • (Module)

    the module to include into the model

Raises:

  • (ArgumentError)

Since:

  • 0.5.0



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/active_record/ksuid.rb', line 41

def self.[](field, auto_gen: true, created_at: false, binary: false, prefix: nil)
  raise ArgumentError, 'cannot include a prefix on a binary KSUID' if binary && prefix

  Module.new.tap do |mod|
    if prefix
      define_prefixed_attribute(field, mod, auto_gen, prefix)
    else
      define_attribute(field, mod, auto_gen, binary)
    end
    define_created_at(field, mod) if created_at
  end
end