Class: CoolId::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/cool_id.rb

Overview

Registry for managing prefixes and model classes.

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



112
113
114
# File 'lib/cool_id.rb', line 112

def initialize
  @prefix_map = {}
end

Instance Method Details

#locate(id) ⇒ ActiveRecord::Base?

Locates a record by its CoolId.

Parameters:

  • The CoolId to look up.

Returns:

  • The found record, or nil if not found.



139
140
141
142
143
144
145
# File 'lib/cool_id.rb', line 139

def locate(id)
  parsed = parse(id)
  return nil unless parsed

  id_field = CoolId.resolve_cool_id_field(parsed.model_class)
  parsed.model_class.find_by(id_field => id)
end

#parse(id) ⇒ Id?

Parses a CoolId into its components.

Parameters:

  • The CoolId to parse.

Returns:

  • The parsed Id object, or nil if parsing fails.



150
151
152
153
154
155
156
157
158
# File 'lib/cool_id.rb', line 150

def parse(id)
  components = id.split(CoolId.separator)
  prefix = components[0..-2].join(CoolId.separator)
  key = components[-1]
  model_class = @prefix_map[prefix]
  return nil unless model_class
  id_field = CoolId.resolve_cool_id_field(model_class)
  Id.new(key, prefix, id, model_class, id_field)
end

#register(prefix, model_class) ⇒ void

This method returns an undefined value.

Registers a prefix with a model class.

Parameters:

  • The prefix to register.

  • The ActiveRecord model class to associate with the prefix.

Raises:

  • If the prefix is already registered to a different model.



121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/cool_id.rb', line 121

def register(prefix, model_class)
  existing = @prefix_map[prefix]
  if existing
    same_class = if existing.name && model_class.name
      existing.name == model_class.name
    else
      existing == model_class
    end
    unless same_class
      raise DuplicatePrefixError, "Prefix '#{prefix}' is already registered to #{existing.name}"
    end
  end
  @prefix_map[prefix] = model_class
end