Meet the new video from our regular screencasts series on Syndicode’s YouTube channel! Great Ruby advice and tips will make you a better developer and will simplify your work! Prepared and explained by Paul Leoniuk, Rails code tips will bring you some interesting and useful knowledge. If you will have any comments, questions or suggestions, leave your comments under the post or under the original video on our YouTube channel. Today we’ll tell you about ‘Commands Pattern for(in) Ruby on Rails. Callbacks Killer’.
Today we are going to talk about Commands pattern in Ruby on Rails and best practices of its usage.
Why do we need to know Commands pattern in Ruby on Rails?
Have you ever heard about Active Record callbacks problem? It can be a real disaster for your Rails project. From the controller’s side, it is not clear that after Customer without auto_created credentials is created, and e-mail is sent. There is a conditional hidden on the model level here.
A better solution will be to get rid of callbacks and introduce two class methods — register and auto_create.
Keep in mind to keep your conditionals as close to the boundary as possible.
To move all of your callbacks to Commands services we’ll:
- Create a commands service folder. And create a new service called Customer::SaveCommand and put auto_create logic inside to keep model and controller clean;
- Write @customer_params = customer_params.dup because it’s safer not to mutate global params.
To see how the final version of the controller will look like – watch the video above!
p.s. Find more about Ruby methods on Syndicode blog!
p.p. s. Note, that If your project looks the same and you don’t really want to cope with it yourself, Syndicode can easily do this for you! We love coding and can help you no matter how difficult your project is! Use the contact form on our site to implement your idea to life!