Class: Strict::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/strict/attribute.rb

Constant Summary collapse

NOT_PROVIDED =
::Object.new.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, validator:, default_generator:, coercer:) ⇒ Attribute

Returns a new instance of Attribute.



46
47
48
49
50
51
52
53
# File 'lib/strict/attribute.rb', line 46

def initialize(name:, validator:, default_generator:, coercer:)
  @name = name.to_sym
  @validator = validator
  @default_generator = default_generator
  @coercer = coercer
  @optional = !default_generator.equal?(NOT_PROVIDED)
  @instance_variable = "@#{name.to_s.chomp('!').chomp('?')}"
end

Instance Attribute Details

#coercerObject (readonly)

Returns the value of attribute coercer.



44
45
46
# File 'lib/strict/attribute.rb', line 44

def coercer
  @coercer
end

#default_generatorObject (readonly)

Returns the value of attribute default_generator.



44
45
46
# File 'lib/strict/attribute.rb', line 44

def default_generator
  @default_generator
end

#instance_variableObject (readonly)

Returns the value of attribute instance_variable.



44
45
46
# File 'lib/strict/attribute.rb', line 44

def instance_variable
  @instance_variable
end

#nameObject (readonly)

Returns the value of attribute name.



44
45
46
# File 'lib/strict/attribute.rb', line 44

def name
  @name
end

#validatorObject (readonly)

Returns the value of attribute validator.



44
45
46
# File 'lib/strict/attribute.rb', line 44

def validator
  @validator
end

Class Method Details

.make(name, validator = Validators::Anything.instance, coerce: false, **defaults) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/strict/attribute.rb', line 8

def make(name, validator = Validators::Anything.instance, coerce: false, **defaults)
  unless valid_defaults?(**defaults)
    raise ArgumentError, "Only one of 'default', 'default_value', or 'default_generator' can be provided"
  end

  new(
    name: name.to_sym,
    validator: validator,
    default_generator: make_default_generator(**defaults),
    coercer: coerce
  )
end

Instance Method Details

#coerce(value, for_class:) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/strict/attribute.rb', line 65

def coerce(value, for_class:)
  return value unless coercer

  case coercer
  when Symbol
    for_class.public_send(coercer, value)
  when true
    for_class.public_send("coerce_#{name}", value)
  else
    coercer.call(value)
  end
end

#optional?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/strict/attribute.rb', line 55

def optional?
  @optional
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
62
63
# File 'lib/strict/attribute.rb', line 59

def valid?(value)
  return true unless Strict.configuration.validate?

  validator === value
end