Paul Thompson Paul Thompson - 2 months ago 15
Ruby Question

Ruby: creating a case statement that checks csv file for string to authenticate user (terminal only)

I apologies if this is simple but I'm just starting out. Any constructive help welcome.

Problem:


  • Trying to create authentication from ruby terminal to CSV.

  • I'd like to create clean (and as short as possible) loop statement that goes to csv file checks the top row for header "pin" and then checks the gets.chomp entry against that to authenticate.

    require 'csv'

    class Menu

    def self.login
    system "clear"
    puts "Welcome to Hip-Bikes & Coffee"
    puts "Please login with your pin:"
    print "> "
    customer_pin = gets.chomp

    verified = authentication(customer_pin)
    end

    def self.authentication(customer_pin)

    case
    when CSV.foreach('customers.csv', headers: true) { |row| ["pin"] == login.verified }
    puts verified
    else
    puts "login failed. Please try again in 3 seconds..."
    sleep(3.0)
    self.login


Answer

This should work for you

UPD

 require 'csv'

class Menu
  class << self
    def login
      login_start
      verified(gets.chomp)
    end

    def verified(input)
      if authentication(input)
        puts 'verified'
      else
        failed
      end
    end

    def authentication(customer_pin)
      CSV.foreach('customers.csv', headers: true).any? { |row| row['pin'] == customer_pin }
    end

    def failed
      puts "login failed. Please try again in 3 seconds..."
      sleep(3.0)
      login
    end

    def login_start
      system "clear"
      print "Welcome to Hip-Bikes & Coffee\nPlease login with your pin:\n> "
    end
  end
end