class Rubidux::Store

Constants

INITIALIZE

Attributes

dispatch[RW]
listeners[RW]
reducer[RW]
state[RW]
subscribe[RW]

Public Class Methods

new(reducer:, preloaded_state: {}, enhancer: nil) click to toggle source
# File lib/rubidux/store.rb, line 11
def initialize(reducer:, preloaded_state: {}, enhancer: nil)
  raise ArgumentError.new("Expect preloaded state to be a Hash.") unless preloaded_state.is_a? Hash
  raise ArgumentError.new("Expect reducer to be a Proc.") unless reducer.is_a? Proc
  raise ArgumentError.new("Expect enhancer to be a Proc.") unless (!enhancer || enhancer.is_a?(Proc))

  @state = {}
  @reducer = reducer
  @listeners = []
  @subscribe = _subscribe

  @dispatch = enhancer ? enhancer.(-> { @state }, _dispatch) : _dispatch
  @dispatch.({ type: INITIALIZE })

  @state = @state.merge preloaded_state
end

Private Instance Methods

_dispatch() click to toggle source
# File lib/rubidux/store.rb, line 34
def _dispatch
  -> action {
    raise ArgumentError.new("Expect action to have key 'type'.") unless action[:type]
    @state = @reducer.(@state, action)
    @listeners.each(&:call)
    action
  }
end
_subscribe() click to toggle source
# File lib/rubidux/store.rb, line 43
def _subscribe
  -> listener {
    raise ArgumentError.new("Expect listener to be a Proc.") unless listener.is_a? Proc
    @listeners.push listener
    -> { @listeners.delete listener }
  }
end