Class: Mayu::State::Store

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/mayu/state/store.rb

Constant Summary collapse

State =
T.type_alias { T.untyped }
Reducer =
T.type_alias do
  T.proc.params(arg0: State, arg1: ActionWrapper).returns(State)
end
Thunk =
T.type_alias { T.proc.params(arg0: Store).void }
Reducers =
T.type_alias { T::Hash[Symbol, Store::Reducer] }
ActionHash =
T.type_alias { T::Hash[Symbol, T.untyped] }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_state, reducers:) ⇒ Store

Returns a new instance of Store.



35
36
37
38
39
40
41
# File 'lib/mayu/state/store.rb', line 35

def initialize(initial_state, reducers:)
  @state = T.let(initial_state, State)
  @reducer = T.let(combine_reducers(reducers), Reducer)
  @semaphore = T.let(Async::Semaphore.new, Async::Semaphore)

  dispatch({ type: :__INIT__, payload: nil })
end

Instance Attribute Details

#stateObject (readonly)

Returns the value of attribute state.



32
33
34
# File 'lib/mayu/state/store.rb', line 32

def state
  @state
end

Instance Method Details

#dispatch(action, *args, **kwargs) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/mayu/state/store.rb', line 52

def dispatch(action, *args, **kwargs)
  if action.is_a?(ActionCreator::Base)
    return dispatch(T.unsafe(action).call(*args, **kwargs))
  end

  return action.call(self) if action.is_a?(Proc)

  @semaphore.async do
    new_state =
      @reducer.call(@state.dup, T.unsafe(ActionWrapper).new(**action))
    @state = new_state
  rescue => e
    Console.logger.error(self) { "Reducer crashed" }
  end

  nil
end

#marshal_dumpObject



14
15
16
# File 'lib/mayu/state/store.rb', line 14

def marshal_dump
  [@state]
end

#marshal_load(a) ⇒ Object



19
20
21
# File 'lib/mayu/state/store.rb', line 19

def marshal_load(a)
  @state = a.first
end