~singpolyma/sgx-jmp

ref: 4be555de103e992ee7e03feb48b45c1eca917c45 sgx-jmp/lib/payment_methods.rb -rw-r--r-- 849 bytes
4be555deStephen Paul Weber Split logic out into testable objects 1 year, 7 months 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
# 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.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,
			options: to_options
		}.merge(kwargs)
	end

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