attr_accessor across multiple classes?

Shpigford picture Shpigford · Aug 8, 2013 · Viewed 7.2k times · Source

I have a single module with lots of different classes (divided into separate files). Each class has the same set of attr_accessor, so how can I reuse that instead of having to repeat the attr_accessor block?

What I'm currently doing....

# dog.rb
module Animals
   class Dog
      attr_accessor :name, :color, :age 
   end
end

# cat.rb
module Animals
   class Cat
      attr_accessor :name, :color, :age 
   end
end

# rodent.rb
module Animals
   class Rodent
      attr_accessor :name, :color, :age 
   end
end

I tried doing this with no luck...

# animals.rb
module Animals
   attr_accessor :name, :color, :age 
end

I need to access these modules directly across my app (it's a Rails app). For example: Animals::Dog.give_water

Answer

sawa picture sawa · Aug 8, 2013

Your use of the module Animal is wrong. Using it as a namespace does not do anything good for your purpose. You should include them.

module Animals
  attr_accessor :name, :color, :age 
end

class Dog
  include Animals
end

class Cat
  include Animals
end

class Rodent
  include Animals
end

Or, you can turn Animal into a class, and subclass from that.

class Animals
  attr_accessor :name, :color, :age 
end

class Dog < Animals
end

class Cat < Animals
end

class Rodent < Animals
end

By the way, a class already implies that it has possibly multiple instances, so it is redundant to have a plural name for a class. And you are also inconsistent about it.