Hey friends, I’m working through the Intermediate Ruby tutorials and was given some homework to refactor some code duplication across two controllers. The original controllers looked like so:
class XShoutsController < ApplicationController
def create
content = build_content
shout = current_user.shouts.new(content: content)
if shout.save
# etc..
end
end
private
def build_content; TextShout.new(text_shout_params); end
end
The way I refactored was I created a Service Object(?) called ShoutBuilder
which lives in app/models
. The service object looks like this:
class ShoutBuilder
def initialize user, shout_generic
@shout_generic = shout_generic
@user = user
end
def save
@user.shouts.create(content: @shout_generic)
end
end
class XShoutsController < ApplicationController
def create
shout = ShoutBuilder.new current_user, build_content
if shout.save
# etc..
end
end
private
def build_content; TextShout.new(text_shout_params); end
end
Have I gone about this refactor in the correct way? I feel I did I just wanted to get a second eye on this. Thanks guys!