Skip to content

Instantly share code, notes, and snippets.

@yukas
Last active March 24, 2017 13:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukas/ea1872f9a2d093e740b54d64ed1c4060 to your computer and use it in GitHub Desktop.
Save yukas/ea1872f9a2d093e740b54d64ed1c4060 to your computer and use it in GitHub Desktop.
Cleaner controller with service object
# A controller
module Api::V2
module Controllers::ZonesRecords
class Create
include Hanami::Action
def call(params)
@zone = DomainFinder.find!(
params[:zone_id], authentication_context).zone
@result = RecordCreateCommand.execute(command_context, @zone,
params[:type], ZoneRecordParams.new(params, [:regions]))
@record = @result.data
if @result.successful? && !@result.exists
render Serializers::RecordSerializer.new(@record), 201
elsif @result.exists
error(400, I18n.t("api.zone_records.already_exists"))
else
render Serializers::ErrorSerializer.new(@result.error, @record), 400
end
end
end
end
end
# A cleaner controller
module Api::V2
module Controllers::ZonesRecords
class Create
include Hanami::Action
def call(params)
zone_record_creator = ZoneRecordCreator.new(params)
zone_record_creator.create_zone_record
if zone_record_creator.zone_record_created_successfully?
render Serializers::RecordSerializer.new(zone_record_creator.zone_record), 201
elsif zone_record_creator.zone_record_already_exists?
error 400, I18n.t("api.zone_records.already_exists")
else
render Serializers::ErrorSerializer.new(zone_record_creator.error, zone_record_creator.zone_record), 400
end
end
end
end
end
# Service
class ZoneRecordCreator
attr_reader :params
attr_reader :zone_record, :errors
def initialize(params)
@params = params
end
def create_zone_record
validate_params
if params_valid?
find_domain_zone
create_the_record
end
end
def zone_record_created_successfully?
# ...
end
def zone_record_already_exists?
# ...
end
private
attr_reader :domain_zone
def validate_params
# ...
end
def params_valid?
# ...
end
def find_domain_zone
domain_zone_finder = DomainZoneFinder.new
domain_zone_finder.find_domain_zone
@domain_zone = domain_zone_finder.domain_zone
end
def create_the_record
# ...
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment