Search code examples
rubyattr-accessor

If attr_accessor includes an element, eg. ':name', is there any need for the 'name=' method?


Preface: I do understand the standard definition for attr_accessor and know that attr_accessor stands for two instance methods-a setter and a writer, and attr_accessor allows instances variables to be accessible throughout the class.

But now and then I see an element included in attr_accessor AND is defined as a method.

So my question is: Why does that happen? Is it just bad code I saw?

Pseudo/example code:

class Such_n_such
    attr_accessor :name, :color  
            #code omitted
       def color=(color)
         (some code)
       end

Thanks in advance!


Solution

  • I would argue that you should not use attr_accessor and then override the setter.

    I prefer using attr_reader with custom setter methods:

    attr_accessor :name
    attr_reader :color  
    
    def color=(color)
      # ...
    end