我正在看一些关于Ruby中的Service object的教程中使用的Virtus gem。在github页面https://github.com/solnic/virtus中,它给出了以下示例。
在类中使用Virtus
您可以创建使用Virtus扩展的类并定义属性:
class User include Virtus.model
attribute :name, String
attribute :age, Integer
attribute :birthday, DateTime
end
user = User.new(:name => 'Piotr', :age => 31) user.attributes # => { :name => "Piotr", :age => 31, :birthday => nil }
user.name # => "Piotr"
user.age = '31' # => 31 user.age.class # => Fixnum
user.birthday = 'November 18th, 1983' # => #<DateTime: 1983-11-18T00:00:00+00:00 (4891313/2,0/1,2299161)>
# mass-assignment user.attributes = { :name => 'Jane', :age => 21 } user.name # => "Jane" user.age # => 21我可以看到这个例子是如何工作的,但是我想知道这和在Ruby语言中定义attr_accessors有什么不同?如果我必须向某人解释包含Virtus gem的好处,以及它在几行代码中的作用,我会怎么解释呢?
发布于 2016-09-20 22:00:24
Virtus的目标可以概括为试图使属性更加"Rails-y“。它们支持解析form/JSON、封装while retaining type information和其他一些东西,让常规属性去做并不是不可能的事情,但也不容易。
然而,当您将Virtus与每个this post的ActiveModel::Validations结合起来时,真正的好处就来了。由于您的基本值已经对Rails表单帮助器的期望做出了更好的响应,因此您有了一个非常强大的替代嵌套表单的方法。
https://stackoverflow.com/questions/39595856
复制相似问题