Module: Serviced::Typed

Extended by:
ActiveSupport::Concern
Includes:
ActiveModel::API, ActiveModel::Attributes
Included in:
Query, Service
Defined in:
lib/serviced/typed.rb

Overview

Shared foundation for typed, immutable, validatable inputs. Included by both Service and Query, and usable on its own for any plain value object that wants the same contract.

class DateRange
include Serviced::Typed
attribute :from, :date
attribute :to,   :date
validates :from, :to, presence: true
end

Attributes are declared with the ActiveModel::Attributes DSL, so they are coerced to the declared type. Their writers are made private, so an instance cannot be rebound once built. Unknown keys are ignored, which lets these objects be fed from a wider hash (for example a Flow context) without raising.

Inputs are isolated by default: at construction each value is captured as an immutable snapshot (see snapshot). Arrays, hashes, sets and strings are deep-copied and deep-frozen, so neither side can mutate the other. Objects with identity (ActiveRecord records and the like) are shared by reference and left alone, because a deep copy of a record is a different, non-persisted object. Pass isolate: false to share a value by reference, for example a mutable accumulator you deliberately want the caller to see:

attribute :filters             # isolated snapshot (default)
attribute :sink, isolate: false # shared by reference

Instance Method Summary collapse

Instance Method Details

#initialize(attributes = {}) ⇒ Object

Parameters:

  • attributes (Hash) (defaults to: {})

    input values; unknown keys are ignored



41
42
43
44
45
# File 'lib/serviced/typed.rb', line 41

def initialize(attributes = {})
  super()
  assign_typed_attributes(attributes)
  capture_isolated_snapshots
end