Class: Braintree::InputHandler
- Inherits:
-
Object
- Object
- Braintree::InputHandler
- Defined in:
- lib/braintree.rb
Instance Method Summary collapse
- #add(args) ⇒ Object
- #charge(args) ⇒ Object
- #credit(args) ⇒ Object
- #display_balances ⇒ Object
- #find_user_by_name(name) ⇒ Object
-
#initialize ⇒ InputHandler
constructor
A new instance of InputHandler.
- #process_input(line, i) ⇒ Object
- #valid_cc?(cc) ⇒ Boolean
- #validate(args) ⇒ Object
Constructor Details
#initialize ⇒ InputHandler
Returns a new instance of InputHandler.
6 7 8 9 10 11 |
# File 'lib/braintree.rb', line 6 def initialize @data = [] @salt = Time.now.to_i.to_s @secret_key = 'braintree' @iv = OpenSSL::Cipher::Cipher.new('aes-256-cbc').random_iv end |
Instance Method Details
#add(args) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/braintree.rb', line 35 def add(args) return false unless valid_cc?(args[2]) new_user = { name: args[1], cc: encrypted_value = Encryptor.encrypt(args[2], :key => @secret_key, :iv => @iv, :salt => @salt), limit: args[3][1..-1].to_i, balance: 0 } @data << new_user unless @data.include?(new_user) end |
#charge(args) ⇒ Object
52 53 54 55 56 57 58 |
# File 'lib/braintree.rb', line 52 def charge(args) user = find_user_by_name(args[1]) unless user.nil? new_balance = user[:balance] + args[2][1..-1].to_i user[:balance] = new_balance unless new_balance > user[:limit] end end |
#credit(args) ⇒ Object
47 48 49 50 |
# File 'lib/braintree.rb', line 47 def credit(args) user = find_user_by_name(args[1]) user[:balance] = user[:balance] - args[2][1..-1].to_i unless user.nil? end |
#display_balances ⇒ Object
80 81 82 |
# File 'lib/braintree.rb', line 80 def display_balances @data.each { |d| puts "#{d[:name]} $#{d[:balance]}" } end |
#find_user_by_name(name) ⇒ Object
60 61 62 |
# File 'lib/braintree.rb', line 60 def find_user_by_name(name) @data.find { |i| i[:name] == name } end |
#process_input(line, i) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/braintree.rb', line 19 def process_input(line, i) args = line.split(" ") line_num = i + 1 case args[0] when "Add" puts "Invalid credit card number on line #{line_num}" unless add(args) when "Credit" credit(args) when "Charge" charge(args) else puts "Invalid command on line #{line_num}" return false end end |
#valid_cc?(cc) ⇒ Boolean
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/braintree.rb', line 64 def valid_cc?(cc) nums = cc.chars.map(&:to_i).reverse sum = 0 nums.each_with_index do |n, i| if i.odd? n *= 2 n = (n - 10) + 1 if n >= 10 end sum += n end (sum % 10) == 0 end |
#validate(args) ⇒ Object
13 14 15 16 17 |
# File 'lib/braintree.rb', line 13 def validate(args) raise ArgumentError, 'Argument with file path is necessary.' if args.empty? raise ArgumentError, 'Only one argument needed.' if args.length > 1 raise ArgumentError, 'File does not exist at given path.' unless File.file?(args[0]) end |