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.rbclass WidgetCreatordef create_widget(widget)widget.widget_status = WidgetStatus.firstwidget.saveResult.new(created: widget.valid?, widget: widget)endclass Resultattr_reader :widgetdef initialize(created:, widget:)@created = created@widget = widgetenddef created?@createdendendend
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 ...