• Stars
    star
    617
  • Rank 69,927 (Top 2 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple, standardized way to build and use Service Objects (aka Commands) in Ruby

Code Climate CI

SimpleCommand

A simple, standardized way to build and use Service Objects (aka Commands) in Ruby

Requirements

  • Ruby 2.6+

Installation

Add this line to your application's Gemfile:

gem 'simple_command'

And then execute:

$ bundle

Or install it yourself as:

$ gem install simple_command

Usage

Here's a basic example of a command that authenticates a user

# define a command class
class AuthenticateUser
  # put SimpleCommand before the class' ancestors chain
  prepend SimpleCommand
  include ActiveModel::Validations

  # optional, initialize the command with some arguments
  def initialize(email, password)
    @email = email
    @password = password
  end

  # mandatory: define a #call method. its return value will be available
  #            through #result
  def call
    if user = User.find_by(email: @email)&.authenticate(@password)
      return user
    else
      errors.add(:base, :failure)
    end
    nil
  end
end

in your locale file

# config/locales/en.yml
en:
  activemodel:
    errors:
      models:
        authenticate_user:
          failure: Wrong email or password

Then, in your controller:

class SessionsController < ApplicationController
  def create
    # initialize and execute the command
    # NOTE: `.call` is a shortcut for `.new(args).call`
    command = AuthenticateUser.call(session_params[:email], session_params[:password])

    # check command outcome
    if command.success?
      # command#result will contain the user instance, if found
      session[:user_token] = command.result.secret_token
      redirect_to root_path
    else
      flash.now[:alert] = t(command.errors.full_messages.to_sentence)
      render :new
    end
  end

  private

  def session_params
    params.require(:session).permit(:email, :password)
  end
end

Test with Rspec

Make the spec file spec/commands/authenticate_user_spec.rb like:

describe AuthenticateUser do
  subject(:context) { described_class.call(username, password) }

  describe '.call' do
    context 'when the context is successful' do
      let(:username) { 'correct_user' }
      let(:password) { 'correct_password' }
      
      it 'succeeds' do
        expect(context).to be_success
      end
    end

    context 'when the context is not successful' do
      let(:username) { 'wrong_user' }
      let(:password) { 'wrong_password' }

      it 'fails' do
        expect(context).to be_failure
      end
    end
  end
end

Contributing

  1. Fork it ( https://github.com/nebulab/simple_command/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

More Repositories

1

pulsar

Manage your Capistrano deployments with ease
Ruby
129
star
2

erb-formatter

Format ERB files with speed and precision
Ruby
115
star
3

cangaroo

Connect Any App to Any Service
Ruby
107
star
4

spree-subscriptions

Spree extension to handle subscriptions
Ruby
86
star
5

reverse_coverage

A tool to find the test examples which cover a specific line (or set of lines) of a Ruby project
JavaScript
74
star
6

omnes

Pub/Sub for Ruby
Ruby
55
star
7

playbook

πŸ“– We are Nebulab, and this is how we work.
SCSS
53
star
8

prependers

Easily and cleanly extend third-party code.
Ruby
27
star
9

runtime_config

A runtime configuration tool for Rails 5
Ruby
24
star
10

spree-one-page-checkout

Source code for One Page Checkout blog post
Ruby
24
star
11

rails_console_toolkit

Configurable Rails Console Helpers
Ruby
20
star
12

umarell

All in one Ruby static code analyzer
Ruby
18
star
13

spree-ember-example

The example repository that goes with http://nebulab.it/blog/using-ember-js-with-spree/
Ruby
17
star
14

multitenant_shop

Solidus eCommerce with multitenancy
Ruby
11
star
15

spree-garbage-cleaner

A little gem that helps you cleanup old, unneeded data from a Spree database.
Ruby
11
star
16

rails-vuejs-jsx

Products catalog Rails application moved to VueJS and JSX
Ruby
8
star
17

indago

Lightweight drop-in Ransack replacement without the ActiveRecord hackery.
Ruby
7
star
18

spree_return_authorizations_frontend

Adds a frontend interface to allow user to ask for items returns
Ruby
7
star
19

dev_tools

Contains useful gems to be used in development
Ruby
7
star
20

erb-formatter-vscode

VSCode extension for ERB::Formatter (Format ERB files with speed and precision)
JavaScript
7
star
21

spree_simple_reports

JavaScript
6
star
22

dru

DRU - Docker-Compose Run Utility
Ruby
6
star
23

moonshine

Moonshine is a configuration driven method chain builder.
Ruby
5
star
24

cypress-store

An example of integrating Cypress with Rails.
Ruby
5
star
25

spree_ember_one_page_checkout

An ember.js application to add a one page checkout to Spree.
CoffeeScript
5
star
26

erb-linter

Check your ERB files for closing tags, indentation, bad attributes etc.
Ruby
5
star
27

spree_order_constraints

A simple way to change the behaviour of checkout_allowed? to add some constraints to your customers as they proceed to checkout
Ruby
5
star
28

spree_exclusive_products

It filters variants depending on user roles
Ruby
5
star
29

solidus_shipwire

solidus and shipwire connect manager
Ruby
5
star
30

solidus_client

Solidus eCommerce API Ruby client
Ruby
4
star
31

solidus_page_objects

An extension that adds site_prism page objects for common Solidus views
Ruby
4
star
32

spree_one_page_add_to_cart

Spree one page add to cart for fast checkout
Ruby
4
star
33

soliton

An Ember application to search for Solidus extensions on GitHub
JavaScript
4
star
34

solidus_nextjs_frontend

JavaScript
4
star
35

baywatch

Rescue projects before they sink: easy 1-container feature branch previews with Docker
Dockerfile
4
star
36

renderful

A Ruby rendering engine for headless CMSs, with support for caching and Ruby on Rails.
Ruby
4
star
37

spree-api-client.js

JavaScript
4
star
38

wombat_migration

Useful to share info about how to migrate wombat
3
star
39

bretelline

Nebulab's Rails (and Solidus) application template.
Ruby
3
star
40

create-hydrogen

JavaScript
2
star
41

workflow

A repo useful to simulate a basic features management workflow
2
star
42

nebulab.github.io

The Nebulab website
HTML
2
star
43

spree_line_item_discount

Adds the ability to create a different discount in percentage for each item in the cart with the same coupon code
Ruby
2
star
44

spree_multiple_notifications

Ruby
2
star
45

klarna_proxy

Ruby Klarna proxy gem that consumes the Klarna APIs: https://developers.klarna.com/api/
Ruby
2
star
46

easy_maintenance

Easy maintenance page for your apps
Ruby
2
star
47

rails-sales-taxes-kata

One of the exercises used in our internal academy.
2
star
48

solidus_bot

A simple chatbot which search products on a solidus store
Ruby
1
star
49

spree_social_promotions

Ruby
1
star
50

helen

Helen - Office Automation
1
star
51

heroku-ruby-docker

A docker image to mimic Heroku Ruby environment
Dockerfile
1
star
52

products_feed

Easy products feed generator
Ruby
1
star
53

solidus_product_uploads

Ruby
1
star
54

docker-preview-server

Chef cookbooks to spin up a docker preview server.
Ruby
1
star
55

circleci-orbs-stoplight

πŸ“œ An Orb for linking your Git repository to a Stoplight project.
1
star
56

solidus_frontend_examples

Example custom frontend applications built on Solidus's GraphQL API
JavaScript
1
star
57

spree_allow_shipping_methods

Ruby
1
star
58

html5-boilerplate-stasis

JavaScript
1
star
59

backport

Manage your backported code with ease.
Ruby
1
star
60

segmentation

The missing SDK for integrating Segment in your Ruby on Rails application.
Ruby
1
star
61

pulsar-conf-demo

Example of pulsar-conf repository
Ruby
1
star
62

spree-invite-a-friend-example

Ruby
1
star
63

circleci-orbs-feature-branch-preview

πŸ‘“ An Orb to preview PRs on a specific server using Docker
1
star
64

solidus-on-heroku

Deploy your solidus app on heroku like a boss
Ruby
1
star
65

cangaroo_tutorial

Example application on how to setup Cangaroo to tweet every time a new product is created
Ruby
1
star
66

darkstore

Darkstore API gem
Ruby
1
star
67

products_catalog

Simple app Rails APIs with VueJS JSX for the Ruby day Workshop
Ruby
1
star
68

aws-solidus-demo-opsworks_cookbook

Chef 13 cookbook with Opsworks and NodeJS for AWS Rails deployment
Ruby
1
star