0

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

Smile
  • 21
  • 6
  • 2
    You can use YAML Store from the standard library, but you'll still have to re-write the whole file. YAML files are not databases; pragmatically, you can't write only parts of them, unless you're working with fixed-length fields at the byte level. – Todd A. Jacobs Jul 12 '22 at 16:48
  • Thx, i think the same! @Todd A. Jacobs – Smile Jul 12 '22 at 16:53
  • 2
    Yeah, but you can load the YAML file as a Ruby object and then edit the specific info inside the object that you care about. Then dump it out as YAML again. That way your code is only modifying part of the object instead of reassembling the whole thing. – David Grayson Jul 12 '22 at 17:06

1 Answers1

0
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

MatzFan
  • 877
  • 8
  • 17