Class: ValidatesStructure::Validator

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/validates-structure.rb

Defined Under Namespace

Classes: Boolean, EnumerableValidator, KlassValidator, NestedValidator, NotBlankValidator, NotNilValidator

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Validator

Returns a new instance of Validator.



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/validates-structure.rb', line 15

def initialize(hash)
  self.class.initialize_class_attributes
  self.keys = []

  return unless hash.is_a?(Hash)

  hash.each do |key, value|
    self.keys << key.to_s
    send "#{key}=", value if respond_to? "#{key}="
  end
end

Instance Attribute Details

#keysObject

Returns the value of attribute keys.



13
14
15
# File 'lib/validates-structure.rb', line 13

def keys
  @keys
end

Class Method Details

.human_attribute_name(attr) ⇒ Object



69
70
71
# File 'lib/validates-structure.rb', line 69

def self.human_attribute_name(attr, *)
  "/#{attr}"
end

.key(key, klass, validations = {}, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/validates-structure.rb', line 27

def self.key(key, klass, validations={}, &block)
  initialize_class_attributes
  key = key.to_s

  if klass.class != Class
    raise ArgumentError.new("Types must be given as classes")
  end
  unless @nested_array_key.nil?
    raise ArgumentError.new("Key can not only appear within a block of a key of type Array")
  end
  if keys.include?(key)
    raise ArgumentError.new("Dublicate key \"#{key}\"")
  end

  keys << key
  attr_accessor key

  validations = prepare_validations(klass, validations, &block)
  validates key, validations

  nest_dsl(klass, key, &block)
end

.value(klass, validations = {}, &block) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/validates-structure.rb', line 50

def self.value(klass, validations={}, &block)
  initialize_class_attributes

  if klass.class != Class
    raise ArgumentError.new("Types must be given as classes")
  end
  if @nested_array_key.nil?
    raise ArgumentError.new("Value can only appear within the block of a key of Array type")
  end
  if values[@nested_array_key]
    raise ArgumentError.new("Value can only appear once within a block")
  end
  values[@nested_array_key] = klass

  validations = prepare_validations(klass, validations, &block)
  validates @nested_array_key, enumerable: validations
  nest_dsl(klass, @nested_array_key, &block)
end