Class: BinData::Registry

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

Overview

This registry contains a register of name -> class mappings.

Numerics (integers and floating point numbers) have an endian property as part of their name (e.g. int32be, float_le).

Classes can be looked up based on their full name or an abbreviated name with hints.

There are two hints supported, :endian and :search_prefix.

#lookup("int32", { endian: :big }) will return Int32Be.

#lookup("my_type", { search_prefix: :ns }) will return NsMyType.

Names are stored in under_score_style, not camelCase.

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



21
22
23
# File 'lib/bindata/registry.rb', line 21

def initialize
  @registry = {}
end

Instance Method Details

#lookup(name, hints = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/bindata/registry.rb', line 38

def lookup(name, hints = {})
  the_class = @registry[normalize_name(name, hints)]
  if the_class
    the_class
  elsif @registry[normalize_name(name, hints.merge(endian: :big))]
    raise(UnRegisteredTypeError, "#{name}, do you need to specify endian?")
  else
    raise(UnRegisteredTypeError, name)
  end
end

#register(name, class_to_register) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/bindata/registry.rb', line 25

def register(name, class_to_register)
  return if name.nil? || class_to_register.nil?

  formatted_name = underscore_name(name)
  warn_if_name_is_already_registered(formatted_name, class_to_register)

  @registry[formatted_name] = class_to_register
end

#underscore_name(name) ⇒ Object

Convert CamelCase name to underscore style.



50
51
52
53
54
55
56
57
58
# File 'lib/bindata/registry.rb', line 50

def underscore_name(name)
  name
    .to_s
    .sub(/.*::/, "")
    .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
    .gsub(/([a-z\d])([A-Z])/, '\1_\2')
    .tr('-', '_')
    .downcase
end

#unregister(name) ⇒ Object



34
35
36
# File 'lib/bindata/registry.rb', line 34

def unregister(name)
  @registry.delete(underscore_name(name))
end