How to export a Ruby Array from my Heroku console into CSV?

后端 未结 10 907
悲&欢浪女
悲&欢浪女 2021-02-02 11:17

I am looking to export an array from my heroku console into a local CSV file.

In my current situation, I have a daily rake task which looks for tweets talking about my a

相关标签:
10条回答
  • 2021-02-02 11:22

    You can't access your local filesystem from the heroku console. One option is to use Tee. Tee sends the output to both STDOUT and a file, so you can have a local log of everything that was printed.

    heroku run console | tee output.txt
    
    0 讨论(0)
  • 2021-02-02 11:22

    I tried Tee as suggested, but for some reason it always got stuck after the output of

    Running `console` attached to terminal... up, run.1
    

    So I ended up emailing the csv content for me in the text format email body. If you already have emailing set up, that can be easy solution too.

    0 讨论(0)
  • 2021-02-02 11:25

    You can also use rails runner to run a line of code or three on heroku and pipe (or tee) the results to a file:

    heroku run rails runner \'Tweet.all.to_csv\' -a my-app-name | all_tweets.csv
    

    You can disable rails logging if that's showing up in your file and trim the top of the file if you're getting startup logging like "Running `rails runner`" in your file, but that should be easy to do.

    0 讨论(0)
  • 2021-02-02 11:27

    FWIW you could pretty easily puts a string with commas and newlines and then copy paste into your text editor and save as .csv, though "all of the tweets" might be a little unwieldy.

    tweets = Tweet.all
    @string = String.new()
    @string << Tweet.last.attributes.keys.join(", ") + "\n" # "header" row with attribute names
    
    
    tweets.each do |t|
      @string << t.attributes.values.join(", ") + "\n"
    end
    
    puts @string #will output string with \n newline which you could then copy paste into your editor and save as a csv
    
    0 讨论(0)
  • 2021-02-02 11:30

    You can shell out to SCP:

    my_data = "hello world"
    File.write("tmp/data", my_data)
    `scp tmp/data me@some-server:`
    

    It may prompt you about the server being unknown and ask for a password.

    0 讨论(0)
  • 2021-02-02 11:31

    Thanks for your help guys, I followed this railscast http://railscasts.com/episodes/362-exporting-csv-and-excel and added a way to export to excel from an admin panel.

    Thanks again.

    0 讨论(0)
提交回复
热议问题