class Ciesta::Field

Class for storing form field

@attr_reader [Symbol] name Field name @attr_reader [Ciesta::Types::Declaration] type Field type

Constants

DEFAULT_TYPE

Default type when another one is not passed

Attributes

name[R]
type[R]

Public Class Methods

new(name, **options) click to toggle source

Constructor

@param [Symbol] name Name of the field @param [Hash] options Field's options @option [Ciesta::Types::Definition] :type Type of value stored in this field @option [Proc, Lambda, any] :default Default value for this field

# File lib/ciesta/field.rb, line 19
def initialize(name, **options)
  @name = name.to_sym
  @type = options.delete(:type) || DEFAULT_TYPE
  @default = options.delete(:default)
end

Public Instance Methods

bind(obj) click to toggle source

Binds current field to object

@api private @param [Object] obj Object to mapping to

# File lib/ciesta/field.rb, line 50
def bind(obj)
  @binding = obj
end
clear!() click to toggle source

Clear field

# File lib/ciesta/field.rb, line 55
def clear!
  @value = nil
end
value() click to toggle source

Returns current value

@return [any]

# File lib/ciesta/field.rb, line 40
def value
  return @value if @was_set

  @value || default
end
value=(val) click to toggle source

Sets a new value for field

@param [any] val Value

@raise Ciesta::ViolatesConstraints

# File lib/ciesta/field.rb, line 30
def value=(val)
  @value = type[val]
  @was_set = true
rescue Dry::Types::ConstraintError
  raise Ciesta::ViolatesConstraints, "#{val} is not a valid #{name} (#{type.name})"
end

Private Instance Methods

default() click to toggle source

Returns typed default value for field

@api private @raise Ciesta::ViolatesConstraints @return [any]

# File lib/ciesta/field.rb, line 66
def default
  type[raw_default]
rescue Dry::Types::ConstraintError
  raise Ciesta::ViolatesConstraints, "#{raw_default} is not a #{type.name}"
end
raw_default() click to toggle source

Returns raw default value

@api private @return [any]

# File lib/ciesta/field.rb, line 76
def raw_default
  if @default.respond_to?(:call) && @binding
    @binding.instance_exec(&@default)
  else
    @default
  end
end