เพิ่ม type ใหม่ให้กับ attributes API ของ Rails 5
13 ตุลาคม 2563
attributes API ของ Rails 5 ช่วยให้เราสร้าง form object ได้ง่ายมาก
ก่อนหน้านี้เราใช้ callback after_initialize เพื่อแปลงอีเมลเป็นตัวพิมพ์เล็ก แต่ด้วยโค้ดต่อไปนี้ เราสามารถกำหนด type :email ขึ้นมาเอง แล้วค่าจะถูก cast ให้อัตโนมัติทุกครั้งที่เซ็ตค่า
ข้อดีคือการเรียกเซ็ตค่าอีเมลครั้งถัด ๆ ไปก็จะถูก cast ให้ด้วยเช่นกัน
class EmailType < ActiveModel::Type::String
def cast(value)
return super unless value.is_a?(String)
super(value.downcase)
end
end
ActiveModel::Type.register(:email, EmailType)
class Foo
include ActiveModel::Model
include ActiveModel::Attributes
attribute :email, :email
end
> Foo.new(email: 'EMAIL@MAIL.com').email
=> 'email@mail.com'