百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rectify

> 编程语言
开源

构建可维护的 Rails 应用

592 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

构建可维护的 Rails 应用

Rectify

Rectify is a gem that provides some lightweight classes that will make it easier to build Rails applications in a more maintainable way. It's built on top of several other gems and adds improved APIs to make things easier.

Rectify is an extraction from a number of projects that use these techniques and proved to be successful.

Video

In June 2016, I spoke at RubyC about Rectify and how it can be used to improve areas of your application. The full video and slides can be found here:

Building maintainable Rails apps - RubyC 2016

Installation

To install, add it to your Gemfile:

ruby
gem "rectify"

Then use Bundler to install it:

bundle install

Overview

Currently, Rectify consists of the following concepts:

  • Form Objects
  • Commands
  • Presenters
  • Query Objects

You can use these separately or together to improve the structure of your Rails applications.

The main problem that Rectify tries to solve is where your logic should go. Commonly, business logic is either placed in the controller or the model and the views are filled with too much logic. The opinion of Rectify is that these places are incorrect and that your models in particular are doing too much.

Rectify's opinion is that controllers should just be concerned with HTTP related things and models should just be concerned with data relationships. The problem then becomes, how and where do you place validations, queries and other business logic?

Using Rectify, Form Objects contain validations and represent the data input of your system. Commands then take a Form Object (as well as other data) and perform a single action which is invoked by a controller. Query objects encapsulate a single database query (and any logic it needs). Presenters contain the presentation logic in a way that is easily testable and keeps your views as clean as possible.

Rectify is designed to be very lightweight and allows you to use some or all of it's components. We also advise to use these components where they make sense not just blindly everywhere. More on that later.

Here's an example controller that shows details about a user and also allows a user to register an account. This creates a user, sends some emails, does some special auditing and integrates with a third party system:

ruby
class UserController  current_user)
  end

  def new
    @form = RegistrationForm.new
  end

  def create
    @form = RegistrationForm.from_params(params)

    RegisterAccount.call(@form) do
      on(:ok)      { redirect_to dashboard_path }
      on(:invalid) { render :new }
      on(:already_registered) { redirect_to login_path }
    end
  end
end

The RegistrationForm Form Object encapsulates the relevant data that is required for the action and the RegisterAccount Command encapsulates the business logic of registering a new account. The controller is clean and business logic now has a natural home:

HTTP             => Controller   (redirecting, rendering, etc)
Data Input       => Form Object  (validation, acceptable input)
Business Logic   => Command      (logic for a specific use case)
Data Persistence => Model        (relationships between models)
Data Access      => Query Object (database queries)
View Logic       => Presenter    (formatting data)

The next sections will give further details about using Form Objects, Commands and Presenters.

Form Objects

The role of the Form Object is to manage the input data for a given action. It validates data and only allows whitelisted attributes (replacing the need for Strong Parameters). This is a departure from "The Rails Way" where the model contains the validations. Form Objects help to reduce the weight of your models for one, but also, in an app of reasonable complexity even simple things like validations become harder because context is important.

For example, you can add validation for a User model but there are different context where the validations change. When a user registers themselves you might have one set of validations, when an admin edits that user you might have another set, maybe even when a user edits themselves you may have a third. In "The Rails Way" you would have to have conditional validation in your model. With Rectify you can have a different Form Object per context and keep things easier to manage.

Form objects in Rectify are based on Virtus and make them compatible with Rails form builders, add ActiveModel validations and all allow you to specify a model to mimic.

Here is how you define a form object:

ruby
class UserForm  true
end

You can then set that up in your controller instead of a normal ActiveRecord model:

ruby
class UsersController  "1",
  "user" => {
    "first_name" => "Andy",
    "last_name"  => "Pike"
  }
}

You might want to mimic something different and use a form object that is not named in a way where the correct model can be mimicked. For example:

ruby
class UserForm  true
end

In this example we are using the same UserForm class but am mimicking a Teacher model. The above form will then use the route path helpers teachers_path and the params key will be teacher rather than users_path and user respectively.

Attributes

You define your attributes for your form object just like you do in Virtus.

By default, Rectify forms include an id attribute for you so you don't need to add that. We use this id attribute to fulfill some of the requirements of ActiveModel so your forms will work with form builders. For example, your form object has a #persisted? method. Your form object is never persisted so technically this should always return false.

However, you are normally representing something that is persistable. So we use the value of id to workout if what this should return. If id is a number greater than zero then we assume it is persisted otherwise we assume it isn't. This is important as it affects where your form is posted (to the #create or #update action in your controller).

