The intention of [] and []= is so that you can override your model's accessor.

def username=(username)
  self[:username] = username
end

If we fix the []= to call the accessor as well, that will lead to circular 
reference, and there will be no way to set those variables. You're also 
supposed to call the model accessor's method as well, as those are actually a 
public interface. [] and []= is not.

- Prem

On Apr 6, 2012, at 11:24 AM, Ken Collins wrote:

> They are established aliases to read and write attribute. I know changing 
> would break a ton of my own code and various gems I author. 
> 
> Sent from my iPad
> 
> On Apr 6, 2012, at 10:47 AM, Rodrigo Rosenfeld Rosas <[email protected]> 
> wrote:
> 
>> Currently [] and []= are defined as follows for ActiveRecord instances:
>> 
>> https://github.com/rails/rails/blob/master/activerecord/lib/active_record/attribute_methods.rb
>> 
>> def [](attr_name)
>>   read_attribute(attr_name)
>> end
>> 
>> def []=(attr_name, value)
>>   write_attribute(attr_name, value)
>> end
>> 
>> If those accessors are used then overridden attribute accessors wouldn't be 
>> called.
>> 
>> I didn't find any references about the []/[]= methods in the current API, so 
>> I just mentioned them in docrails:
>> 
>> https://github.com/lifo/docrails/commit/a49fe6ec2cb9f22a3b18d7db5ae2ee90325e9d09
>> 
>> But then I realized that the given example may have undesired side effects:
>> 
>> [:deleted, :disabled].each{|p| model[p] = params[p] == 'true' }
>> 
>> What if "deleted=" or "disabled=" were overridden? They wouldn't be called.
>> 
>> So I was thinking that maybe Rails 4 could change their implementation to:
>> 
>> def [](attr_name)
>>   send attr_name.to_s
>> end
>> 
>> def []=(attr_name, value)
>>   send :"#{attr_name}=", value
>> end
>> 
>> Better to read this style of code in some framework than inside some 
>> application...
>> 
>> Any thoughts?
>> 
>> Happy Easter!
>> 
>> Rodrigo.
>> 
>> 
>> -- 
>> You received this message because you are subscribed to the Google Groups 
>> "Ruby on Rails: Core" group.
>> To post to this group, send email to [email protected].
>> To unsubscribe from this group, send email to 
>> [email protected].
>> For more options, visit this group at 
>> http://groups.google.com/group/rubyonrails-core?hl=en.
> 
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Ruby on Rails: Core" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to 
> [email protected].
> For more options, visit this group at 
> http://groups.google.com/group/rubyonrails-core?hl=en.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-core?hl=en.

Reply via email to