├── .gitignore ├── test ├── helper.rb └── writ_test.rb ├── .gems ├── lib ├── writ │ └── version.rb └── writ.rb ├── .travis.yml ├── writ.gemspec ├── Makefile ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | /pkg/*.gem 2 | -------------------------------------------------------------------------------- /test/helper.rb: -------------------------------------------------------------------------------- 1 | require "writ" 2 | -------------------------------------------------------------------------------- /.gems: -------------------------------------------------------------------------------- 1 | scrivener -v 1.0.0 2 | cutest -v 1.2.3 3 | -------------------------------------------------------------------------------- /lib/writ/version.rb: -------------------------------------------------------------------------------- 1 | class Writ 2 | VERSION = "1.0.0".freeze 3 | end 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | script: make 3 | rvm: 4 | - 2.3.1 5 | - 2.2 6 | - 2.1 7 | - ruby-head 8 | matrix: 9 | allow_failures: 10 | - rvm: ruby-head 11 | install: | 12 | gem install dep 13 | curl https://raw.githubusercontent.com/tonchis/gst/master/bin/gst > gst 14 | chmod +x gst 15 | ./gst init 16 | source ./gst in 17 | -------------------------------------------------------------------------------- /writ.gemspec: -------------------------------------------------------------------------------- 1 | require "./lib/writ/version" 2 | 3 | Gem::Specification.new do |s| 4 | s.name = "writ" 5 | s.licenses = ["MIT"] 6 | s.version = Writ::VERSION 7 | s.summary = "Minimal implementation of the command pattern." 8 | s.description = <<-EOS.gsub(/\s+/m, ' ').strip 9 | Tiny implementation of the command pattern, including input validation, 10 | using Scrivener. 11 | EOS 12 | s.authors = ["Nicolas Sanguinetti"] 13 | s.email = ["contacto@nicolassanguinetti.info"] 14 | s.homepage = "http://github.com/foca/writ" 15 | 16 | s.files = Dir[ 17 | "LICENSE", 18 | "README.md", 19 | "lib/writ.rb", 20 | "lib/writ/version.rb", 21 | ] 22 | 23 | s.add_dependency "scrivener", "~> 1.0" 24 | s.add_development_dependency "cutest", "~> 1.2" 25 | end 26 | 27 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | PACKAGES := writ 2 | VERSION_FILE := lib/writ/version.rb 3 | 4 | DEPS := ${GEM_HOME}/installed 5 | VERSION := $(shell sed -ne '/.*VERSION *= *"\(.*\)".*/s//\1/p' <$(VERSION_FILE)) 6 | GEMS := $(addprefix pkg/, $(addsuffix -$(VERSION).gem, $(PACKAGES))) 7 | 8 | export RUBYLIB := $(RUBYLIB):test:lib 9 | 10 | all: test $(GEMS) 11 | 12 | test: $(DEPS) 13 | cutest -r ./test/helper.rb ./test/**/*_test.rb 14 | 15 | clean: 16 | rm pkg/*.gem 17 | 18 | release: $(GEMS) 19 | for gem in $^; do gem push $$gem; done 20 | 21 | pkg/%-$(VERSION).gem: %.gemspec $(VERSION_FILE) | pkg 22 | gem build $< 23 | mv $(@F) pkg/ 24 | 25 | $(DEPS): $(GEM_HOME) .gems 26 | which dep &>/dev/null || gem install dep 27 | dep install 28 | touch $(GEM_HOME)/installed 29 | 30 | pkg: 31 | mkdir -p $@ 32 | 33 | .PHONY: all test release clean 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Nicolas Sanguinetti 2 | 3 | Permission is hereby granted, free of charge, to any person 4 | obtaining a copy of this software and associated documentation 5 | files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, 7 | copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the 9 | Software is furnished to do so, subject to the following 10 | conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /test/writ_test.rb: -------------------------------------------------------------------------------- 1 | require "ostruct" 2 | 3 | User = Class.new(OpenStruct) 4 | 5 | class LogIn < Writ 6 | attr_accessor :email 7 | attr_accessor :password 8 | 9 | def validate 10 | assert_email :email 11 | assert_equal :password, "password123" # such authentication 12 | end 13 | 14 | def run 15 | User.new(email: email) 16 | end 17 | end 18 | 19 | scope "with valid parameters" do 20 | setup do 21 | LogIn.run(email: "jane.doe@example.com", password: "password123") 22 | end 23 | 24 | test "returns a successful outcome" do |outcome| 25 | assert outcome.success? 26 | end 27 | 28 | test "uses the return value of #execute as the outcome's #value" do |outcome| 29 | assert_equal User.new(email: "jane.doe@example.com"), outcome.value 30 | end 31 | 32 | test "has an empty error hash" do |outcome| 33 | assert_equal Hash.new, outcome.errors 34 | end 35 | end 36 | 37 | scope "with invalid parameters" do 38 | setup do 39 | LogIn.run(email: "jane.doe@example.com", password: nil) 40 | end 41 | 42 | test "returns an unsuccessful outcome" do |outcome| 43 | assert !outcome.success? 44 | end 45 | 46 | test "returns a nil #value" do |outcome| 47 | assert_equal nil, outcome.value 48 | end 49 | 50 | test "returns the scrivener errors in the outcome" do |outcome| 51 | password_errors = outcome.errors[:password] 52 | assert password_errors.any? 53 | end 54 | 55 | test "exposes the original Writ to access user input" do |outcome| 56 | assert_equal "jane.doe@example.com", outcome.input.email 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /lib/writ.rb: -------------------------------------------------------------------------------- 1 | require "scrivener" 2 | 3 | class Writ < Scrivener 4 | # Public: Run the command with the provided input. Any arguments will be 5 | # forwarded to `Writ#new`. 6 | # 7 | # Returns a Writ::Outcome. 8 | def self.run(*args, &block) 9 | new(*args, &block).run! 10 | end 11 | 12 | # Internal: Runs your business logic, and assigns the return value of this 13 | # method as the Outcome's `#value`. 14 | # 15 | # Returns an Object. 16 | def run 17 | fail NotImplementedError 18 | end 19 | 20 | # Internal: Perform validations, run the business logic, and generate the 21 | # outcome to return. 22 | # 23 | # Returns a Writ::Outcome. 24 | def run! 25 | result = run if valid? 26 | Outcome.new(result, self) 27 | end 28 | 29 | class Outcome 30 | # Public: Get the return value of your Writ. 31 | attr_reader :value 32 | 33 | # Public: Get the Writ object, with the user input as accessors. 34 | attr_reader :input 35 | 36 | # Public: Get the errors Hash generated by running Writ.run. This will be an 37 | # empty Hash if no errors were returned. 38 | attr_reader :errors 39 | 40 | # Public: Initialize the outcome. 41 | # 42 | # value - The return value from Writ.run 43 | # writ - The Writ instance. 44 | def initialize(value, writ) 45 | @value = value 46 | @input = writ 47 | @errors = writ.errors 48 | end 49 | 50 | # Public: Whether the Writ performed successfully or not (i.e. no errors are 51 | # present.) 52 | # 53 | # Returns Boolean. 54 | def success? 55 | errors.empty? 56 | end 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Writ: A minimal command pattern implementation 2 | 3 | [![Build Status](https://img.shields.io/travis/foca/writ.svg)](https://travis-ci.org/foca/writ) [![RubyGem](https://img.shields.io/gem/v/writ.svg)](https://rubygems.org/gems/writ) 4 | 5 | > **writ**, _noun_:
6 | >          a form of written command in the name of a court or other legal authority to act, or abstain from acting, in some way. 7 | 8 | `Writ` is a minimal [command pattern][pattern] implementation, including input validation, built on top of [Scrivener][scrivener]. 9 | 10 | [pattern]: http://wiki.c2.com/?CommandPattern 11 | [scrivener]: https://github.com/soveran/scrivener 12 | 13 | # Example 14 | 15 | ``` ruby 16 | # Define your commands 17 | class LogIn < Writ 18 | attr_accessor :email 19 | attr_accessor :password 20 | 21 | def validate 22 | assert_email :email 23 | assert_present :password 24 | end 25 | 26 | def run 27 | user = User.authenticate(email, password) 28 | assert user, [:email, :not_valid] 29 | end 30 | end 31 | 32 | # And use them 33 | outcome = LogIn.run(req.params) 34 | 35 | if outcome.success? 36 | session[:user_id] = outcome.value.id 37 | else 38 | outcome.input.password = nil # Don't leak it when rendering the form again 39 | render "auth/sign_in", errors: outcome.errors, form: outcome.input 40 | end 41 | ``` 42 | 43 | ## Install 44 | 45 | gem install writ 46 | 47 | ## Validations 48 | 49 | As with [scrivener][], you should define a `validate` method that defines all validations for the user input. You're also welcome to use validations inside of `run`, when an error can come from the process itself. The example above, where the email/password combination yields no user, is a good example. Another example would be having to make an API call that returns an error. 50 | 51 | Take a look at the default [validations](https://github.com/soveran/scrivener#assertions) that come from scrivener, or feel free to define custom ones to suit your domain. 52 | 53 | ## Why 54 | 55 | When using [scrivener][], I tend to add a `run` method to the objects to alter state based on user input alongside the validations. Some people like calling these objects "services", "use cases", "commands", or "interactions". 56 | 57 | I find this useful to decouple complex actions from the actors involved in them, and to keep models "thin" by only caring about expressing the domain without burdening themselves with expressing how users can interact with the domain, or with concepts like validation and authorization. 58 | 59 | After using this pattern in several production projects, I figured it might as well live in a gem I can reuse instead of copy-pasting code around. 60 | 61 | ## License 62 | 63 | This project is shared under the MIT license. See the attached [LICENSE](./LICENSE) file for details. 64 | --------------------------------------------------------------------------------