Skip to content

Commit

Permalink
Guides article for custom validations and I18n (hanami#418)
Browse files Browse the repository at this point in the history
  • Loading branch information
jodosha authored Nov 27, 2017
1 parent 62eb6a4 commit 493d716
Showing 1 changed file with 50 additions and 2 deletions.
52 changes: 50 additions & 2 deletions source/guides/1.1/validations/custom-predicates.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ We have seen that built-in predicates as an expressive tool to get our job done

But what if our case is not common? We can define our own custom predicates.

#### Inline Custom Predicates
### Inline Custom Predicates

If we are facing a really unique validation that don't need to be reused across our code, we can opt for an inline custom predicate:

Expand All @@ -29,7 +29,7 @@ class Signup
end
```

#### Global Custom Predicates
### Global Custom Predicates

If our goal is to share common used custom predicates, we can include them in a module to use in all our validators:

Expand Down Expand Up @@ -62,3 +62,51 @@ class Signup
end
end
```

### Internationalization (I18n)

```ruby
require 'hanami/validations'

module MyPredicates
include Hanami::Validations::Predicates

self.messages_path = 'config/errors.yml'

predicate(:uuid?) do |input|
!/[0-9a-f]{8}-
[0-9a-f]{4}-
[0-9a-f]{4}-
[0-9a-f]{4}-
[0-9a-f]{12}/x.match(input).nil?
end
end
```

```ruby
require 'hanami/validations'
require_relative 'my_predicates'

module Web::Controllers::Signup
class Params < Hanami::Action::Params
predicates MyPredicates

validations do
required(:id).filled(:uuid?)
end
end
end
```

```ruby
module Web::Controllers::Signup
class Create
include Web::Action
params Params

def call(params)
# ...
end
end
end
```

0 comments on commit 493d716

Please sign in to comment.