项目作者: foca

项目描述 :
Minimal command pattern implementation on top of Scrivener
高级语言: Ruby
项目地址: git://github.com/foca/writ.git
创建时间: 2016-12-21T20:15:26Z
项目社区:https://github.com/foca/writ

开源协议:MIT License

下载


Writ: A minimal command pattern implementation

Build Status RubyGem

writ, noun:

a form of written command in the name of a court or other legal authority to act, or abstain from acting, in some way.

Writ is a minimal command pattern implementation, including input validation, built on top of Scrivener.

Example

  1. # Define your commands
  2. class LogIn < Writ
  3. attr_accessor :email
  4. attr_accessor :password
  5. def validate
  6. assert_email :email
  7. assert_present :password
  8. end
  9. def run
  10. user = User.authenticate(email, password)
  11. assert user, [:email, :not_valid]
  12. end
  13. end
  14. # And use them
  15. outcome = LogIn.run(req.params)
  16. if outcome.success?
  17. session[:user_id] = outcome.value.id
  18. else
  19. outcome.input.password = nil # Don't leak it when rendering the form again
  20. render "auth/sign_in", errors: outcome.errors, form: outcome.input
  21. end

Install

  1. gem install writ

Validations

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.

Take a look at the default validations that come from scrivener, or feel free to define custom ones to suit your domain.

Why

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”.

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.

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.

License

This project is shared under the MIT license. See the attached LICENSE file for details.