Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ContentfulModel::Base doesn't provide a #hash method #65

Closed
georgebrock opened this issue Apr 4, 2017 · 1 comment
Closed

ContentfulModel::Base doesn't provide a #hash method #65

georgebrock opened this issue Apr 4, 2017 · 1 comment

Comments

@georgebrock
Copy link

ContentfulModel::Base doesn't provide a #hash method, so model instances cannot be effectively used as keys in Hashes, or easily filtered for duplicates.

For example, I have a Requirement model which has_one Category. After loading my requirements, I group them by category:

requirements.group_by(&:category)
  # => {<Category> => [<Requirement>, <Requirement>, …], …}

For the results of a single query, this works fine. However, sometimes I want to combine the results of two queries, to simulate a logical OR:

(some_requirements + other_requirements).uniq.group_by(&:category)

This throws up two problems, both arising from the lack of #hash:

  1. Duplicate requirements from the two queries are different objects, and since they inherit the default implementation of #hash, they're not filtered out by #uniq.
  2. Any category that was present in both sets of results ends up as two different keys in the resulting Hash, again because they are different objects.

Possible solutions

In my app, I added #hash and #eql? methods based closely on ActiveRecord's implementation:

  def eql?(other)
    super || other.instance_of?(self.class) && id.present? && other.id == id
  end

  def hash
    if id.present?
      self.class.hash ^ id.hash
    else
      super
    end
  end
@dlitvakb
Copy link
Contributor

Hey @georgebrock,

Thanks for the suggestion, I'm currently implementing the upgrade to the 2.0 CDA SDK and implemented a similar solution to this.

The release will be coming up in the next few weeks, with the initial PR coming out tomorrow.

Cheers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants