Class: Nocode::Util::ClassRegistry

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/nocode/util/class_registry.rb

Overview

Create a type -> class constant interface. Classes can be registered as types. Types are snake-cased while class names are stored as pascal-cased. Then constant! can be called to retrieve the class constant by type.

Direct Known Subclasses

StepRegistry

Defined Under Namespace

Classes: NotRegisteredError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(types_to_classes = {}) ⇒ ClassRegistry

Returns a new instance of ClassRegistry.



17
18
19
20
21
# File 'lib/nocode/util/class_registry.rb', line 17

def initialize(types_to_classes = {})
  @types_to_classes = Dictionary.new(types_to_classes)

  freeze
end

Instance Attribute Details

#types_to_classesObject (readonly)

Returns the value of attribute types_to_classes.



13
14
15
# File 'lib/nocode/util/class_registry.rb', line 13

def types_to_classes
  @types_to_classes
end

Instance Method Details

#constant!(type) ⇒ Object

Raises:



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/nocode/util/class_registry.rb', line 43

def constant!(type)
  name = types_to_classes[type]

  raise NotRegisteredError, "Constant not registered for: #{type}" if name.to_s.empty?

  if Object.const_defined?(name, false)
    Object.const_get(name, false)
  else
    Object.const_missing(name)
  end
end

#load(types, class_prefix: '', type_prefix: '') ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/nocode/util/class_registry.rb', line 23

def load(types, class_prefix: '', type_prefix: '')
  types.each do |type|
    pascal_cased = type.split(File::SEPARATOR).map do |part|
      part.split('_').collect(&:capitalize).join
    end.join('::')

    register("#{type_prefix}#{type}", "#{class_prefix}#{pascal_cased}")
  end

  self
end

#register(type, class_name) ⇒ Object



35
36
37
# File 'lib/nocode/util/class_registry.rb', line 35

def register(type, class_name)
  tap { types_to_classes[type] = class_name }
end

#unregister(type) ⇒ Object



39
40
41
# File 'lib/nocode/util/class_registry.rb', line 39

def unregister(type)
  tap { types_to_classes.delete(type) }
end