Module: ActiveID::Utils

Defined in:
lib/active_id/utils.rb

Overview

Variety of convenience functions.

Class Method Summary collapse

Class Method Details

.cast_to_uuid(value) ⇒ UUIDTools::UUID?

Casts value to UUIDTools::UUID.

When an instance of UUIDTools::UUID or nil is given, then this method returns that argument. When a String is given, then it is parsed, and respective instance of UUIDTools::UUID is returned.

A variety of string formats is recognized:

  • 36 characters long strings (hexadecimal number interpolated with dashes)

  • 32 characters long strings (hexadecimal number without dashes)

  • 16 bytes long strings (binary representation of UUID)

Parameters:

  • value (UUIDTools::UUID, String, nil)

    value to be casted to UUIDTools::UUID.

Returns:

  • (UUIDTools::UUID, nil)

    respective UUID instance or nil.

Raises:

  • (ArgumentError)

    argument cannot be casted to UUIDTools::UUID.



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/active_id/utils.rb', line 24

def cast_to_uuid(value)
  case value
  when UUIDTools::UUID, nil
    value
  when String
    parse_uuid_string(value)
  else
    m = "UUID, String, or nil required, but '#{value.inspect}' was given"
    raise ArgumentError, m
  end
end

.quote_as_binary(value) ⇒ ::ActiveRecord::Type::Binary::Data?

Casts UUID to binary and quotes it, so that it can be used in SQL query interpolation.

model.where("id = ?", ActiveID.quote_as_binary(some_uuid))

This method is unable to determine the correct attribute type. It always casts UUIDs to their binary form, which may be unwanted in some contexts, i.e. in case of UUIDs which are meant to be serialized as strings or as Postgres’ native UUID data type. Due to this fact, it is generally recommended to avoid SQL query interpolation if possible.

Parameters:

  • value (UUIDTools::UUID, String, nil)

    UUID or its representation to be quoted.

Returns:

  • (::ActiveRecord::Type::Binary::Data, nil)

    a binary value which can be used in SQL queries.

Raises:

  • (ArgumentError)

    see cast_to_uuid.



52
53
54
55
# File 'lib/active_id/utils.rb', line 52

def quote_as_binary(value)
  uuid = cast_to_uuid(value)
  uuid && ::ActiveRecord::Type::Binary::Data.new(uuid.raw)
end