~singpolyma/sgx-jmp

ref: 35f09f18dc79dcf2d3c73db6d7a9a652507171c9 sgx-jmp/lib/payment_methods.rb -rw-r--r-- 959 bytes
35f09f18Stephen Paul Weber Allow getting default payment method, not just index 2 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true

class PaymentMethods
	def self.for_braintree_customer(braintree_customer)
		methods = braintree_customer.payment_methods
		if methods.empty?
			Empty.new
		else
			new(methods)
		end
	end

	def initialize(methods)
		@methods = methods
	end

	def fetch(idx)
		@methods.fetch(idx)
	end

	def default_payment_method
		@methods.find(&:default?)
	end

	def default_payment_method_index
		@methods.index(&:default?)&.to_s
	end

	def to_options
		@methods.map.with_index do |method, idx|
			{
				value: idx.to_s,
				label: "#{method.card_type} #{method.last_4}"
			}
		end
	end

	def to_list_single(**kwargs)
		{
			var: "payment_method",
			type: "list-single",
			label: "Credit card to pay with",
			required: true,
			value: default_payment_method_index,
			options: to_options
		}.merge(kwargs)
	end

	class Empty
		def default_payment_method; end

		def to_list_single(*)
			raise "No payment methods available"
		end
	end
end