What’s the best way to abstract this pattern:
class MyClass
attr_accessor :foo, :bar
def initialize(foo, bar)
@foo, @bar = foo, bar
end
end
A good solution should take superclasses into consideration and be able to handle still being able to have an initializer to do more things. Extra points for not sacrificing performance in your solution.
A solution to that problem already (partially) exists, but if you want a more declarative approach in your classes then the following should work.
You can now do:
Some characteristics of this solution:
initialize_withinitializeto do custom initializationsuperininitializeinitializeare the arguments that were not consumed by attributes specified withinitialize_withinitialize_withare inherited, but defining a new set on a child class will remove the parent attributesIf you want to create a solution with absolute minimal performance overhead, it would be not that difficult to refactor most of the functionality into a string which can be
evaled when the initializer is defined. I have not benchmarked what the difference would be.Note: I found that hacking
newworks better than hackinginitialize. If you defineinitializewith metaprogramming, you’d probably get a scenario where you pass a block toinitialize_withas a substitute initializer, and it’s not possible to usesuperin a block.