Ruby 跨多个类的attr\u访问器?
我有一个单独的模块,有很多不同的类(分为不同的文件)。每个类都有一组相同的Ruby 跨多个类的attr\u访问器?,ruby,class,module,attr-accessor,Ruby,Class,Module,Attr Accessor,我有一个单独的模块,有很多不同的类(分为不同的文件)。每个类都有一组相同的attr\u访问器,因此我如何重用它而不必重复attr\u访问器块 我现在正在做的 # dog.rb module Animals class Dog attr_accessor :name, :color, :age end end # cat.rb module Animals class Cat attr_accessor :name, :color, :age
attr\u访问器
,因此我如何重用它而不必重复attr\u访问器
块
我现在正在做的
# 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
我试着这么做,但运气不好
# animals.rb
module Animals
attr_accessor :name, :color, :age
end
我需要通过我的应用程序直接访问这些模块(它是Rails应用程序)。例如:
Animals::Dog.give_water
您使用模块Animal
是错误的。将其用作名称空间对您的目的没有任何好处。你应该包括他们
module Animals
attr_accessor :name, :color, :age
end
class Dog
include Animals
end
class Cat
include Animals
end
class Rodent
include Animals
end
或者,您可以将Animal
转换为一个类,并从中生成子类
class Animals
attr_accessor :name, :color, :age
end
class Dog < Animals
end
class Cat < Animals
end
class Rodent < Animals
end
类动物
属性访问器:名称、颜色、年龄
结束
狗类动物
结束
猫类动物
结束
啮齿类动物
结束
顺便说一句,一个类已经暗示它可能有多个实例,所以一个类的复数名是多余的。你对此也不一致。我需要能够直接访问每个类中的方法,比如
动物::Dog.feed
…我仍然可以使用其中一个/两个吗?不确定你的意思是什么。您应该在问题中详细说明这一点。@shipford yes您可以在第二个示例中通过定义这样的方法来实现这一点<代码>def自进给。如果希望所有后代继承它,它必须进入Animals
类中。