Module: NeatIds
- Defined in:
- lib/neat_ids.rb,
lib/neat_ids/engine.rb,
lib/neat_ids/neat_id.rb,
lib/neat_ids/version.rb
Defined Under Namespace
Modules: Attribute, Finder, Rails, ToParam Classes: Engine, Error, NeatId
Constant Summary collapse
- VERSION =
"1.1.0"
Class Method Summary collapse
-
.decode_neat_id(neat_id) ⇒ Object
Returns a decoded ID from a neat_id.
- .find(neat_id) ⇒ Object
- .register_prefix(prefix, model:) ⇒ Object
-
.split_id(neat_id, delimiter = NeatIds.delimiter) ⇒ Object
Splits a prefixed ID into its prefix and ID.
Class Method Details
.decode_neat_id(neat_id) ⇒ Object
Returns a decoded ID from a neat_id
39 40 41 42 43 44 45 46 |
# File 'lib/neat_ids.rb', line 39 def self.decode_neat_id(neat_id) return neat_id if neat_id.nil? || neat_id.is_a?(Integer) return neat_id unless models.keys.any? { |key| neat_id.to_s.start_with?("#{key}#{delimiter}") } model_name, _ = split_id(neat_id) models.fetch(model_name).decode_neat_id(neat_id) end |
.find(neat_id) ⇒ Object
31 32 33 34 35 36 |
# File 'lib/neat_ids.rb', line 31 def self.find(neat_id) prefix, _ = split_id(neat_id) models.fetch(prefix).find_by_neat_id(neat_id) rescue KeyError raise Error, "Unable to find model with prefix `#{prefix}`. Available prefixes are: #{models.keys.join(", ")}" end |
.register_prefix(prefix, model:) ⇒ Object
54 55 56 57 58 59 60 |
# File 'lib/neat_ids.rb', line 54 def self.register_prefix(prefix, model:) if (existing_model = NeatIds.models[prefix]) && existing_model.name != model.name raise Error, "Prefix #{prefix} already defined for model #{existing_model.name}" end NeatIds.models[prefix] = model end |
.split_id(neat_id, delimiter = NeatIds.delimiter) ⇒ Object
Splits a prefixed ID into its prefix and ID
49 50 51 52 |
# File 'lib/neat_ids.rb', line 49 def self.split_id(neat_id, delimiter = NeatIds.delimiter) prefix, _, id = neat_id.to_s.rpartition(delimiter) [prefix, id] end |