I would strongly advise against using bracket notation as it breaks the inheritance hierarchy of method calls and makes refactoring harder.
If my model has an attribute name
, and I decide I want to enhance the name every time someone reads it, a very idiomatic way to do that would be:
def name
"Awesome #{super}!"
end
Any place in my app that uses the method version would work fine, any place that uses the []
notation would return raw database data. I could overwrite the []
but then I would need special conditions checking for specific attributes. The whole thing would be a nightmare.
Another scenario, let's say I had an attribute that used to be stored in the database, but after a while decide that it should be computed on the fly, and end up dropping the database column. With the method version all I would need to do is add methods to my model. With the []
notation the process would be much much harder.
Also []
provides an insignificant performance improvement so though it looks like it's "closer" to the raw data it really isn't.
#[]
, some typecast is occurred based on the column type. And if I didn't specify withattr_name
, it raises an error. – Dairen