Ruby instance variables versus ActiveRecord attributes

activerecord, ruby, ruby-on-rails

Solution

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.

Problem

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?

Original source