Andrei S
Andrei S

Reputation: 6516

class inheritance in ruby / rails

so this is what i want to do:

class A
  ATTRS = []

  def list_attrs
    puts ATTRS.inspect
  end
end

class B < A
  ATTRS = [1,2]
end

a = A.new
b = B.new
a.list_attrs
b.list_attrs

i want to create a base class with a method that plays with the ATTRS attribute of the class. in each inherited class there will be a different ATTRS array

so when i call a.list_attrs it should print an empty array and if i call b.attrs should put [1,2].

how can this be done in ruby / ruby on rails?

Upvotes: 2

Views: 621

Answers (3)

sawa
sawa

Reputation: 168101

I don't think it's a good idea to create the same array each time a method is called. It's more natural to use class instance variables.

class A
  def list_attrs; p self.class.attrs end
end
class << A
  attr_accessor :attrs
end

class A
  @attrs = []
end
class B < A
  @attrs = [1, 2]
end
A.new.list_attrs # => []
B.new.list_attrs # => [1, 2]

You can also use constants along the line suggested in the question:

class A
  def list_attrs; p self.class.const_get :ATTRS end
  ATTRS = []
end
class B < A
  ATTRS = [1, 2]
end
A.new.list_attrs # => []
B.new.list_attrs # => [1, 2]

Upvotes: 1

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

modf's answer works... here's another way with variables. (ATTRS is a constant in your example)

class A
  def initialize
    @attributes = []
  end

  def list_attrs
    puts @attributes.inspect
  end
end

class B < A
  def initialize
    @attributes = [1,2]
  end
end

Upvotes: 2

molf
molf

Reputation: 74945

It is typically done with methods:

class A
  def attrs
    []
  end

  def list_attrs
    puts attrs.inspect
  end
end

class B < A
  def attrs
    [1,2]
  end
end

Upvotes: 2

Related Questions