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
48
49
50
51
52
53
54
55
# File 'lib/bindata/registry.rb', line 38

def lookup(name, hints = {})
  search_names(name, hints).each do |search|
    register_dynamic_class(search)
    if @registry.has_key?(search)
      return @registry[search]
    end
  end

  # give the user a hint if the endian keyword is missing
  search_names(name, hints.merge(endian: :big)).each do |search|
    register_dynamic_class(search)
    if @registry.has_key?(search)
      raise(UnRegisteredTypeError, "#{name}, do you need to specify endian?")
    end
  end

  raise(UnRegisteredTypeError, name)
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.



58
59
60
61
62
63
64
65
66
# File 'lib/bindata/registry.rb', line 58

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