Sha256: ee425fe4567bd6f88c185e8a4336c007bc7e3794654ff92afb0edc0a726185a4

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module SolidusStripe
  class AddressFromParamsService
    attr_reader :address_params, :user

    def initialize(address_params, user = nil)
      @address_params, @user = address_params, user
    end

    def call
      if user
        user.addresses.find_or_initialize_by(attributes)
      else
        Spree::Address.new(attributes)
      end
    end

    private

    def attributes
      @attributes ||= begin
        default_attributes.tap do |attributes|
          # possibly anonymized attributes:
          phone = address_params[:phone]
          lines = address_params[:addressLine]
          names = address_params[:recipient].split(' ')

          attributes.merge!(
            state_id: state&.id,
            firstname: names.first,
            lastname: names.last,
            phone: phone,
            address1: lines.first,
            address2: lines.second
          ).reject! { |_, value| value.blank? }
        end
      end
    end

    def country
      @country ||= Spree::Country.find_by_iso(address_params[:country])
    end

    def state
      @state ||= country.states.find_by_abbr(address_params[:region])
    end

    def default_attributes
      {
        country_id: country.id,
        city: address_params[:city],
        zipcode: address_params[:postalCode]
      }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
solidus_stripe-4.0.0 app/models/solidus_stripe/address_from_params_service.rb