Ruby undefined method `copy_stream' for IO:Class - ruby

I want to download almost 2GB size zip files (builds) on the target server. For that I have written the following piece of code:
def download_file(src, dest, build_name)
begin
if !File.file?("#{dest}/#{build_name}")
$LOG.debug "#{dest}/#{build_name} does not exist"
$LOG.info "Downloading #{build_name} to #{dest}"
destination = "#{dest}/#{build_name}"
download = open(src)
IO.copy_stream(download, destination)
$LOG.info "Downloading #{build_name} completed succesfully.\n"
rescue => e
puts e
end
end
But it is giving the following error message:
undefined method `copy_stream' for IO:Class
Need help in fixing this. Thanks in advance.

Related

undefined method `+' for nil:NilClass (NoMethodError) ruby

trying to build a pptx to scorm converter. I get an error NoMethodError Undefined method `+' for NilClass. I guess it may be due to a defined method. any idea on how i can remove this error ?
dir = ARGV.shift
dest = ARGV.shift
pptx = dir + "/presentation.pptx"
lis = []`enter code here`
STDERR.puts "Copy template => #{dest}"
FileUtils.cp_r "template", dest
Dir["#{dir}/*.PNG"].each do |file|
STDERR.puts "Copy #{file} => #{dest}/img"
FileUtils.cp file, "#{dest}/img/"
STDERR.puts "Creating thumb #{file} => #{dest}/img/thumb"
name = file.split(/\//).last
system "/usr/bin/convert", "-scale", "200x", file, "#{dest}/img/thumb/#{name}"
lis.push name
end
ordered = lis.sort_by { |x| x[/\d+/].to_i }
DIR is nil
If you debug your code as follows:
puts dir.nil? # true
So, in order to run this code you must provide the ruby shell with 2 arguments, as follows:
ruby test.rb DIRECTORY_NAME DESTINATION_NAME

Accessing the Receiving Object that Throws an Exception

While debugging a really strange issue with ActionMailer, I came to realize I didn't know how to access an object that was creating the exception. Not the exception, but the object itself.
begin
AppMailer.send_invoice(hostel_resident).deliver_later
flash[:success] = "Your invoice was sent successfully!"
rescue => msg
# display the system generated error message
flash[:error] = "#{msg}"
end
NoMethodError: undefined method `disposition_type' for #<Mail::UnstructuredField:0x009g71c2a68258>
This code works great to catch any exceptions and print the message.
However, how do I get ahold of the <Mail::UnstructuredField:0x009g71c2a68258> object? I'd like to be able to play around with this guy, read messages inside it, and just generally have access to it.
This has to be possible, but inspect doesn't help, cause is no use and backtrace just shows you where it happened. I need that object though, the receiver of the nonexistent method.
Thanks!
actionmailer (4.2.4)
mail (2.6.3)
Seems like you're using mail gem. This is a known issue which is already reported in the GitHub. See #851.
Try using different version of the gem, something in 2.6 series.
This seems to work, using receiver on NameError (which NoMethodError is a child of)
obj = Object.new
puts obj.to_s
begin
obj.do_something
rescue NoMethodError => e
puts e.message
puts e.receiver
end
# #<Object:0x007fa5ac84da88>
# undefined method `do_something' for #<Object:0x007fa5ac84da88>
# #<Object:0x007fa5ac84da88>
This seems to require ruby >= 2.3, to do this for < 2.3, AFAIK you have to do something like this (not tested in older rubies, but should work):
class MyNoMethodError < NoMethodError
attr_accessor :my_receiver
end
obj = Object.new
puts obj.to_s
begin
begin
obj.do_something
rescue NoMethodError => e
# rescue the exception and wrap it in the method that caused it, using `self` instead of `obj`
error = MyNoMethodError.new(e)
error.my_receiver = obj
raise error
end
rescue MyNoMethodError => c
puts c.inspect # custom exception stuff
puts c.cause.inspect # original exception stuff
puts c.my_receiver
end
# #<Object:0x007f884e846d58>
# #<MyNoMethodError: undefined method `do_something' for #<Object:0x007f884e846d58>>
# #<NoMethodError: undefined method `do_something' for #<Object:0x007f884e846d58>>
# #<Object:0x007f884e846d58>

Getting undefined error in mass text app

I'm creating a app that sends mass texts using a JSON file with the numbers and names. Every time I test load the app in IRB I get the error:
NameError: undefined local variable or method `data_from_file' for main:Object
from /home/qc/tep/Coding Stuff/Ruby/text app/main.rb:14:in `contacts_from_file'
I understand what the error means, but I don't understand why I'm getting the error, here's the source code:
require 'json'
def sanatize(numbers)
"+1" + number.gsub(/^1|\D/, "")
end
def numbers_from_file
file = open('numbers.json').read
JSON.parse(file)
end
def contacts_from_file
contacts= { }
data_from_file['feed']['entry'].each do |entry|
name = entry['gsx$name']['$t']
number = entry['gsx$number']['$t']
contacts[sanatize(number)] = name
end
contacts
end
def contact_numbers
contacts_from_file.keys
end
def contact_name
contacts_from_file[number]
end
And here's the JSON file:
{
'1**********' => 'Big Bird'
'1**********'} => 'Josh'
}
If anybody could help me and tell me why the data_from_file is "undefined" it would be extremely helpful, thank you ahead of time.
You never define data_from_file, you just try to read from it in the contects_from_file method.
Perhaps you meant numbers_from_file instead of data_from_file?

