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?
Yes, you can extend a ruby class with
include ActiveModel::AttributeMethodsto expose your instance variables asActiveModel-like attributes.See the docs for more information.