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.



109
110
111
# File 'lib/cool_id.rb', line 109

def initialize
  @prefix_map = {}
end

Instance Method Details

#locate(id) ⇒ ActiveRecord::Base?

Locates a record by its CoolId.

Parameters:

  • id (String)

    The CoolId to look up.

Returns:

  • (ActiveRecord::Base, nil)

    The found record, or nil if not found.



124
125
126
127
128
129
130
# File 'lib/cool_id.rb', line 124

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:

  • id (String)

    The CoolId to parse.

Returns:

  • (Id, nil)

    The parsed Id object, or nil if parsing fails.



135
136
137
138
139
140
141
# File 'lib/cool_id.rb', line 135

def parse(id)
  prefix, key = id.split(CoolId.separator, 2)
  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:

  • prefix (String)

    The prefix to register.

  • model_class (Class)

    The ActiveRecord model class to associate with the prefix.



117
118
119
# File 'lib/cool_id.rb', line 117

def register(prefix, model_class)
  @prefix_map[prefix] = model_class
end