2016-09-29 24 views
0

Ruby新手在這裏。在CSV文件中基本上,我有幾個用戶(以下標題):如何使用CSV將登錄功能(用戶名/密碼)添加到我的應用程序

first_name,age,location,gender,phone_number,email,username,password 

我想用戶與他們的用戶名,這將檢查相應的用戶名CSV文件登錄,當它發現用戶名它將向用戶詢問密碼,如果密碼匹配,則會運行'user_mainmenu'變量,然後將用戶帶到用戶主菜單。

def user_login 
print "Enter username: " 
    username_access = $stdin.gets.chomp 
    CSV.foreach('users.csv', headers: true) do |row| 
    if row["@username"] == username_access then 
    @user = User.new(row.to_hash) 
    break 
    end 
    end 
print "Enter password: " 
password_access = $stdin.gets.chomp 
CSV.foreach('users.csv', headers: true) do |row| 
    if row["@password"] == password_access then 
    user_mainmenu 
    break 
    end 
end 
end 

我敢肯定我沒有使用正確的代碼,我只是用紅寶石(不允許在課程中使用的Rails作爲其和我們以後學習)。 因爲大多數涉及Rails,我找不到任何答案。

道歉,如果沒有足夠的信息或如果我不夠清楚,第一次發佈在這裏。

回答

0

您不需要兩次讀取CSV文件。使用CSV#openCSV::Table#new,一個可能會派上用場格式的數據到內存:

def user_login 
    # load CSV 
    csv = CSV::Table.new(CSV.open('users.csv', headers: true)) 

    print "Enter username: " 
    username_access = $stdin.gets.chomp 
    # detect row with this username 
    row = csv.detect { |e| e["username"] == username_access } 
    # immediately throw if no such user 
    raise "No such user" unless row 

    print "Enter password: " 
    password_access = $stdin.gets.chomp 
    raise "Wrong password" unless row["password"] == password_access 

    # everything is fine, logged in, return user 
    User.new(row.to_hash) 
end 
+0

謝謝,看起來像你的是我的更簡化的版本數變化。 – thomasgee

0

本來導師幫我:

def user_login 
login_start 
verified(gets.chomp) 
end 

def verified(input) 
user_row = authentication(input) 
if user_row 
    puts 'Please enter your password:' 
    print "> " 
    password = gets.chomp 
    if user_row['password'] == password 
    user_mainmenu 
    else 
    puts "Incorrect password." 
    sleep 1 
    user_login 
    end 
else 
    failed 
end 
end 

def authentication(username) 
CSV.open('users.csv', headers: true).find { |row| row['username'] == username } 
end 

def failed 
puts "Username not recognised. Please try again." 
sleep(1) 
user_login 
end 

def login_start 
puts "Enter username:" 
print "> " 
end 
+0

很好,你包括你自己的答案,不要讓你的問題在你找到解決方案後「死亡」。好精神!現在...讓你的導師教你如何格式化和縮進代碼;) – Felix

相關問題