Created
February 11, 2022 17:59
-
-
Save marclerodrigues/0c8bf2776de6c6c6ac07b0f4c2a056d1 to your computer and use it in GitHub Desktop.
Ruby Models + Services
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Phone < ApplicationRecord | |
| belongs_to :contact | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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