Undefined method error for CSV class - csv

I am following this tutorial for exporting CSV:
http://railscasts.com/episodes/362-exporting-csv-and-excel
However, I am getting an "undefined method '<<' for CSV:Class
The code snippet being highlighted in the error is:
def self.to_csv
CSV.generate do |csv|
CSV << column_names #this row is highlighted in the error
all.each do |opportunity|
CSV << product.attributes.value_at(*column_names)
end
end
end
My config/application:
require 'rails/all'
require 'csv'
Thanks!
Please note that I am only 2:30 into the video.

In the Fifth line
CSV << product.attributes.value_at(*column_names)
change it to
CSV << product.attributes.values_at(*column_names)
Now it'll work fine. Hope this helps.

Related

Octave - error reading data with textscan function

I am trying to read data of the following format with textscan:
date,location,new_cases,new_deaths,total_cases,total_deaths
2019-12-31,Afghanistan,0,0,0,0
2020-01-01,Afghanistan,0,0,0,0
2020-01-02,Afghanistan,0,0,0,0
2020-01-03,Afghanistan,0,0,0,0
2020-01-04,Afghanistan,0,0,0,0
...
(Full data file available here: https://covid.ourworldindata.org/data/ecdc/full_data.csv)
My code is:
# Whitespace replaced with _
file_name = "full_data.csv";
fid = fopen(file_name, "rt");
data= textscan(fid, "%s%s%d%d%d%d", "Delimiter", ",", "HeaderLines", 1, ...
"ReturnOnError", 0);
fclose(fid);
Text scan terminates with an error:
error: textscan: Read error in field 3 of row 421
Row 421 is the center row in the example below:
2020-01-12,Australia,0,0,0,0
2020-01-13,Australia,0,0,0,0
2020-01-14,Australia,0,0,0,0
2020-01-15,Australia,0,0,0,0
2020-01-16,Australia,0,0,0,0
2020-01-17,Australia,0,0,0,0
2020-01-18,Australia,0,0,0,0
I've checked the row it complains about and there is nothing different from the example above. I've replaced all spaces in the file with underscores too. Am I doing something wrong with textcan?

Trouble parsing file obtained from Dir.glob

I am new to ruby. Running into error while trying to parse file obtained from Dir.glob command using JSON.parse()
require 'json'
Dir.glob('**/*/.json').each do |f| # find all the .json file and loop each file
puts f
data = JSON.parse(f)
if data['Apple'].nil?
puts "skipping file #{f} as it does not have Apple"
next
end
parsed_key= File.dirname(data['Apple'][0]['red'][0]['key'])
puts parsed_key
end
`parse': 767: unexpected token at 'xyz/abc/config.json' (JSON::ParserError)
f there is just the path, a String. If you want the contents of the file you'll need to read it first, data = JSON.parse(File.read(f))

Cannot send base64 String to PubNub

I am using PyCamera module of Raspberry Pi to capture an image and store as .jpg.
first encoding the image using base64.encodestring(). but while sending encoded string to PubNub server, I get error on my_publish_callback as
('ERROR: ', 'Expecting value: line 1 column 1 (char 0)')
('ERROR: ', JSONDecodeError('Expecting value: line 1 column 1 (char 0)',))
I have tried using base64.b64encode() but still get the same errors. I have tried the script in python 2 and 3;
def my_publish_callback(envelope, status):
if not status.is_error():
pass # Message successfully published to specified channel.
else:
#print("recv: ", envelope)
print("ERROR: ", status.error_data.information)
print("ERROR: ", status.error_data.exception)
def publish(channel, msg):
pubnub.publish().channel(channel).message(msg).async(my_publish_callback)
def captureAndSendImage():
camera.start_preview()
time.sleep(2)
camera.capture("/home/pi/Desktop/image.jpg")
camera.stop_preview()
with open("/home/pi/Desktop/image.jpg", "rb") as f:
encoded = base64.encodestring(f.read())
publish(myChannel, str(encoded))
I am not able to find or print full error traceback so that I can get some more clues about where the error is occurring. But it looks like PubNub is trying to parse the data in JSON, and its failing.
I realized the .jpg file size is 154KB, whereas PubNub max packet size is 32KB, so that should clearly say it all. PubNub recommends to send large messages by splitting them and re-arranging them in subscriber-end. Thanks #Craig for referring to that link, Its useful though support.pubnub.com/support/discussions/topics/14000006326

JSON to CSV write data to csv file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a small script:
require "csv"
require "json"
puts "JSON file name (include extension) ->"
jsonfile = gets.chomp
json = JSON.parse(File.open(jsonfile).read)
#puts json.first.collect {|k,v| k}.join(',')
puts json.collect {|node| "#{node.collect{|k,v| v}.join(',')}\n"}.join
CSV.open("generated.csv", "wb") do |csv|
csv << json.collect {|node| "#{node.collect{|k,v| v}.join(',')}\n"}.join
end
In the terminal it shows like this:
Missing: [User],{"error"=>[{"Something"=>"", "errno"=>"somthing", "de"=>"smoehting", "pe"=>"error", "errorMessage"=>"Missing "}], "data"=>nil}
Missing: [User],{"error"=>[{"Something"=>"", "errno"=>"somthing", "de"=>"smoehting", "pe"=>"error", "errorMessage"=>"Missing "}], "data"=>nil}
I need to output each row into a seperate row in a csv file. The above is what im trying to do to write it to csv, but it does not work
Your first mistake in your code is that you call << only one time. Each << creates one line, so you have to call << method n-times, where n is a number of lines.
Your second mistake is that you concatenate the array elements and try to pass a string as a <<'s argument. Each <<'s argument should be an array.
Summarizing, to create a CSV file containing two lines:
# my.csv
1,2,3
4,5,6
you should write:
CSV.open("my.csv", "wb") do |csv|
csv << [1, 2, 3]
csv << [4, 5, 6]
end
Similarly, to achieve your desired effect, try to rewrite your code as:
CSV.open("generated.csv", "wb") do |csv|
json.each do |node|
csv << node.collect { |k,v| v }
end
end

Rails: Creating a csv file in a rake task - can't access a classes database column_names

I am struggling to create a simple rake task which will generate a csv dump of the database table "baselines".
task :send_report => :environment do
path = "tmp/"
filename = 'data_' + Date.today.to_s + '.csv'
Baseline.all.each do
CSV.open(path + filename, "wb") do |csv|
csv << Baseline.column_names
Baseline.all.each do |p|
csv << p.attributes.values_at(*column_names)
end
end
end
end
I am getting the error
undefined local variable or method `column_names' for main:Object
I am completely unclear why this is....Baseline.column_names will work in the console, in a view etc etc.
Any thought would be appreciated.
You're specifying Baseline.column_names in the first case, but just column_names on your values_at call. That defaults to the main context where no such method exists. It must be called against a model.
Make those two consistent, Baseline is required in both cases.