Module: Schema::AttributeMacro

Defined in:
lib/schema/schema.rb

Defined Under Namespace

Modules: Defaults

Instance Method Summary collapse

Instance Method Details

#attribute_macro(attribute_name, type = nil, default: nil, check: 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
# File 'lib/schema/schema.rb', line 28

def attribute_macro(attribute_name, type=nil, default: nil, check: nil)
  check ||= Defaults.check

  attribute_check = lambda do |val|
    if not check.(type, val)
      raise Schema::Attribute::TypeError, "#{val.inspect} of type #{val.class.name} cannot be assigned to attribute #{attribute_name.inspect} of #{self.to_s}"
    end
  end

  if default.nil?
    initialize_value = nil
  elsif default.respond_to?(:call)
    initialize_value = default
  else
    raise Schema::Attribute::Error, "Default values must be callable, like procs, lambdas, or objects that respond to the call method (Attribute: #{attribute_name})"
  end

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

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