Codementor Events

Rydux - A Redux store for your ruby application

Published Jun 27, 2018

Hey all, just wanted to write this post to let you know about a small ruby gem I've created, Rydux. This gem allows you to decouple the state from your logic in your application, and implements a more functional paradigm to ruby programming. You can check it out here.

To use the gem, require it somewhere in the root of your application (or somewhere the store will be accessible everywhere you need it). Next, create some reducers in your application, you can place them anywhere, but a reducers/ directory is recommended. A sample reducer looks something like this:

# reducers/user_reducer.rb

class UserReducer < Rydux::Reducer

  # Your reducer MUST have a map_state function in order to do anything.
  def self.map_state(action, state = {})
    case action[:type]
    when 'SOME_RANDOM_ACTION' # You can add as many actions here as you'd like
      state.merge(some_random_data: true)
    when 'APPEND_PAYLOAD'
      state.merge(action[:payload])
    else
      state
    end
  end

end

Create a store somewhere easily accessible in your application:

  require 'reducers/user_reducer'

  # The key passed into .new here is the key at which this value
  # will be stored in the state. E.g. { user: whatever_user_state }
  Store = Rydux::Store.new(user: UserReducer)

Have something subscribe to the store:

  class MyClass
    def initialize
      Store.subscribe(self)
    end

    # Every instance that subscribes to the store will
    # get this state_changed method called whenever the state
    # in the store changes. Do whatever you want with your state here.
    def state_changed(state)
      # ...
    end
  end

To update the store with new data, you can dispatch actions, like so:

  Store.dispatch(type: 'SOME_RANDOM_ACTION')

Putting it all together:

require 'rydux'

class UserReducer < Rydux::Reducer
  @@initial_state = { name: 'Alex', age: 20 }

  def self.map_state(action, state = @@initial_state)
    case action[:type]
    when 'CHANGE_USER_NAME'
      state.merge(name: action[:payload][:name])
    else
      state
    end
  end

end

Store = Rydux::Store.new(user: UserReducer)

class Friend
  def initialize
    Store.subscribe(self)
    @users_name = Store.state.user.name
  end

  def state_changed(state)
    @users_name = state.user.name
  end

  def greet_user
    puts "Hello, #{@users_name}"
  end
end

# Create a new friend (this will subscribe it to the store)
friend = Friend.new
friend.greet_user #=> Hello, Alex

# Change a value in the store
Store.dispatch(type: 'CHANGE_USER_NAME', payload: { name: 'Mike' })
friend.greet_user #=> Hello, Mike
Discover and read more posts from Alex Dovzhanyn
get started