Roger
Roger

Reputation: 1853

methods created by attr_accessor are not available to sub classes

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.

Upvotes: 4

Views: 4126

Answers (3)

xander-miller
xander-miller

Reputation: 529

Rails class_attribute method would be better in this case.

Rails Guide

Upvotes: 0

Chuck
Chuck

Reputation: 237010

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.

Upvotes: 1

tadman
tadman

Reputation: 211560

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

http://apidock.com/rails/Class/cattr_accessor

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'

Upvotes: 1

Related Questions