Class: Inquirex::Accumulator

Inherits:
Object
  • Object
show all
Defined in:
lib/inquirex/accumulator.rb

Overview

Declares a named running total (e.g. :price, :complexity, :credit_score) that flows accumulate into as the user answers questions. Pure data, serializable to JSON, evaluated identically on Ruby and JS sides.

Examples:

Declare a running price total and contribute to it from a step

Inquirex.define do
  accumulator :price, type: :currency, default: 0
  ask :dependents do
    type :integer
    accumulate :price, per_unit: 50
  end
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, type: :decimal, default: 0) ⇒ Accumulator

Returns a new instance of Accumulator.

Parameters:

  • name (Symbol, String)

    accumulator identifier

  • type (Symbol, String) (defaults to: :decimal)

    value type, one of Node::TYPES

  • default (Numeric) (defaults to: 0)

    starting value before any contributions



26
27
28
29
30
31
# File 'lib/inquirex/accumulator.rb', line 26

def initialize(name:, type: :decimal, default: 0)
  @name = name.to_sym
  @type = type.to_sym
  @default = default
  freeze
end

Instance Attribute Details

#defaultNumeric (readonly)

starting value (default: 0)

Returns:

  • (Numeric)

    the current value of default



20
21
22
# File 'lib/inquirex/accumulator.rb', line 20

def default
  @default
end

#nameSymbol (readonly)

accumulator identifier (e.g. :price)

Returns:

  • (Symbol)

    the current value of name



20
21
22
# File 'lib/inquirex/accumulator.rb', line 20

def name
  @name
end

#typeSymbol (readonly)

one of Node::TYPES (typically :currency, :integer, :decimal)

Returns:

  • (Symbol)

    the current value of type



20
21
22
# File 'lib/inquirex/accumulator.rb', line 20

def type
  @type
end

Class Method Details

.from_h(name, hash) ⇒ Accumulator

Deserializes an Accumulator from its wire format.

Parameters:

  • name (Symbol, String)

    accumulator identifier (the map key)

  • hash (Hash)

    type/default attributes (string or symbol keys)

Returns:



46
47
48
49
50
51
52
# File 'lib/inquirex/accumulator.rb', line 46

def self.from_h(name, hash)
  new(
    name:    name,
    type:    hash["type"] || hash[:type] || :decimal,
    default: hash["default"] || hash[:default] || 0
  )
end

Instance Method Details

#to_hHash{String => Object}

Serializes the accumulator to its wire format. The name is omitted — Definition#to_h keys the accumulators map by name.

Returns:

  • (Hash{String => Object})

    e.g. { "type" => "currency", "default" => 0 }



37
38
39
# File 'lib/inquirex/accumulator.rb', line 37

def to_h
  { "type" => @type.to_s, "default" => @default }
end