Search⌘ K
AI Features

Sketch Business Logic and Define the Seam

Explore how to create a service class to hold business logic separately from controllers, ensuring cleaner code and easier maintenance. Understand the importance of managing data conversion in the controller and learn to define a clear interface between the UI and business operations. This lesson helps you implement a sustainable Rails app design and prepare for effective system testing.

We'll cover the following...

Let’s create the service class that will hold our business logic. This will codify the contract between our code and the controller. We should be able to do this without breaking the system test. Once that’s done, we can then start to build out the real business logic.

We’ll call the service WidgetCreator, and it’ll go in app/services/ as widget_creator.rb. We’ll need to create the app/services directory. We’ll give it one method, create_widget, and it’ll accept a Widget instance initialized with the parameters received from the UI.

Ruby
# app/services/widget_creator.rb
class WidgetCreator
def create_widget(widget)
widget.widget_status = WidgetStatus.first
widget.save
Result.new(created: widget.valid?, widget: widget)
end
class Result
attr_reader :widget
def initialize(created:, widget:)
@created = created
@widget = widget
end
def created?
@created
end
end
end

This may seem like a lot of code has been introduced just to call valid? on an Active Record, but it will make a lot more sense when we put all the actual ...