Module: Ant::Nanoservice::MetaTypes

Extended by:
DRY::ResourceInjector, Storage::Exceptions
Defined in:
lib/ant/nanoservice/metatypes.rb

Overview

This module is a factory of types. This will provide a class from the configurations, attaching all the validations requested. Currently it only plugs the validations and the repository inside the factory so you can start using them on your code

Class Method Summary collapse

Class Method Details

.build(name, fields, _configs) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/ant/nanoservice/metatypes.rb', line 63

def build(name, fields, _configs)
  validations = validation_builder(fields)
  klass = Class.new(Ant::Storage::Datasource::Model)
  build_constructor(klass)
  build_validation_errors_method(klass)
  class_name = name.split('_').collect(&:capitalize).join
  MetaTypes.const_set(class_name, klass)
  klass.const_set('VALIDATIONS', validations)
  klass.const_set('NAME', name)
  klass.const_set('PRIMARY_KEY', primary_keys(fields))
  klass
end

.build_constructor(klass) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ant/nanoservice/metatypes.rb', line 25

def build_constructor(klass)
  klass.define_method :initialize do |data|
    @data = {}
    data.each do |key, val|
      case key
      when Symbol
        @data[key] = val if self.class::VALIDATIONS.key?(key)
      when String
        if self.class::VALIDATIONS.keys.map(&:to_s).include?(key)
          @data[key.to_sym] = val
        end
      end
    end
  end
end

.build_validation_errors_method(klass) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ant/nanoservice/metatypes.rb', line 41

def build_validation_errors_method(klass)
  klass.define_method :validation_errors do
    result = {}
    self.class::VALIDATIONS.each do |key, validation|
      problems = validation.map { |val| val.call(@data[key]) }.compact
      result[key] = problems unless problems.empty?
    end
    result
  end
  klass.define_method :run_validations! do
    errors = validation_errors
    raise ValidationErrors, errors unless errors.empty?
  end
end

.primary_keys(fields) ⇒ Object



56
57
58
59
60
61
# File 'lib/ant/nanoservice/metatypes.rb', line 56

def primary_keys(fields)
  fields.select { |_, conf| conf['keys'] && conf['keys']['primary'] }
        .keys
        .first
        &.to_sym
end

.validation_builder(fields) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/ant/nanoservice/metatypes.rb', line 17

def validation_builder(fields)
  fields.each_with_object({}) do |(field, plugins), obj|
    obj[field.to_sym] = plugins.map do |plug, conf|
      Validator.validator(plug).curry.call(conf)
    end
  end
end