Class: Strict::Parameter

Inherits:
Object
  • Object
show all
Defined in:
lib/strict/parameter.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:) ⇒ Parameter

Returns a new instance of Parameter.



46
47
48
49
50
51
52
# File 'lib/strict/parameter.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)
end

Instance Attribute Details

#coercerObject (readonly)

Returns the value of attribute coercer.



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

def coercer
  @coercer
end

#default_generatorObject (readonly)

Returns the value of attribute default_generator.



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

def default_generator
  @default_generator
end

#nameObject (readonly)

Returns the value of attribute name.



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

def name
  @name
end

#validatorObject (readonly)

Returns the value of attribute validator.



44
45
46
# File 'lib/strict/parameter.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/parameter.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) ⇒ Object



64
65
66
67
68
# File 'lib/strict/parameter.rb', line 64

def coerce(value)
  return value unless coercer

  coercer.call(value)
end

#optional?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/strict/parameter.rb', line 54

def optional?
  @optional
end

#valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
61
62
# File 'lib/strict/parameter.rb', line 58

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

  validator === value
end