Skip to content

Commit

Permalink
feat: extract and move implementation to the gem
Browse files Browse the repository at this point in the history
  • Loading branch information
bibendi committed Oct 28, 2021
0 parents commit d3c290f
Show file tree
Hide file tree
Showing 29 changed files with 964 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Ruby version
2. Rails version
3. Run command
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Context (please complete the following information):**
- OS: [e.g. Ubuntu 18.04.3]
- Version [e.g. binary 4.3.2]

**Additional context**
Add any other context about the problem here.
24 changes: 24 additions & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Context

<!--
Short description about the feature and the motivation/issue behind it
-->

## Related tickets



# What's inside

<!--
List of features and changes (or highlights) (from the code perspective)
The purpose of this list is to track the progress if it's WIP (use checkboxes)
and to emphasize the critical parts (which you'd like to pay reviewers attention to)
-->
- [x] A
- [ ] B

# Checklist:

- [ ] I have added tests
- [ ] I have made corresponding changes to the documentation
30 changes: 30 additions & 0 deletions .github/workflows/ruby.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: Ruby

on:
push:
branches: [ master ]
pull_request:
branches: [ '**' ]

jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
ruby: [ '2.6', '2.7', '3.0' ]
env:
RUBY_IMAGE: ${{ matrix.ruby }}
name: Ruby ${{ matrix.ruby }}
steps:
- uses: actions/checkout@v2
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 2.7
- name: Install dependencies
run: |
gem install dip
dip provision
- name: Run tests
run: dip appraisal rspec
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/gemfiles/
/pkg/
/spec/reports/
/tmp/
.pry_history
.rspec_status
Gemfile.lock
lefthook-local.yml
3 changes: 3 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--format progress
--color
--require spec_helper
1 change: 1 addition & 0 deletions .standard.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ruby_version: 2.6
17 changes: 17 additions & 0 deletions Appraisals
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# frozen_string_literal: true

if RUBY_VERSION < "3"
appraise "rails-5" do
gem "rails", "~> 5.0"
end
end

appraise "rails-6" do
gem "rails", "~> 6.0"
end

if RUBY_VERSION >= "2.7"
appraise "rails-7" do
gem "rails", "~> 7.0.0.alpha2"
end
end
5 changes: 5 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# frozen_string_literal: true

source "https://rubygems.org"

gemspec
21 changes: 21 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2018 Michael Merkushin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
122 changes: 122 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
[![Gem Version](https://badge.fury.io/rb/downstream.svg)](https://badge.fury.io/rb/downstream)
[![Build Status](https://github.com/bibendi/downstream/workflows/Ruby/badge.svg?branch=master)](https://github.com/bibendi/downstream/actions?query=branch%3Amaster)

# Downstream

This gem provides a straightforward way to implement communication between Rails Engines using the Publish-Subscribe pattern. The gem allows decreasing decoupling engines with events. An event is a recorded object in the system that reflects an action that the engine performs, and the params that lead to its creation.

The gem inspired by [`active_event_store`](https://github.com/palkan/active_event_store), and initially based on its codebase. Having said that, it does not store in a database all happened events which ensures simplicity and performance.

<a href="https://evilmartians.com/?utm_source=bibendi-downstream">
<img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg" alt="Sponsored by Evil Martians" width="236" height="54"></a>

## Installation

Add this line to your application's Gemfile:

```ruby
gem "downstream", "~> 1.0"
```

## Usage

Under the hood it's a wrapper for `ActiveSupport::Notifications`. But it provides a way more handy interface to build reactive apps. Each event has a strict schema described by a separate class. Also, the gem has convenient tooling to write tests.

### Describe events

Events are represented by _event classes_, which describe events payloads and identifiers:

```ruby
class ProfileCreated < Downstream::Event
# (optional)
# Event identifier is used for streaming events to subscribers.
# By default, identifier is equal to underscored class name.
# You don't need to specify identifier manually, only for backward compatibility when
# class name is changed.
self.identifier = "profile_created"

# Add attributes accessors
attributes :user
end
```

Each event has predefined (_reserved_) fields:
- `event_id` – unique event id
- `type` – event type (=identifier)

**NOTE:** events should be in the past tense and describe what happened (e.g. "ProfileCreated", "EventPublished", etc.).

Events are stored in `app/events` folder.

### Publish events

To publish an event you must first create an instance of the event class and call `Downstream.publish` method:

```ruby
event = ProfileCompleted.new(user: user)

# then publish the event
Downstream.publish(event)
```

That's it! Your event has been stored and propagated.

### Subscribe to events

To subscribe a handler to an event you must use `Downstream.subscribe` method.

You should do this in your app or engine initializer:

```ruby
# some/engine.rb

initializer "my_engine.subscribe_to_events" do
# To make sure event store is initialized use load hook
# `store` == `Downstream`
ActiveSupport.on_load "downstream-events" do |store|
store.subscribe MyEventHandler, to: ProfileCreated

# anonymous handler (could only be synchronous)
store.subscribe(to: ProfileCreated) do |name, event|
# do something
end

# you can omit event if your subscriber follows the convention
# for example, the following subscriber would subscribe to
# ProfileCreated event
store.subscribe OnProfileCreated::DoThat
end
end
```

**NOTE:** event handler **must** be a callable object.

Although subscriber could be any callable Ruby object, that have specific input format (event); thus we suggest putting subscribers under `app/subscribers/on_<event_type>/<subscriber.rb>`, e.g. `app/subscribers/on_profile_created/create_chat_user.rb`).

## Testing

You can test subscribers as normal Ruby objects.

To test that a given subscriber exists, you can do the following:

```ruby
it "is subscribed to some event" do
allow(MySubscriberService).to receive(:call)

event = MyEvent.new(some: "data")

Downstream.publish event

expect(MySubscriberService).to have_received(:call).with(event)
end
```

To test publishing use `have_published_event` matcher:

```ruby
expect { subject }.to have_published_event(ProfileCreated).with(user: user)
```

**NOTE:** `have_published_event` only supports block expectations.

**NOTE 2** `with` modifier works like `have_attributes` matcher (not `contain_exactly`);
11 changes: 11 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# frozen_string_literal: true

require "bundler/setup"
require "downstream"
require_relative "spec/rails_helper"

begin
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec)
rescue LoadError
end
11 changes: 11 additions & 0 deletions bin/rails
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

require "bundler/setup"

ENGINE_ROOT = File.expand_path("..", __dir__)
ENGINE_PATH = File.expand_path("../lib/downstream/engine", __dir__)

require_relative "../spec/rails_helper"

require "rails/engine/commands"
43 changes: 43 additions & 0 deletions dip.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
version: '7'

compose:
files:
- docker-compose.yml

interaction:
shell:
description: Open the Bash shell in app's container
service: ruby
command: /bin/bash

bundle:
description: Run Bundler commands
service: ruby
command: bundle

rails:
description: Open Rails console
service: ruby
command: ./bin/rails

appraisal:
description: Run Appraisal commands
service: ruby
command: bundle exec appraisal

rspec:
description: Run Rspec commands
service: ruby
command: bundle exec rspec

standardrb:
description: Run Standard linter
service: ruby
command: bundle exec standardrb

provision:
- cp -f lefthook-local.dip_example.yml lefthook-local.yml
- dip compose down --volumes
- rm -f Gemfile.lock gemfiles/*
- dip bundle install
- dip appraisal install
16 changes: 16 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
services:
ruby:
image: ruby:${RUBY_IMAGE:-3.0}-buster
environment:
- HISTFILE=/app/tmp/.bash_history
- BUNDLE_PATH=/bundle
command: bash
working_dir: /app
volumes:
- .:/app:cached
- bundler_data:/bundle
tmpfs:
- /tmp

volumes:
bundler_data:
Loading

0 comments on commit d3c290f

Please sign in to comment.