Sha256: fa3cd75e0f56e5788ccdf406f12d7d24f8f9c4fe097d43f0f296fd92fa58862f

Contents?: true

Size: 1.36 KB

Versions: 62

Compression:

Stored size: 1.36 KB

Contents

module Workarea
  class User
    module Addresses
      extend ActiveSupport::Concern

      included do
        embeds_many :addresses,
                    class_name: 'Workarea::User::SavedAddress',
                    as: :addressable,
                    cascade_callbacks: true
      end

      def default_billing_address
        addresses
          .select { |a| a.last_billed_at }
          .sort { |a, b| a.last_billed_at <=> b.last_billed_at }
          .last || last_modified_address
      end

      def default_shipping_address
        addresses
          .select { |a| a.last_shipped_at }
          .sort { |a, b| a.last_shipped_at <=> b.last_shipped_at }
          .last || last_modified_address
      end

      def auto_save_billing_address(params)
        address = find_existing_address_or_new(params)
        address.last_billed_at = Time.current
        address.save
      end

      def auto_save_shipping_address(params)
        address = find_existing_address_or_new(params)
        address.last_shipped_at = Time.current
        address.save
      end

      private

      def last_modified_address
        addresses.sort { |a, b| a.updated_at <=> b.updated_at }.last
      end

      def find_existing_address_or_new(params)
        new = SavedAddress.new(params)
        addresses.detect { |a| a.address_eql?(new) } || addresses.new(params)
      end
    end
  end
end

Version data entries

62 entries across 62 versions & 1 rubygems

Version Path
workarea-core-3.5.27 app/models/workarea/user/addresses.rb
workarea-core-3.5.26 app/models/workarea/user/addresses.rb
workarea-core-3.4.45 app/models/workarea/user/addresses.rb
workarea-core-3.5.25 app/models/workarea/user/addresses.rb
workarea-core-3.5.23 app/models/workarea/user/addresses.rb
workarea-core-3.4.44 app/models/workarea/user/addresses.rb
workarea-core-3.5.22 app/models/workarea/user/addresses.rb
workarea-core-3.4.43 app/models/workarea/user/addresses.rb
workarea-core-3.5.21 app/models/workarea/user/addresses.rb
workarea-core-3.4.42 app/models/workarea/user/addresses.rb
workarea-core-3.5.20 app/models/workarea/user/addresses.rb
workarea-core-3.4.41 app/models/workarea/user/addresses.rb
workarea-core-3.5.19 app/models/workarea/user/addresses.rb
workarea-core-3.4.40 app/models/workarea/user/addresses.rb
workarea-core-3.5.18 app/models/workarea/user/addresses.rb
workarea-core-3.4.39 app/models/workarea/user/addresses.rb
workarea-core-3.5.17 app/models/workarea/user/addresses.rb
workarea-core-3.4.38 app/models/workarea/user/addresses.rb
workarea-core-3.5.16 app/models/workarea/user/addresses.rb
workarea-core-3.4.37 app/models/workarea/user/addresses.rb