Ruby’s Prepend: How is it useful?

And then manually invoke it in all the methods.class SecondBridge def get_address validate_supported_currency # do the things to get address end def balance validate_supported_currency # do the magic end def validate_supported_currency raise Exceptions::UnsupportedCurrencyError if conditions_not_fulfilled endendThis is a stressful solution, because it requires me to repeatedly define validate_supported_currency and then remember to make sure it’s called in every method.One other option would be to define a Bridge module that defines validate_supported_currency and then I could include that in every class that’s meant to be a Bridge.module Bridge def validate_supported_currency raise Exceptions::UnsupportedCurrencyError if conditions_not_fulfilled endendclass FirstBridge include Bridge def get_address validate_supported_currency # do the things to get address end def balance validate_supported_currency # do the magic end endThis solves the problem of having to define validate_supported_currency repeatedly but I still have to remember to invoke it in every single method of every Bridge class that I create.To solve that, I decided to use prepend..This means that I first needed to make some additions to the Bridge module.module Bridge def get_address validate_supported_currency super end def balance validate_supported_currency super end def validate_supported_currency raise Exceptions::UnsupportedCurrencyError if conditions_not_fulfilled endendsuper simply calls the method of the same name in the parent class of the current class.Let’s look at get_address, what this means is that after calling validate_supported_currency Ruby will try to see if our current object has a parent class/module with get_address defined and then invoke it if it does..You can read more about super and overriding methods here.So how do we get this to work in our actual Bridge classes?.Simple:class AnotherBridge prepend Bridge def get_address # do the tings fam end def balance # magic time end endAnd that’s it!.By simply prepending Bridge, every time get_address or balance is called, validate_supported_currency will be called first before running the code that’s actually defined in the methods themselves.This is because (as explained above) prepend makes AnotherBridge the parent class of Bridge.As such, when get_address is called, the Ruby interpreter will invoke the get_address as is defined in Bridge first..And this invokes validated_supported_currency.Then we call super in the next line which then invokes the get_address defined in AnotherBridge (the parent class).That’s all for today!.Go forth and prepend!. More details

Leave a Reply