开发者

How to write to a csv file through ftp in rails 3?

开发者 https://www.devze.com 2023-03-20 16:46 出处:网络
I am trying to write to a csv file through ftp. Here is what i have so far: require \'net/ftp\' require \'csv\'

I am trying to write to a csv file through ftp. Here is what i have so far:

require 'net/ftp'
require 'csv'

users = User.users.limit(5)
开发者_Go百科
csv_string = CSV.generate do |csv|
  csv << ["email_addr", "first_name", "last_name"]

  users.each do |user|
    new_line = [user.email, user.first_name, user.last_name]
    csv << new_line
  end
end

csv_file = CSV.new(csv_string)

ftp = Net::FTP.new('**SERVER NAME**')
ftp.login(user = "**USERNAME**", passwd = "**PASSWORD**")
ftp.storbinary('STOR ' + 'my_file.csv', csv_file)
ftp.quit()

I get the error "wrong number of arguments (2 for 3)". When i change the line to ftp.storbinary('STOR ' + 'my_file.csv', csv_file, 1024) it says "wrong number of arguments (1 for 0)". I've also tried using storlines instead, but that gave me errors also. Does anybody have any ideas on how to handle this?


In the line

ftp.storbinary('STOR ' + 'my_file.csv', csv_file)

csv_file needs to be an actual File object, not another kind of object.

> (from ruby core)

storbinary(cmd, file, blocksize, rest_offset = nil) { |data| ... }


Puts the connection into binary (image) mode, issues the given server-side command (such as "STOR myfile"), and sends the contents of the file named file to the server. If the optional block is given, it also passes it the data, in chunks of blocksize characters.


require 'net/ftp'

Login to the FTP server

ftp = Net::FTP.new('ftp.sample.com', 'test', 'pass')

OR

ftp = Net::FTP.new('ftp.sample.com')
ftp.login('test', 'pass')

Switch to the desired directory

ftp.chdir('source/files')

Get the file we need and save it to our 'ftp_photos' directory

ftp.getbinaryfile('photos_2009-03-29.zip', 'ftp_photos/photos.zip')

We're done, so we need to close the connection

ftp.close

http://travisonrails.com/2009/03/29/ruby-net-ftp-tutorial

This will help you.

0

精彩评论

暂无评论...
验证码 换一张
取 消