lundi 29 juillet 2019

run factorybot and create an array of json with specific values

I am learning Ruby on rails and stuck on this issue.

I have to use a FactoryBot, and from the generated value, take only 2 values out and write into an array of JSON. I also need it pretty printed.

So far I got till this

   test = FactoryBot.create(:test)

   foo = {
      'a' => test.id,
      'b' => test.email
    }

    companies_json = []
    puts "hello" << foo.to_json
    out_file = File.open("test.data.ts", "w+") do |f|
       companies_json << foo.to_json
       f.puts("DATA =")
       f.puts(JSON.pretty_generate(companies_json))
       f.close
    end

When I do this, the file gets printed like this

   DATA =
  [
    "{\"a\":78,\"b\":\"richardprice@kertzmann.info\"}"
  ]

which is not pretty :-(

Plus now, If I want to loop through the factorybot and generate 10 data and write it like this,

   DATA =
  [
      {
        a : 78
        b : test@test1.com
      },
      {
        a : 79
        b : test@test2.com
       },
       ...
    ]

How do I do this. TIA. Have been struggling on this for a while :-(

Aucun commentaire:

Enregistrer un commentaire