vendredi 30 novembre 2018

Ruby - Calling methods in class definition

I was recently sifting through some code and came across this:

class A

  @@container = {}
  def self.register(a, b)
    @@container[a] = b
  end

  def self.get(a)
    @@contaienr[a]
  end
end


class BRunner < A
  A.register(D, self)

  def self.run
    #...
  end
end

class CRunner < A
  A.register(E, self)

  def self.run
    #...
  end
end


class C
  [D, E].each do |item|
    A.get(item).run()
  end
end

BRunner and CRunner call register when their respective class definition blocks are executed at runtime without explicitly calling them. This doesn't seem right because to me, this is not clear code. Is this a Ruby thing or just bad programming? Whats your opinion on code like this and why?

Aucun commentaire:

Enregistrer un commentaire