Module: Schema::AttributeMacro

Defined in:
lib/schema/schema.rb

Instance Method Summary collapse

Instance Method Details

#attribute_macro(attribute_name, type = nil, strict: nil, default: nil) ⇒ Object Also known as: attribute



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
# File 'lib/schema/schema.rb', line 28

def attribute_macro(attribute_name, type=nil, strict: nil, default: nil)
  if type.nil? && !strict.nil?
    raise Schema::Attribute::Error, "The \"#{attribute_name}\" attribute is declared with the \"strict\" option but a type is not specified"
  end

  if type == Boolean && strict == false
    raise Schema::Attribute::Error, "The \"#{attribute_name}\" attribute is declared with the \"strict\" option disabled but boolean type is specified"
  end

  check = nil

  if type == Boolean
    strict ||= true

    check = proc do |val|
      unless val.nil? || Boolean.(val)
        raise Schema::Attribute::TypeError, "#{val.inspect} is not a boolean"
      end
    end
  elsif !type.nil?
    strict ||= false

    check = proc do |val|
      unless val.nil?
        if strict
          raise Schema::Attribute::TypeError, "#{val.inspect} is not an instance of #{type.name}" unless val.instance_of? type
        else
          raise Schema::Attribute::TypeError, "#{val.inspect} is not a kind of #{type.name}" unless val.is_a? type
        end
      end
    end
  end

  initialize_value = nil
  if default.is_a? Proc
    initialize_value = default
  elsif !default.nil?
    initialize_value = proc { default.clone }
  end

  ::Attribute::Define.(self, attribute_name, :accessor, check: check, &initialize_value)

  attribute = attributes.register(attribute_name, type, strict)
  attribute
end