Skip to content

Instantly share code, notes, and snippets.

@joshmfrankel
Last active February 23, 2022 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshmfrankel/6ef9881581b7f3fb41f845803d63f1bf to your computer and use it in GitHub Desktop.
Save joshmfrankel/6ef9881581b7f3fb41f845803d63f1bf to your computer and use it in GitHub Desktop.
Ruby: Singelton example of wrapping child method from Parent
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