Reputation: 169
In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example:
user = User.first # Assuming User to be inheriting from ActiveRecord::Base
user.name # Accessing attribute 'name' via method
user[:name] # Attribute 'name' is accessible via hash as well
How to make instance variables accessible through hash for classes not inheriting from ActiveRecord::Base
?
Upvotes: 1
Views: 978
Reputation: 9495
It's not "through Hash", it's "array access" operator.
To implement it, you need to define methods:
def [](*keys)
# Define here
end
def []=(*keys, value)
# Define here
end
Of course, if you won't be using multiple keys to access an element, you're fine with using just key
instead of *keys
, so that you have not an array of keys (even if only one is given), but just a single key.
Plenty of other classes implement it, namely Struct
s, so you're free to pick an existing implementation or roll out your own.
Getting instance variables to be affected by these methods means implementing them using instance_variable_get
/instance_variable_set
. Nothing fancy.
Upvotes: 3
Reputation: 176552
Generally speaking, in order to make attributes available as Hash and/or getter/setter, you can store the attributes in a single Hash and provide the corresponding getter/setter methods.
This is a fairly simple feature you can easily code directly into the target class.
In Ruby, there are also a couple of built-in libraries that provide a similar feature with slightly different approaches: Struct
and OpenStruct
.
Here's an example with an object defined using a Struct
.
Customer = Struct.new(:name, :address, :zip)
joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", 12345)
joe["name"] #=> "Joe Smith"
joe[:name] #=> "Joe Smith"
joe[0] #=> "Joe Smith"
If you are using Rails, you can also include ActiveModel::Model
to have an ActiveRecord-like feature.
Upvotes: 0