After learning about the existence of Gem and Trailblazer, which provide an abstract layer, I tried Create. The outline of Trailblazer is explained in other articles in an easy-to-understand manner, so I will omit it.
This article was very easy to understand. TrailBlazer overview I tried to summarize
ruby '2.7.2' 'rails', '~> 6.0.3' template engine: haml
Create
.
└── todo
    ├── cell
    │   ├── index.rb
    │   └── new.rb
    ├── contract
    │   └── form.rb
    ├── operation
    │   ├── create.rb
    │   └── index.rb
    └── view
        ├── form.haml
        ├── index.haml
        └── new.haml
Operation
module Todo::Operation
  class Create < Trailblazer::Operation
    class Present < Trailblazer::Operation
      step Model(Todo, :new)
      step Contract::Build( constant: Todo::Contract::Form )
    end
    step Subprocess(Present) #present class step call
    step Contract::Validate(key: :todo) #Validation using contract
    step Contract::Persist() #Save to model
  end
end
Contract
module Todo::Contract
  class Form < Reform::Form
    include Reform::Form::ActiveModel
    property :title
    property :description
    property :completed
      
    validates :title, presence: true
    validates :description, length: { minimum: 2 }
    #You can also override
    # def title
    #  super.capitalize
    # end
  end
end
Cell
module Todo::Cell
  class New < Trailblazer::Cell
    include ActionView::RecordIdentifier
    include ActionView::Helpers::FormOptionsHelper
    include SimpleForm::ActionViewExtensions::FormHelper
  end
end
View
= simple_form_for(model, html: {novalidate: true}) do |f|
  = f.input :title, placeholder: "Title"
  %br
  = f.input :description, as: :text, placeholder: "Description"
  %br
  = f.submit 'Submit'
  = link_to 'Back', todos_path

[Project] I tried this time (https://github.com/izumiiii/trail-todo)
I tried to summarize the outline of TrailBlazer trailblazer
Recommended Posts