开发者

setup settings send to its parent class in ruby

开发者 https://www.devze.com 2023-02-09 14:59 出处:网络
how can i write this (child) class like so: class child < parent开发者_开发百科 create_columns :name, :address

how can i write this (child) class like so:

class child < parent开发者_开发百科
  create_columns :name, :address
end

so that:

class parent
# Can access the create_columns set by the child class?
end

Thanks.


You can solve this by using the inherited hook method in Ruby, so you can track all the children.

class Parent
 self.inherited(base)
    self.children << base
  end
end

class Child < Parent
def initialize
  @@instances << self
end

def self.instances
  @@instances
end

Now you can do things like Parent.children.each { |child| child.instances.collect(:&name) }. If name is accessable :-)

Hope that helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消