-
-
Save EdwardDiehl/3f348f2391e684aea88df9266f293d46 to your computer and use it in GitHub Desktop.
Redux in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Redux in Ruby | |
class Store | |
attr_reader :state | |
def initialize(initial_state, *reducers) | |
@reducers = reducers | |
@state = initial_state || {} | |
end | |
def dispatch(action) | |
@state = @reducers.reduce(state.dup) do |s, reducer| | |
reducer.call(s, action) | |
end | |
end | |
end | |
# Reducers | |
totals_reducer = ->(state, action) do | |
case action[:type] | |
when 'ADD_ITEM' then state[:total] += 1 | |
when 'REMOVE_ITEM' then state[:total] -= 1 | |
end | |
state | |
end | |
items_reducer = -> (state, action) do | |
case action[:type] | |
when 'ADD_ITEM' then state[:items] << action[:item] | |
when 'REMOVE_ITEM' then state[:items] = state[:items] - [action[:item]] | |
end | |
state | |
end | |
# DEMO | |
@store = Store.new({ total: 0, items: [] }, items_reducer, totals_reducer) | |
@store.dispatch type: 'ADD_ITEM', item: 'APPLES' | |
@store.dispatch type: 'ADD_ITEM', item: 'BANANAS' | |
@store.dispatch type: 'REMOVE_ITEM', item: 'APPLES' | |
@store.dispatch type: 'ADD_ITEM', item: 'FEIJOAS' | |
puts @store.state # => {total: 2, items: ["BANANAS", "FEIJOAS"]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment