Module: Sequel::Plugins::UUIDPrefix::ClassMethods

Defined in:
lib/sequel/plugins/uuid_prefix.rb

Instance Method Summary collapse

Instance Method Details

#[](*args) ⇒ Object

Override Model.[] to add lookup by uuid.

Examples:

Account['a-xxxxxx']


162
163
164
165
166
167
168
# File 'lib/sequel/plugins/uuid_prefix.rb', line 162

def [](*args)
  if args.size == 1 and args[0].is_a? String
    super(:uuid=>trim_uuid(args[0]))
  else
    super(*args)
  end
end

#check_trimmed_uuid_format(uuid) ⇒ Object

Checks the general uuid syntax



193
194
195
# File 'lib/sequel/plugins/uuid_prefix.rb', line 193

def check_trimmed_uuid_format(uuid)
  uuid.match(/^[\w]+$/) && uuid.length <= 255
end

#check_uuid_format(uuid) ⇒ Object

Checks the uuid syntax if it is for the UUIDPrefix class.



198
199
200
# File 'lib/sequel/plugins/uuid_prefix.rb', line 198

def check_uuid_format(uuid)
  uuid =~ /^#{self.uuid_prefix}-/
end

#dataset_where_uuid(p_uuid) ⇒ Object

Returns dataset which has been selected for the uuid.

Examples:

Account.dataset_where_uuid('a-xxxxxx')


174
175
176
# File 'lib/sequel/plugins/uuid_prefix.rb', line 174

def dataset_where_uuid(p_uuid)
  dataset.where(uuid: trim_uuid(p_uuid))
end

#trim_uuid(p_uuid) ⇒ Object

Returns the uuid string which is removed prefix part: /^(:?w+)-/.

Examples:

Account.trim_uuid('a-abcd1234') # = 'abcd1234'

Will get InvalidUUIDError as the uuid with invalid prefix has been tried.

Account.trim_uuid('u-abcd1234') # 'u-' prefix is for User model.

Raises:



184
185
186
187
188
189
190
# File 'lib/sequel/plugins/uuid_prefix.rb', line 184

def trim_uuid(p_uuid)
  regex = %r/^#{self.uuid_prefix}-/
  if p_uuid and p_uuid =~ regex
    return p_uuid.sub(regex, '')
  end
  raise InvalidUUIDError, "Invalid uuid or unsupported uuid: #{p_uuid} in #{self}"
end

#uuid_prefix(prefix = nil) ⇒ Object

Getter and setter for uuid_prefix of the class.

Examples:

class Model1 < Sequel::Model
  plugin UUIDPrefix
  uuid_prefix('m')
end

Model1.uuid_prefix # == 'm'
Model1.new.canonical_uuid # == 'm-abcd1234'


142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/sequel/plugins/uuid_prefix.rb', line 142

def uuid_prefix(prefix=nil)
  if prefix
    if UUIDPrefix.uuid_prefix_collection.has_key?(prefix)
      raise UUIDPrefixDuplication, "Found collision for uuid_prefix key: #{prefix}"
    end

    UUIDPrefix.uuid_prefix_collection[prefix]={:class=>self}
    @uuid_prefix = prefix
  end

  @uuid_prefix ||
    (superclass.uuid_prefix if superclass.respond_to?(:uuid_prefix)) ||
    raise(UnsetUUIDPrefix, "uuid prefix is unset for: #{self}")
end

#valid_uuid_syntax?(uuid) ⇒ Boolean

Returns:

  • (Boolean)


202
203
204
# File 'lib/sequel/plugins/uuid_prefix.rb', line 202

def valid_uuid_syntax?(uuid)
  uuid =~ /^#{self.uuid_prefix}-[\w]+/
end