...

/

Sketch Business Logic and Define the Seam

Sketch Business Logic and Define the Seam

Learn how to define business logic on our Rails application.

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.

Press + to interact
# 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 ...