Trailblazer Tutorial: Validations and Classes
Codementor Ruby on Rails Contributor and Expert Nick Sutterer joined us for a session in office hours to talk about the Trailblazer framework he’s working on. During his talks, Nick answered some of our viewers’ questions regarding how Trailblazer works.
The text below is a summary done by the Codementor team and may vary from the original video and if you see any issues, please let us know!
In your talks, you mentioned wanting users to put all validations in reform. What if the user just wants to use a simple model? If you set the validation in a sequel and abstract it to the reform, the model won’t work unless validation is written twice. Isn’t this redundant?
In my hardcore Trailblazer project, I don’t have anything in the models except association, so even if I had a really simple model to validate something like an email, I put the validation into a reform and then the reform into an operation, because I only want to work on operations.
The thing is, you only think your model is really simple, but then 2 weeks later you’d need another validation, and then 2 weeks after that you’d need another validation so it grows and grows until you go, “Oh shit, why didn’t I put it in an operation in the first place?”
If you already have an existing project and don’t want to go and delete everything in every model and put it in operations, here’s what you can do:
There’s a new feature in reform 1.1 where you can inherit or copy validations from a model into a form, so you don’t have to have redundancy. It’s a pretty nice thing for a transition where you pretty much take everything from the user and put/copy them in the user form, so you’ll have them on both layers.
In your code example, every step in Trailblazer needs to be be separated into a different class such as
Comment::Operation::Delete. Is there a better way to handle classifying?
You can use inheritance to make creating classes easy in Trailblazer. So let’s say you have the same validations and forms for
update, you can just inherit a
create operation from the
update operation. No other code needs to be written, as it will inherit the
contract and the code, so there is nothing you need to override.
I know it may sound crazy because you’ll need a class for every step, but if you use inheritance, you can also have reforms in your models. I did a lot of work to keep this process really dry in Trailblazer. I’m also working on something that automatically creates classes for you, so if you have really simple objects, you can use
runtime generator for the classes so you won’t have to write 8 different operations for a model that just has an email.
Other posts in this series with Nick Sutterer:
- Trailblazer Office Hours: A New Architecture For Rails by Nick Sutterer
- Tutorial: Decoupling Requests in Trailblazer Operations
Or Become a Codementor!
Codementor is your live 1:1 expert mentor helping you in real time.