Module: Taggable::ClassMethods

Defined in:
app/models/base_new.rb

Instance Method Summary collapse

Instance Method Details

#[](*args) ⇒ Object

Override Model.[] to add lookup by uuid.

Examples:

Account['a-xxxxxx']


133
134
135
136
137
138
139
# File 'app/models/base_new.rb', line 133

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



156
157
158
# File 'app/models/base_new.rb', line 156

def check_trimmed_uuid_format(uuid)
  uuid.match(/^[a-z0-9 ]*$/) && uuid.length <= 8
end

#check_uuid_format(uuid) ⇒ Object

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



161
162
163
# File 'app/models/base_new.rb', line 161

def check_uuid_format(uuid)
  uuid =~ /^#{self.uuid_prefix}-/
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.


147
148
149
150
151
152
153
# File 'app/models/base_new.rb', line 147

def trim_uuid(p_uuid)
  regex = %r/^#{self.uuid_prefix}-/
  if p_uuid and p_uuid =~ regex
    return p_uuid.sub(regex, '')
  end
  raise "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 Taggable
  uuid_prefix('m')
end

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


118
119
120
121
122
123
124
125
126
# File 'app/models/base_new.rb', line 118

def uuid_prefix(prefix=nil)
  if prefix
    raise UUIDPrefixDuplication, "Found collision for uuid_prefix key: #{prefix}" if Taggable.uuid_prefix_collection.has_key?(prefix)
  
    Taggable.uuid_prefix_collection[prefix]={:class=>self}
    @uuid_prefix = prefix
  end
  @uuid_prefix || raise("uuid prefix is unset for:#{self}")
end