Skip to content

Instantly share code, notes, and snippets.

@marclerodrigues
Created February 11, 2022 17:59
Show Gist options
  • Select an option

  • Save marclerodrigues/0c8bf2776de6c6c6ac07b0f4c2a056d1 to your computer and use it in GitHub Desktop.

Select an option

Save marclerodrigues/0c8bf2776de6c6c6ac07b0f4c2a056d1 to your computer and use it in GitHub Desktop.
Ruby Models + Services
class Phones::Creator
attr_reader :phone_params
delegate :contact, to: :phone
def initialize(phone_params)
@phone_params = phone_params
end
def call
if phone.save
set_main_phone
end
phone.persisted?
end
def phone
@phone = Phone.new(phone_params)
end
private
def set_main_phone
if phone.main?
Phones::MakeDefault.new(phone, contact).call
end
end
end
class Phones::MakeDefault
delegate :phones, to: :contact
def initialize(contact, phone)
@contact = contact
@phone = phone
end
def call
phones.where.not(id: phone.id).update(main: false)
end
private
attr_reader :contact, :phone
end
class Phone < ApplicationRecord
belongs_to :contact
end
class PhonesController < ApplicationController
def create
@creator = Phones::Create.new(phone_params).call
if @creator
render json: { success: true, phone: @creator.phone }
else
render json: { success: false, errors: @creator.phone.errors }
end
end
private
def phone_params
params.require(:phone).permit(:main, :number, :contact_id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment