在Hanami中实现表单对象 [英] Implementing Form Objects in Hanami

查看:89
本文介绍了在Hanami中实现表单对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Hanami启发的Bob叔叔的整洁架构中,表单对象保护了Interactor和我们的交付机制(通常是http端点)之间的边界.

In Uncle Bob's clean architecture, which Hanami is inspired by, Form Objects guard the boundary between Interactors and our delivery mechanism (typically an http endpoint).

在Hanami文档中,使用Actions中的params块来进行赏金保护(请参阅此处).这似乎将验证与http传递机制结合在一起.在我看来,表单对象(或完成相同任务的黑色参数)将生活在与交付机制无关的交互器中.

In the Hanami docs, bounary guarding is done using params blocks in Actions (see here). This seems to couple validation to the http delivery mechanism. It seems more natural to me that Form Objects (or params black which accomplish the same thing) would live in delivery-mechanism-agnostic Interactors.

不幸的是,我无法弄清楚Hanami是否支持这种设计.我发现了一个类似的问题在Hanami论坛上,但没有答案.

Unfortunately, I cannot figure out if Hanami supports such a design. I found a similar question on the Hanami forum, but it has no answer.

为澄清起见,下面是一段代码,演示了我想做的事情,但是使用了VirtusActiveModel::Validations而不是Hanami工具.对于那些熟悉Trailblazer的人来说,它的contract块在其操作中(Interactor的术语)是另一个示例.

To clarify, below is a snippet of code demonstrating the kind of thing I want to do, but using Virtus and ActiveModel::Validations rather than Hanami facilities. For those familiar with Trailblazer, its contract block within its operations (its term for Interactor) is another example.

最后,我对Hanami的预期用途有误解吗? Hanami支持Interactors,所以看来这应该是可能的...

Finally, am I misunderstanding something about the intended use of Hanami? Hanami supports Interactors, so it seems like this should be possible...

require 'hanami/model'
require 'active_model'
require 'virtus'

class PersonForm
  include Virtus.model
  include ActiveModel::Validations

  attribute :name, String
  attribute :age, Integer

  validates :name, :age, presence: true

  def each
    attributes.each {|a| yield a}
  end
end

class Person
  include Hanami::Entity
  attributes :name, :age
end

# Code like this would then live inside of an Interactor, which
# can accept a params hash.

jonah_form = PersonForm.new({name: 'Jonah', age: '99'})
jonah = Person.new(jonah_form) if jonah_form.valid?
p jonah #=> <Person:0x007fbdde1edcc0 @id=nil @name="Jonah" @age=99>
# do stuff with our jonah entity

推荐答案

很抱歉错过了这个问题.

sorry for missing this question.

这些参数充当验证器,以节省开发人员创建和实例化另一个类的时间.在Ruby社区中,这是一个问题.

The params act as validator to save developers to create and instantiate another class. In Ruby Community this is a problem.

DSL可以帮助您妥协.

DSL to the rescue for this compromise.

如果您希望有一个具体的表单对象,而不是使用VirtusActiveModel,则只需包含Hanami::Validations并具有相同的行为即可.

If you prefer to have a concrete form object, instead of using Virtus and ActiveModel, you can just include Hanami::Validations and have the same behavior.

这篇关于在Hanami中实现表单对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