NilClass# failed with TypeError: nil is not a symbol

I am unable to send emails. i have already tried the following:
Converting type of handler from text to long text does'nt work as i am using postgres.
I have also tried restarting my workers and delayed jobs
and my delayed job is version is 3.0.1.
I am having problem on the line:
Notifier.delay.delivery_alert(u)
and my delivery_alert method is
def delivery_alert(user)
#user = user
#deliveries = #user.issues.includes(:copy => [:rentable]).current.by_last_status("to_be_delivered").map(&:copy).map(&:rentable)
#returns = #user.issues.includes(:copy => [:rentable]).current.by_last_status("marked_for_return").map(&:copy).map(&:rentable)
mail(:to => #user.email)
end
While on localhost i am getting the error:
[Worker(host:ubuntu pid:12169)] Class#delivery_alert failed with NoMethodError: undefined method `delivery_alert' for # - 5 failed attempts
for which i have added a patch in my lib folder
require 'yaml'
module Delayed
module Backend
module Base
def payload_object
YAML::ENGINE.yamler = 'psych'
#payload_object ||= YAML.load(self.handler)
rescue TypeError, LoadError, NameError, ArgumentError => e
raise DeserializationError,
"Job failed to load: #{e.message}. Handler: #{handler.inspect}"
end
end
end
class PerformableMailer
def perform
double = object.is_a?( String ) ? object.constantize : object
double.send(method_name, *args).deliver
end
end
end
by taking reference of
https://gist.github.com/oelmekki/2181381
but still my email are not going. Thanks in advance?

Variables not recognized within Rescue in Ruby

I have the following code:
rescue Timeout::Error, StandardError => e
puts "Caught exception: #{e.message}".red
log.puts("#{e.backtrace}")
email_ids_all.each do |email_delete|
call= "/api/v2/emails/#{email_delete}/"
......
Before this rescue piece I have defined log and email_ids_all. However, neither of these are recognized within the ruby script. If i do this:
rescue Timeout::Error, StandardError => e
File.open(rescuelogfile, 'w') do |log| #setup log to write response codes.
puts "Caught exception: #{e.message}".red
log.puts("#{e.backtrace}")
email_ids_all.each do |email_delete|
call= "/api/v2/emails/#{email_delete}/"
....
log works fine, which makes sense. It would take a lot of writing to redefine the email_ids_all array and other variables contained inside my rescue block.
Is there anyway to allow variables to be recognized inside the rescue? Basically my code is laid out like this:
begin
#some code
rescue
#above code
end
I am using ruby 1.9.3.
EDIT----
log starts right after my begin statement :
begin
File.open(logfile, 'w') do |log| #setup log to write response codes.
log.puts works throughout the entire code except when an error is thrown, and then it runs the rescue script where log is not available.
The same goes for email_ids_all. There is an API call that generates about 10,000 emails and each of them is added to the array email_ids_all. The script is receiving an error about halfway through generating these emails, and so I need the rescue script to delete all email ids in the email_ids_all array. But for whatever reason, I get the following error:
FS_Test_Env.rb:762:in `block in <main>': undefined local variable or method `email_ids_all' for main:Object (NameError)
from FS_Test_Env.rb:759:in `open'
from FS_Test_Env.rb:759:in `rescue in <main>'
from FS_Test_Env.rb:7:in `<main>'
Any thoughts?
The way you put it, it should work, for example:
irb(main):001:0> begin
irb(main):002:1* x = 1
irb(main):003:1> x / 0
irb(main):004:1> rescue Exception => e
irb(main):005:1> p x
irb(main):006:1> end
1
=> 1
So it looks like the exception is thrown before your variables are defined.
The scope of the block parameter log is limited to that block. This is the whole point of the open with block.
Maybe you want to do:
begin
log = File.open('logfile', 'w')
...
rescue
...
ensure
log.close
end
Note that this does not cover errors when opening the logfile.
Regarding email_ids_all, I guess (!) you have the exception in a statement like:
email_ids_all = ... a long and complex calculation which raises an exception
If yes, the problem is that the assignment happens only after the whole right-hand side is calculated. The var email_ids_all is not yet created when the exception happens.
In order to access the elements created before the exception, you have to keep track of them, e.g.
begin
email_ids = []
10000.times do
email_ids << ... # create element eventually raising an exception
end
rescue
... # treat the already created elements
end

Resources