2017-07-27 20:33:32 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Obredux
|
2017-07-27 23:51:44 -04:00
|
|
|
UNDEFINED = {}.freeze
|
2017-07-27 21:47:18 -04:00
|
|
|
|
2017-07-27 20:33:32 -04:00
|
|
|
class Action; end
|
2017-07-27 21:47:18 -04:00
|
|
|
|
|
|
|
class Init < Action; end
|
|
|
|
|
|
|
|
class Store
|
2017-07-27 22:27:42 -04:00
|
|
|
attr_reader :reducer_klass, :state
|
2017-07-27 21:47:18 -04:00
|
|
|
|
2017-07-27 22:27:42 -04:00
|
|
|
def initialize(reducer_klass)
|
|
|
|
@reducer_klass = reducer_klass
|
|
|
|
@state = UNDEFINED
|
|
|
|
dispatch Init.new
|
2017-07-27 21:47:18 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def dispatch(action)
|
2017-07-27 22:27:42 -04:00
|
|
|
@state = reducer_klass.new(state, action).call
|
2017-07-27 21:47:18 -04:00
|
|
|
end
|
|
|
|
end
|
2017-07-27 22:34:58 -04:00
|
|
|
|
|
|
|
class Reducer
|
2017-07-27 23:51:44 -04:00
|
|
|
def self.combine(options = nil)
|
|
|
|
@combine ||= {}
|
|
|
|
|
|
|
|
return @combine if options.nil?
|
|
|
|
|
|
|
|
options.each do |key, reducer_klass|
|
|
|
|
@combine[key] = reducer_klass
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-07-27 22:34:58 -04:00
|
|
|
def initialize(state, action)
|
|
|
|
@state = state
|
|
|
|
@action = action
|
|
|
|
end
|
|
|
|
|
|
|
|
def call
|
2017-07-27 23:51:44 -04:00
|
|
|
init = state.equal? UNDEFINED
|
|
|
|
|
2017-07-27 23:42:52 -04:00
|
|
|
@state ||= {}.freeze
|
2017-07-27 23:51:44 -04:00
|
|
|
|
|
|
|
unless self.class.combine.empty?
|
|
|
|
@state = state.merge(
|
|
|
|
self.class.combine.map do |key, reducer_klass|
|
|
|
|
[
|
|
|
|
key,
|
|
|
|
reducer_klass.new(state[key], action).call,
|
|
|
|
]
|
|
|
|
end.to_h.freeze,
|
|
|
|
).freeze
|
|
|
|
end
|
|
|
|
|
|
|
|
@state = state.merge initial_state if init
|
|
|
|
|
2017-07-27 22:34:58 -04:00
|
|
|
reduce
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
attr_reader :state, :action
|
|
|
|
|
|
|
|
def initial_state
|
2017-07-27 23:44:24 -04:00
|
|
|
{}.freeze
|
2017-07-27 22:34:58 -04:00
|
|
|
end
|
2017-07-27 23:42:52 -04:00
|
|
|
|
|
|
|
def reduce
|
2017-07-27 23:44:24 -04:00
|
|
|
state
|
2017-07-27 23:42:52 -04:00
|
|
|
end
|
2017-07-27 22:34:58 -04:00
|
|
|
end
|
2017-07-27 20:33:32 -04:00
|
|
|
end
|