ruby-on-rails – ActiveModel属性

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – ActiveModel属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@如何获取ActiveRecord属性方法功能?我有这堂课:
  1. class PurchaseForm
  2. include ActiveModel::Validations
  3. include ActiveModel::Conversion
  4. extend ActiveModel::Naming
  5.  
  6. attr_accessor :name,:surname,:email
  7.  
  8. validates_presence_of :name
  9.  
  10. validates_format_of :email,:with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
  11.  
  12. def initialize(attributes = {},shop_name)
  13. if not attributes.nil?
  14. attributes.each do |name,value|
  15. send("#{name}=",value)
  16. end
  17. end
  18.  
  19. def persisted?
  20. false
  21. end
  22. end

我需要做什么,有一个属性方法列出来自PurchaseForm对象的所有名称和值?

解决方法

这是重构的变体:
  1. class PurchaseForm
  2. include ActiveModel::Model
  3.  
  4. def self.attributes
  5. [:name,:email]
  6. end
  7.  
  8. attr_accessor *self.attributes
  9.  
  10. # your validations
  11.  
  12. def to_hash
  13. self.class.attributes.inject({}) do |hash,key|
  14. hash.merge({ key => self.send(key) })
  15. end
  16. end
  17. end

现在您可以轻松使用此类:

  1. irb(main):001:0> a = PurchaseForm.new({ name: 'Name' })
  2. => #<PurchaseForm:0x00000002606b50 @name="Name">
  3. irb(main):002:0> a.to_hash
  4. => {:name=>"Name",:surname=>nil,:email=>nil}
  5. irb(main):003:0> a.email = 'user@example.com'
  6. => "user@example.com"
  7. irb(main):004:0> a
  8. => #<PurchaseForm:0x00000002606b50 @name="Name",@email="user@example.com">
  9. irb(main):005:0> a.to_hash
  10. => {:name=>"Name",:email=>"user@example.com"}

更重要的是,如果要使此行为可重用,请考虑将.attributes和#to_hash方法提取到单独的模块中:

  1. module AttributesHash
  2. extend ActiveSupport::Concern
  3.  
  4. class_methods do
  5. def attr_accessor(*args)
  6. @attributes = args
  7. super(*args)
  8. end
  9.  
  10. def attributes
  11. @attributes
  12. end
  13. end
  14.  
  15. included do
  16. def to_hash
  17. self.class.attributes.inject({}) do |hash,key|
  18. hash.merge({ key => self.send(key) })
  19. end
  20. end
  21. end
  22. end

现在,只需将它包含在您的模型中即可完成:

  1. class PurchaseForm
  2. include ActiveModel::Model
  3. include AttributesHash
  4.  
  5. attr_accessor :name,:email
  6.  
  7. # your validations
  8. end

猜你在找的Ruby相关文章