23
loading...
This website collects cookies to deliver better user experience
The service design pattern breaks down a program into its functional constituents. Each service object completes one task, such as running payment for a customer, completing a bank transaction, etc.
You can use the interactor design pattern to split a large task into a series of small, inter-dependent steps. If any of the steps fail, the flow stops, and a relevant message appears about why the execution failed.
class AuthenticateUser
include Interactor
def call
if user = User.authenticate(context.email, context.password)
context.user = user
context.token = user.secret_token
else
context.fail!(message: "authenticate_user.failure")
end
end
end
class AuthenticateUserService < BaseService
def perform
if (user = User.authenticate(context.email, context.password))
success_result(status: :success, message: nil, data: user) # this method as and error_result are implemented in BaseService
else
error_result(status: :error, message: user.errors, data: {})
end
end
end
The Decorator pattern adds new functionality to an existing object by wrapping it with additional objects containing the new features. This helps to modify an instance of a class for extra features and not define new static subclasses in the code.
The Presenter design pattern aims to isolate view rendering logic from the controller and model and encapsulate it into a reusable component. It makes the controller and models leaner and enhances code readability.
class PostPresenter
def initialize(post)
@post = post
end
def image
@post.image? ? @post.image.url : 'no-image.png'
end
# similary define other methods with their logic
end
class Car
def roof
"fixed"
end
end
class ConvertibleDecorator < SimpleDelegator
def roof
"collapsible"
end
def self.decorate(car)
new(car)
end
private
def model
__getobj__
end
end
#using
basicCar1 = Car.new()
basicCar2 = Car.new()
basicCar1 = ConvertibleDecorator.decorate(basicCar1)
puts(basicCar1.roof) # => collapsible
puts(basicCar2.roof) # => fixed
class Car
def roof
"fixed"
end
end
module ConvertibleDecorator
def roof
"collapsible"
end
end
#using
basicCar1 = Car.new()
basicCar2 = Car.new()
basicCar1 = basicCar1.extend ConvertibleDecorator
puts(basicCar1.roof) # => collapsible
puts(basicCar2.roof) # => fixed
Services
in a project and try to put all new classes there however it can be QueryObject or ValueObject).