Home > other >  How to choose object in file.yml and update only this object
How to choose object in file.yml and update only this object

Time:07-19

I have this structure in file.yml

- !ruby/object:Account
  name: Anton
  login: Anton1231
  password: Antonqwe
  age: '37'
  card: []

When i sign_in in account, i can add some card. Question - How can i find object from file where login and password == login, password account in which i sign_in and update only card

CodePudding user response:

require 'yaml'

# assume your class looks something like this
class Account
  attr_reader :name, :login, :password, :age
  attr_accessor :card
end

def read_accounts
  File.open('file.yml') { |f| YAML.load_stream(f) }
end

def write_accounts(accounts)
  File.open('file.yml', 'r ') do |f|
    accounts.each { |a| f.write YAML.dump(a) }
  end
end

def update_card(account, card)
  account.card << card
end

def find_account(accounts, login, password)
  accounts.each do |acct|
    return acct if acct.login == login && acct.password == password
  end
  nil
end

# assume these are set somewhere
@login = 'Anton1231'
@password = 'Antonqwe'
@card = 'a card'

accounts = read_accounts
account = find_account(accounts.first, @login, @password) # accounts.first as accounts is a 2d array
update_card(account, @card) if account
write_accounts accounts

Inspiration from this answer: How to read ruby object in YAML

  • Related