Class: Trailblazer::Declarative::State

Inherits:
Object
  • Object
show all
Defined in:
lib/trailblazer/declarative/state.rb

Overview

FIXME: who is providing the immutable API?

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeState

Returns a new instance of State.



19
20
21
22
# File 'lib/trailblazer/declarative/state.rb', line 19

def initialize
  @fields        = {}
  @field_options = {}
end

Class Method Details

.dup(value) ⇒ Object

DISCUSS: should that be here?



11
12
13
# File 'lib/trailblazer/declarative/state.rb', line 11

def self.dup(value, **) # DISCUSS: should that be here?
  value.dup
end

.subclass(value) ⇒ Object



15
16
17
# File 'lib/trailblazer/declarative/state.rb', line 15

def self.subclass(value, **)
  Class.new(value)
end

Instance Method Details

#add!(path, value, copy: State.method(:dup)) ⇒ Object



24
25
26
27
28
# File 'lib/trailblazer/declarative/state.rb', line 24

def add!(path, value, copy: State.method(:dup))
  @fields[path]        = value
  @field_options[path] = {copy: copy}
  self
end

#copy(**options) ⇒ Object

DISCUSS: do we need it?



58
59
60
61
62
# File 'lib/trailblazer/declarative/state.rb', line 58

def copy(**options) # DISCUSS: make class method?
  inherited_fields = copy_fields(**options)

  Declarative.State(inherited_fields)
end

#copy_fields(**options) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/trailblazer/declarative/state.rb', line 48

def copy_fields(**options)
  @fields.collect do |path, value|
    path_options = @field_options.fetch(path)
    inherited_value = path_options.fetch(:copy).(value, **options)

    [path, [inherited_value, path_options]]
  end.to_h
end

#get(path) ⇒ Object



39
40
41
# File 'lib/trailblazer/declarative/state.rb', line 39

def get(path)
  @fields.fetch(path)
end

#set!(path, value) ⇒ Object



44
45
46
# File 'lib/trailblazer/declarative/state.rb', line 44

def set!(path, value)
  @fields[path] = value
end

#update!(path, &block) ⇒ Object

Tries to retrieve path, if it exists block is called and receives the old value. The return value of the block will be the new value.



33
34
35
36
37
# File 'lib/trailblazer/declarative/state.rb', line 33

def update!(path, &block)
  value = get(path)
  new_value = yield(value, **{})
  set!(path, new_value)
end