Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveModel attributes

How do I get ActiveRecord attributes method functionality? I have this class:

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

What I need to do, to have an attributes method to list all names and values from PurchaseForm object?

like image 651
zigomir Avatar asked Mar 28 '11 17:03

zigomir


1 Answers

#instance_values could do the job:

class PurchaseForm
  attr_accessor :name, :email

  def attributes
    instance_values
  end
end

Output sample:

purchase.attributes #=> {"name"=>"John", "email"=>"[email protected]"}
like image 78
Alexey Morozov Avatar answered Sep 21 '22 06:09

Alexey Morozov