Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attributes() method in Ruby

Tags:

ruby

According to this post, to make attributes stick during to_json call, we need to do something like this:

def attributes
  super.merge('foo' => self.foo)
end

With my beginner's knowledge in Ruby, I fail to understand the following:

  • Is there an attribute method present for every Ruby class?
  • What is super.merge doing here? Which hashmap does it append its argument to?
like image 840
Holmes.Sherlock Avatar asked Sep 27 '26 17:09

Holmes.Sherlock


1 Answers

Hi attributes is a method provided by ActiveRecord. If you click on source you will notice how it really just exposes the instance variable @attributes which is a hash (as it can be nil it is enforced to a hash through .to_hash).

class ActiveRecord::Base
  def attributes
    @attributes.to_hash
  end
end

We'll call this method parent as we will extend its behaviour in our class. This is possible through inheritance:

class Person < ActiveRecord::Base
  def attributes
    super.merge('foo' => self.foo)
  end
end

attributes is now calling the parent's method [Activerecord::Base].attributes and is adding a new key to the hash. This code is roughly equivalent and should be easier to read.

class Person < ActiveRecord::Base
  def attributes
    attrs = super # eg. { name: "x", created_at: [...], [...] }
    attrs[:foo] = self.foo # eg. { name: "x", foo: [...], ... }
    attrs
  end
end
like image 127
Adit Saxena Avatar answered Sep 30 '26 10:09

Adit Saxena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!