12

如何获得 ActiveRecord 属性方法功能?我有这堂课:

class PurchaseForm
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name,
                :surname,
                :email

  validates_presence_of :name

  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i

  def initialize(attributes = {}, shop_name)
    if not attributes.nil?
      attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end
end

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

4

5 回答 5

17

这是重构的变体:

class PurchaseForm
  include ActiveModel::Model

  def self.attributes
    [:name, :surname, :email]
  end

  attr_accessor *self.attributes

  # your validations

  def to_hash
    self.class.attributes.inject({}) do |hash, key|
      hash.merge({ key => self.send(key) })
    end
  end  
end

现在您可以轻松地使用这个类:

irb(main):001:0> a = PurchaseForm.new({ name: 'Name' })
=> #<PurchaseForm:0x00000002606b50 @name="Name">
irb(main):002:0> a.to_hash
=> {:name=>"Name", :surname=>nil, :email=>nil}
irb(main):003:0> a.email = 'user@example.com'
=> "user@example.com"
irb(main):004:0> a
=> #<PurchaseForm:0x00000002606b50 @name="Name", @email="user@example.com">
irb(main):005:0> a.to_hash
=> {:name=>"Name", :surname=>nil, :email=>"user@example.com"}

更重要的是,如果你想让这种行为可重用,请考虑将.attributesand#to_hash方法提取到单独的模块中:

module AttributesHash
  extend ActiveSupport::Concern

  class_methods do
    def attr_accessor(*args)
      @attributes = args
      super(*args)
    end

    def attributes
      @attributes
    end
  end

  included do
    def to_hash
      self.class.attributes.inject({}) do |hash, key|
        hash.merge({ key => self.send(key) })
      end
    end
  end
end

现在,只需将其包含到您的模型中即可:

class PurchaseForm
  include ActiveModel::Model
  include AttributesHash

  attr_accessor :name, :surname, :email

  # your validations
end
于 2015-08-28T21:35:04.323 回答
14

#instance_values可以完成这项工作:

class PurchaseForm
  attr_accessor :name, :email

  def attributes
    instance_values
  end
end

输出样本:

purchase.attributes #=> {"name"=>"John", "email"=>"john@example.com"}
于 2016-11-18T15:06:44.303 回答
7

我已经设法解决了这段代码的问题:

class PurchaseForm
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :attributes,
                :name,
                :surname,
                :email

  validates_presence_of :name

  validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i

  def initialize(attributes = {})
    @attributes = attributes
  end

  def persisted?
    false
  end
end
于 2011-03-28T18:08:07.207 回答
6

让我们试试这个

self.as_json

=> {:name=>"Name", :surname=>nil, :email=>"user@example.com"}

于 2016-08-16T14:23:52.397 回答
-3

使用会不会更好

include ActiveModel::Serialization

def attributes
  JSON.parse(self.to_json)
end
于 2013-03-18T14:07:03.523 回答