Last active
February 23, 2022 01:22
-
-
Save joshmfrankel/6ef9881581b7f3fb41f845803d63f1bf to your computer and use it in GitHub Desktop.
Ruby: Singelton example of wrapping child method from Parent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module BaseService | |
extend ActiveSupport::Concern | |
class_methods do | |
def call(*args, **keyword_args) | |
service = new | |
def service.result=(result) | |
@result = result | |
end | |
def service.result | |
@result | |
end | |
def service.success? | |
@result.success? | |
end | |
def service.failure? | |
@result.failure? | |
end | |
# This is the magic. We can add operations within the #tap block while | |
# still retaining reference to the original instance of the object | |
service.tap do |service_object| | |
service_object.result = service.call(*args, **keyword_args) | |
end | |
end | |
end | |
end | |
module Users | |
class UpdatePassword | |
include BaseService | |
def call(stuff) | |
# Do some stuff | |
Success(:it_works) | |
end | |
end | |
end | |
# Note we use the class level `call` which utilzes the parent definition | |
# Allows us to utilize class level method as main caller and instance level as entrypoint for calling | |
# By doing this we can wrap the instance level method from the Parent and prepend/append operations around | |
# its result | |
Users::UpdatePassword.call("stuff") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment