Skip to content

Commit

Permalink
an initial attempt at symbolic error docs in the README
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronLasseigne committed Sep 3, 2014
1 parent 828795f commit 351e444
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions README.md
Expand Up @@ -41,6 +41,7 @@ on RubyDoc.info.
- [Time](#time)
- [Advanced Usage](#advanced-usage)
- [Composition](#composition)
- [Symbolic Errors](#symbolic-errors)
- [Translation](#translation)
- [Credits](#credits)

Expand Down Expand Up @@ -722,6 +723,62 @@ class AddAndDouble < ActiveInteraction::Base
end
```

### Symbolic Errors

ActiveInteraction provides symbolic errors for easier introspection and testing
of errors. Symbolic errors improve on regular errors by adding a symbol that
represents the type of error that has occurred. Let's look at an example where
an item is purchased using a credit card.

```ruby
class BuyItem < ActiveInteraction::Base
model :credit_card, :item
hash :options do
boolean :gift_wrapped
end

def execute
order = credit_card.purchase(item)

notify(credit_card.account)

order
end

def notify(account)
# ...
end
end
```

Having missing or invalid inputs causes the interaction to fail and return
errors.

```ruby
> outcome = BuyItem.run({item: 'Thing', options: {gift_wrapped: 'yes'}})
> outcome.errors.messages
# => {:credit_card=>["is required"], :item=>["is not a valid model"], :options=>["has an invalid nested value (\"gift_wrapped\" => \"yes\")"]}
```

Determining the type of error based on the string is difficult if not
impossible. Calling `symbolic` instead of `messages` on `errors` gives
you the same list of errors with a testable label representing the error.

```ruby
> outcome.errors.symbolic
# => {"credit_card"=>[:missing], "item"=>[:invalid_type], "options"=>[:invalid_nested]}
```

Symbolic errors can also be manually added during the `execute` call by
calling `add_sym` instead of `add` on `errors`. It works the same way as
`add` except that the second argument is the error label.

```ruby
def execute
errors.add_sym(:monster, :no_passage, 'You shall not pass!')
end
```

### Translation

ActiveInteraction is i18n aware out of the box! All you have to do is add
Expand Down

0 comments on commit 351e444

Please sign in to comment.