Module: UniverseCompiler::Entity::FieldConstraintManagement

Included in:
Base
Defined in:
lib/universe_compiler/entity/field_constraint_management.rb

Constant Summary collapse

BOOLEAN_CONSTRAINTS =
%i(not_null not_empty is_array is_hash).freeze
PARAMETRIZED_CONSTRAINTS =
%i(should_match class_name).freeze
INCOMPATIBLE_CONSTRAINTS =
{
    has_one: %i(has_many is_array is_hash),
    has_many: %i(has_one is_hash),
    is_array: %i(has_one is_hash),
    is_hash: %i(has_one has_many is_array)
}.freeze

Instance Method Summary collapse

Instance Method Details

#define_constraint(field_name, constraint_name = nil, value = nil) ⇒ Object



78
79
80
81
82
83
84
# File 'lib/universe_compiler/entity/field_constraint_management.rb', line 78

def define_constraint(field_name, constraint_name = nil, value = nil)
  fields_constraints[field_name] ||= {}
  check_constraints_incompatibilities(field_name, constraint_name)
  unless constraint_name.nil? and value.nil?
    fields_constraints[field_name][constraint_name] = value
  end
end

#field(field_name, *options) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/universe_compiler/entity/field_constraint_management.rb', line 44

def field(field_name, *options)
  ['', '='].each do |suffix|
    method_name = '%s%s' % [field_name, suffix]
    if instance_methods.include? method_name
      raise UniverseCompiler::Error,
            "'#{method_name}' method cannot be defined on '#{self}' as it is already defined  !"
    end
  end

  define_constraint field_name if options.empty?

  options.each do |option|
    case option
    when Symbol || String
      if BOOLEAN_CONSTRAINTS.include? option.to_sym
        send option, field_name
      else
        raise UniverseCompiler::Error, "Unknown field option '#{option}' !"
      end
    when Hash
      option.each do |constraint_name, value|
        if PARAMETRIZED_CONSTRAINTS.include? constraint_name.to_sym
          send constraint_name, field_name, value
        else
          raise UniverseCompiler::Error, "Unknown field option '#{constraint_name}' !"
        end
      end
    else
      raise UniverseCompiler::Error, "Invalid option for '#{field_name}': #{option.class.name} => #{option.to_s}"
    end
  end

end

#fields_constraintsObject



16
17
18
19
20
21
22
23
24
# File 'lib/universe_compiler/entity/field_constraint_management.rb', line 16

def fields_constraints
  return @fields_constraints unless @fields_constraints.nil?

  @fields_constraints = if superclass.respond_to? :fields_constraints
                          superclass.fields_constraints.dup
                        else
                          {}
                        end
end