Class: ViewModel::Registry

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/view_model/registry.rb

Constant Summary collapse

DEFERRED_NAME =
Object.new

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



14
15
16
17
18
# File 'lib/view_model/registry.rb', line 14

def initialize
  @lock = Monitor.new
  @viewmodel_classes_by_name = {}
  @deferred_viewmodel_classes = []
end

Instance Method Details

#allObject



37
38
39
40
41
42
# File 'lib/view_model/registry.rb', line 37

def all
  @lock.synchronize do
    resolve_deferred_classes
    @viewmodel_classes_by_name.values
  end
end

#clear_removed_classes!Object

For Rails hot code loading: ditch any classes that are not longer present at their constant



64
65
66
67
68
69
70
71
# File 'lib/view_model/registry.rb', line 64

def clear_removed_classes!
  @lock.synchronize do
    resolve_deferred_classes
    @viewmodel_classes_by_name.delete_if do |_name, klass|
      !Kernel.const_defined?(klass.name)
    end
  end
end

#default_view_name(model_class_name) ⇒ Object



54
55
56
# File 'lib/view_model/registry.rb', line 54

def default_view_name(model_class_name)
  model_class_name.gsub('::', '.')
end

#for_view_name(name) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/view_model/registry.rb', line 20

def for_view_name(name)
  raise ViewModel::DeserializationError::InvalidSyntax.new('ViewModel name cannot be nil') if name.nil?

  @lock.synchronize do
    # Resolve names for any deferred viewmodel classes
    resolve_deferred_classes

    viewmodel_class = @viewmodel_classes_by_name[name]

    if viewmodel_class.nil? || !(viewmodel_class < ViewModel)
      raise ViewModel::DeserializationError::UnknownView.new(name)
    end

    viewmodel_class
  end
end

#infer_model_class_name(view_name) ⇒ Object



58
59
60
# File 'lib/view_model/registry.rb', line 58

def infer_model_class_name(view_name)
  view_name.gsub('.', '::')
end

#register(viewmodel, as: DEFERRED_NAME) ⇒ Object



48
49
50
51
52
# File 'lib/view_model/registry.rb', line 48

def register(viewmodel, as: DEFERRED_NAME)
  @lock.synchronize do
    @deferred_viewmodel_classes << [viewmodel, as]
  end
end

#rootsObject



44
45
46
# File 'lib/view_model/registry.rb', line 44

def roots
  all.select { |c| c.root? }
end