Populating attributes

There are a number of ways to populate attributes of a form object.

Constructor

You can use the constructor and pass it a hash of values:

ruby
form = UserForm.new(:first_name => "Andy", :last_name => "Pike")

Params hash

You can use the params hash that a Rails controller provides that contains all the data in the request:

ruby
form = UserForm.from_params(params)

When populating from params we will populate the built in id attribute from the root of the params hash and populate the rest of the form attributes from within the parent key. For example:

ruby
params = {
  "id" => "1",
  "user" => {
    "first_name" => "Andy",
    "last_name"  => "Pike"
  }
}

form = UserForm.from_params(params)

form.id         # => 1
form.first_name # => "Andy"
form.last_name  # => "Pike"

The other thing to notice is that (thanks to Virtus), attribute values are cast to the correct type. The params hash is actually all string based but when you get values from the form, they are returned as the correct type (see id above).

In addition to the params hash, you may want to add additional contextual data. This can be done by supplying a second hash to the .from_params method. Elements from this hash will be available to populate form attributes as if they were under the params key:

ruby
form = UserForm.from_params(params, :ip_address => "1.2.3.4")

form.id         # => 1
form.first_name # => "Andy"
form.last_name  # => "Pike"
form.ip_address # => "1.2.3.4"

Model

You can pass a Ruby object instance (which is normally an ActiveModel but can be any PORO) to the form to populate it's attribute values. This is useful when editing a model:

ruby
user = User.create(:first_name => "Andy", :last_name => "Pike")

form = UserForm.from_model(user)

form.id         # => 1
form.first_name # => "Andy"
form.last_name  # => "Pike"

This works by trying to match (deeply) the attributes of the form object with the passed in object. If there is matching attribute or method in the model, then whatever it returns will be assigned to the form attribute.

This works great for most cases, but sometimes you need more control and need the ability to do custom mapping from the model to the form. When this is required, you just need to implement the #map_model method in your form object:

ruby
class UserForm  "Andy"
form.age        # => 38

Populating the form from JSON can be useful when dealing with API requests into your system. Which allows you to easily access data and perform validation if required.

Validations

Rectify includes ActiveModel::Validations for you so you can use all of the Rails validations that you are used to within your models.

Your Form Object has a #valid? method that will validate the attributes of your form as well as any (deeply) nested form objects and array attributes that contain form objects. There is also an #invalid? method that returns the opposite of #valid?.

The #valid? and #invalid? methods also take a set of options. These options allow you to not validate nested form objects or array attributes that contain form objects. For example:

ruby
class UserForm  true
end

class AddressForm  true
end

class ContactForm  true
end

form = UserForm.from_params(params)

form.valid?(:exclude_nested => true, :exclude_arrays => true)

In this case, the UserForm attributes will be validated (name in the example above) but the address and contacts will not be validated.

Deep Context

It's sometimes useful to have some context within your form objects when performing validations or some other type of data manipulation of the input. For example, you might want to check that the current user owns a particular resource as part of your validations. You could add the current user as an additional contextual option as the example shows above. However, sometimes you need this context to be available at all levels within your form not just at the root form object. You might have nested forms or arrays of form objects and they all might need access to this context. As there is no link up the chain from child to parent forms, we need a way to supply some context and make it available to all child forms.

You can do that using the #with_context method.

ruby
form = UserForm.from_params(params).with_context(:user => current_user)

This allows us to access #context in any form, and use the information within it when we perform validations or other work:

ruby
class PostForm  blog_id)

    errors.add(:blog_id, "not owned by this user")
  end
end

class TagForm  category_id)

    errors.add(:category_id, "not a category for this user")
  end
end

The context is passed to all nested forms within a form object to make it easy to perform all the validations and data conversions you might need from within the form object without having to do this as part of the command.

Strong Parameters

Did you notice in the example above that there was no mention of Strong Parameters. That's because with Form Objects you do not need strong parameters. You only specify attributes in your form that are allowed to be accepted. All other data in your params hash is ignored.

Take a look at Virtus for more information about how to build a form object.

I18n

Regarding internationalization, the main affected classes when coercing are Date and Time classes. This is coercing Strings into Date, DateTime and Time. Texts don't usually need to be coerced as they are simple String attributes with nothing special in them.

When coercing dates and times in a multi-language application, each locale will have its own date and time formats, and

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Ruby

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言