tags:

views:

73

answers:

2

http://gist.github.com/172341 ( stackoverflow was breaking the formatting )

In the following case method name created by Human is not available to Boy. Is my understanding correct that attr_accessor methods are not available to subclasses. I need to use superclass to access the method added by attr_accessor.

A: 

What you're looking for is cattr_accessor which fixes this specific problem:

http://apidock.com/rails/Class/cattr%5Faccessor

Here's your example, fixed:

class Human
  def self.age
    @age = 50
  end
  def self.age=(input)
    @age = input
  end

  cattr_accessor :name

  self.name = 'human'
end
class Boy < Human
end

puts Human.age
puts Boy.age
puts Human.name
puts Boy.superclass.name
puts Boy.name # => 'human'
tadman
`cattr_accessor` makes all classes and instances of those classes share the same value for the property. I'm not sure this is exactly the right behavior.
Chuck
They both access the same attribute, so it makes sense. If you want to declare a different value for the sub-class, you'd likely have to re-declare the cattr_accessor.
tadman
I should have mentioned that I fixed this problem by using cattr_accessor. However I really wanted to understand how attr_accessor works. My understanding was that it stores an instance variable. But instant variables are available to subclasses.So the real question is why Boy.name is returning nil.Also why can't I use the code block of this site on my mac/FF.
Roger
Accessors do not store instance variables. You can define instance variables without using an accessor. Accessors are for exposing instance variables. You can highight code by indenting 4 spaces or highlighting the block and select the "101010" icon.
Tate Johnson
A: 

Human and Boy are two different objects. Two objects can never share a single instance variable. They do both have the method, but the method will access the appropriate ivar for the object.

Chuck