Form object patterns in Rails: Stop creating services for everything with YAAF
Tags: rails, ruby, opensource, codequality
Published: 2021-01-11 16:04:40

<!-- wp:heading -->
<h2 id="h-working-with-large-controllers">Working with large controllers</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>How many times have you encountered large controller methods? If you are&nbsp;<em>lucky</em>&nbsp;like me, probably many times.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>One of the most common practices to start refactoring a long controller is to move the code to a service.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Services are great, and if we code them in an atomic way, they will be easy to test and understand. But the problem is when we use the services it's like using a&nbsp;<em>Swiss Army knife</em>.</p>
<!-- /wp:paragraph -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>-"Hey, I don't know how to properly refactor this piece of code" 
-"Dude, just do a new service"</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p><strong>But no!</strong>, making a new service is not always the best option. In some cases, we are&nbsp;<em>reinventing the wheel</em>&nbsp;and maybe there is a pattern that already fits with our needs.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So here comes&nbsp;<strong>YAAF</strong>, yet another active form to save our day.&nbsp;<strong>YAAF</strong>&nbsp;is a gem that lets you create form objects using Rails in an easy and friendly way. It makes use of&nbsp;<code>ActiveRecord</code>&nbsp;and&nbsp;<code>ActiveModel</code>&nbsp;features, to provide you with a form object that behaves like a Rails model while remaining completely configurable.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-when-to-use-yaaf">When to use YAAF?</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Let's imagine that we have an API endpoint that saves a new post on our database. A post has a title, body, publisher, and could also have tags and a category.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Tags and categories can be created as soon as the publisher sends the post. (If our inputs don't find the correct tag or category, they will let the user write the name of a new one).</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So, in the worst-case scenario, our controller could have something like this:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
```ruby
class Api::V1::PostsController < Api::V1::ApiController
  def index
    @posts = Post.all
  end

  def create
    ActiveRecord::Base.transaction do
      @post = Post.new(post_params)
      @post.tags = params[:tags].map do |tag|
        tag[:id].present? ? Tag.find(tag[:id]) : Tag.find_or_create_by(name: tag[:name])
      end
      if params[:category_name].present?
        category = Category.create!(name: params[:category_name])
        @post.category = category
      end
      @post.save!
    end
  end


  def post_params
    params.require(:post).permit(:title, :body, :publisher_id, :category_id)
  end
end
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p>It looks terrible, right? Maybe our first thought about that piece of code is to make a refactoring that moves the creation of the post to a service named&nbsp;<code>PostCreationService</code>. This could be useful and might be used in the future in another part of the system. But, what have we said about&nbsp;<em>reinventing the wheel</em>?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>When using&nbsp;<strong>YAAF</strong>, we should create a new&nbsp;<code>PostForm</code>&nbsp;class that is going to encapsulate all the logic of post creation and related models inside it. And it is very simple to implement it! Just look at this code:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
```ruby
# app/forms/post_form.rb

class PostForm < ApplicationForm
  attr_accessor :post, :category_name, :tags
  validate :amount_of_tags

  def initialize(args = {})
    super(args)
    @models = [new_post, category, post_tags].flatten.compact
  end

  def new_post
    @new_post ||= Post.new(post).tap do |post|
      post.category = category
      post.tags = post_tags
    end
  end

  def category
    return [] if category_name.blank?

    @category ||= Category.find_or_initialize_by(name: category_name)
  end

  def post_tags
    return [] if tags.blank?

    @post_tags ||= tags.map do |tag|
      tag[:id].present? ? Tag.find(tag[:id]) : Tag.find_or_initialize_by(name: tag[:name])
    end
  end

  private

  def amount_of_tags
    return if tags.size.between?(1, 3)

    errors.add(:base, "You can't assign more than three tags to a post")
  end
end
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p><strong>Note:</strong>&nbsp;We have also added a custom validation named&nbsp;<code>amount_of_tags</code>, as YAAF helps us to encapsulate business rules in our Form Object.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>And then, in our controller, we have the following:</p>
<!-- /wp:paragraph -->

<!-- wp:code -->
```ruby
class Api::V1::PostsController < Api::V1::ApiController
  def index
    @posts = Post.all
  end

  def create
    form = PostForm.new(post_form_params)
    form.save!
    @post = form.post
  end

  private

  def post_form_params
    params.permit(:category_name, tags: %i[id name], post: %i[title body publisher_id category_id])
  end
end
```
<!-- /wp:code -->

<!-- wp:paragraph -->
<p><strong>Tip:</strong>&nbsp;Having an&nbsp;<code>ApplicationForm</code>&nbsp;which inherits from&nbsp;<code>YAAF::Form</code>&nbsp;is a good practice.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>That's it, now we have a&nbsp;<code>PostForm</code>&nbsp;which encapsulates all the persistency logic of post/tags/categories, leaving our controller and models clean, with an easy to follow code.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Another good thing is that&nbsp;<strong>YAAF</strong>&nbsp;provides a similar API to&nbsp;<code>ActiveModel</code>&nbsp;models, so you can treat them interchangeably.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2 id="h-why-not-a-service-or-poro-s">Why not a Service or PORO's?</h2>
<!-- /wp:heading -->

<!-- wp:list -->
<ul><li><strong>Making customized Services or PORO's could be disorganized</strong>&nbsp;if you're working in a team.</li><li>YAAF helps you to apply the&nbsp;<strong>Form Pattern</strong>&nbsp;in an easy way.</li><li>YAAF is only&nbsp;<strong>64 lines long</strong>.</li><li>It's&nbsp;<strong>well tested and maintained</strong>.</li><li>It helps you keep your models, views, and controllers thin by providing a better place to put business logic. In the end, this will&nbsp;<strong>improve the quality of your codebase and make it easier to maintain and extend</strong>.</li><li>And a lot&nbsp;<strong><a href="https://github.com/rootstrap/yaaf">more</a></strong>.</li></ul>
<!-- /wp:list -->

<!-- wp:heading -->
<h2 id="h-summary">Summary</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Well, if you've got this far, I hope this article helps you to integrate&nbsp;<strong>YAAF</strong>&nbsp;in your project, while also helping you use the&nbsp;<code>FormObject</code>&nbsp;Pattern to make your code even better. You can see more examples&nbsp;<strong><a href="https://github.com/rootstrap/yaaf">here</a></strong>.&nbsp;<strong>YAAF</strong>&nbsp;is open-source and is open to receive new contributions.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So check it out and see what you think!</p>
<!-- /wp:paragraph -->