diya
diya

Reputation: 7148

How to compare two objects in ruby

I have two User objects existing_user, current_user, how should I traverse the User.attributes.keys and check if they are equal.

Upvotes: 3

Views: 4472

Answers (2)

Atastor
Atastor

Reputation: 741

The background of this question is not completely clear to me. Usually when one is refering to current_user like you do, the background is ruby-on-rails, not only ruby like stated in the subject. I guess, you are getting the current_user via an external login-process (cas, facebook, etc) and internally keep a user-table for additional attributes.

Given my assumption is true, I would recommend, to identify one uniq attribute of the external user-model and store it in your internal user-table. You might want to validate this attributes uniqueness. When making your comparison, restrict to comparing this single attribute on the externally logged-in user and the internally kept users.

Upvotes: 0

Adam Eberlin
Adam Eberlin

Reputation: 14205

Probably something like this:

class User < ActiveRecord::Base

  # ...

  # untested, but the logic seems sound.
  def equals?(user)
    User.attributes.keys.each do |k|          
      return false unless self[k] == user[k]
    end
    true
  end

end

You could then call current_user.equals?(existing_user).

Upvotes: 3

Related Questions