Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby instance variables versus ActiveRecord attributes

I've read that ruby objects are just places where we can store instance variables (and class pointers). So:

class Person
  def initialize(age)
    @age = age
  end
end

Now if we run:

p = Person.new(101)

Then we get:

#<Person:0x86cf5b8 @age=101>

Great, the property age is stored as an instance variable, as expected. But things work a little differently if we convert the model to inherit from ActiveRecord. Now, after instantiating an new Person, we see this:

# timestamps removed
#<Person id: 1, age: 101 > 

The age property no longer appears to be an instance variable. So what is really going on here?

I know that we can access the @attributes instance variable, which contains a hash of all the properties and values, so I'm wondering if ActiveRecord is possibly modifying the console output to present the objects attributes in this way.

Is it possible to instantiate a Ruby object where properties are held as attributes and not instance variables, without using ActiveRecord?

like image 702
stephenmurdoch Avatar asked Oct 08 '22 14:10

stephenmurdoch


2 Answers

Yes, you can extend a ruby class with include ActiveModel::AttributeMethods to expose your instance variables as ActiveModel-like attributes.

See the docs for more information.

like image 62
seanreads Avatar answered Oct 12 '22 12:10

seanreads


as you see in your code 'storing' properties as instance vars was your own doing, so if you wanna hold them any other way, is also up to you. ruby gives you convenience class methods to define getter and setter methods like attr_accessor.

also worth noting, that if you inherit from ActiveRecord::Base, you should not override initialize.

like image 32
Viktor Trón Avatar answered Oct 12 '22 12:10

Viktor Trón