-
Notifications
You must be signed in to change notification settings - Fork 19
Backend Pattern Delegation
Delegation is a pattern that reduces code repetition by allowing an object to pass calls for a method to another object, the delegate.
N/A
There are a few common ways to delegate method calls that we use in Caseflow:
Rails provides a delegate
method that allows you to delegate methods to a related object. This pattern
is commonly used in our models to call methods on related objects and avoid
declaring redundant methods.
class Hearing < ApplicationRecord
...
delegate :available_hearing_locations, :closest_regional_office, :advanced_on_docket?, to: :appeal
delegate :external_id, to: :appeal, prefix: true
...
end
The prefix
parameter can be used to prefix the new method name to avoid
method naming collisions. 1
The SimpleDelegator
class is an easy way to delegate all methods of an object to a second object. Using
SimpleDelegator
is a good way to add additional functionality onto a class without adding to the class itself.
delegate
is preferred to SimpleDelegator
when you only need to delegate a subset of methods to the second object.
- 1: https://apidock.com/rails/Module/delegate
- https://ruby-doc.org/stdlib-2.5.1/libdoc/delegate/rdoc/Delegator.html
- https://ruby-doc.org/stdlib-2.5.1/libdoc/delegate/rdoc/SimpleDelegator.html
Pattern | Description |
---|