POC: Use Ruby inherited callback instead InsertBulk module
Firstly, I really like your project ! Really helpful :+1:
I would suggest you to move the code inside InsertBulk module ActiveRecord::Base by using inherited callback.
- That permit to don't pollute the looong ancestor chain of ActiveRecord::Base.
- ActiveRecord Models already inherit from ActiveRecord::Base.
- You have access to the model's name via the
inheritedcallback argument.
I've coded a POC there: inherited_callback
I've decided to create a bulk_insert per Model. But it's possible to create the method only once in ActiveRecord::Base
module ActiveRecord
class Base
def self.inherited(child_class)
super
return if methods.include?(:insert_bulk)
...
end
end
end
So, you have the same flexibility and behaviour with less constraints. What do you think about this design ? Maybe I missed something ? :)
Hey, thanks for the suggestion. I'm glad you're excited about BulkInsert!
However, using a module to extend ActiveRecord is a pretty tried-and-true strategy, and is the preferred way to accomplish this kind of thing. Using the inherited callback has hidden gotchas, not least of which is that the inherited callback is invoked as soon as the class is declared, and before any methods are added to the child class. This means that if you're ever trying to override functionality on that child class, you'll have a world of problems using this approach because the functionality you're trying to override hasn't been declared yet.
Also, if another plugin also declares an inherited callback, you suddenly have to worry about chaining that callback cleanly.
Using modules to extend classes is just such a clean, easy, and well-understood strategy for this. Unless there is some critical functionality that is unsupportable using modules, I'm not likely to swap it out for a callback-based approach.
As I said before, the project is pretty cool :)
Thanks for sharing your experience. I'm still mid-level developer. Your explanation is really clear. I have another Gem that uses the inherited callback. I think I gonna move the code in a module.
Thanks again !