Skip to content

Instantly share code, notes, and snippets.

@seanlilmateus
Forked from eadz/ruby-redux.rb
Created July 21, 2022 20:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanlilmateus/ddf8dbafd186f7a3a33aa49008fcb25f to your computer and use it in GitHub Desktop.
Save seanlilmateus/ddf8dbafd186f7a3a33aa49008fcb25f to your computer and use it in GitHub Desktop.
Redux in Ruby
# 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