I've defined this method on ruby ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-darwin14] and (Rails 4.2.5.2)
def log_method_backtrace
backtrace = []
(4..8).map do |i| # 4 because before is ... map, log_method_backtrace...
b = caller[i][/\/(?:.(?!\/))+$/]
b = b[1..-2] # *This is the error line
b = b.sub(':in `', '#')
backtrace << "#{b} <- "
end
log "(Method called from #{backtrace.join})"
end
When I call it it throw this error:
NoMethodError: undefined method `[]' for nil:NilClass from (pry):5:in `block in log_method_backtrace'
But if I place a debugger breakpoint (I'm using binding.pry) in that line, and run the same line it works.
caller is a native Ruby method that returns the current execution stack as an array of strings. The problem I was having was because, as my code was running in the console one of the lines was:
"(pry):7:in `<main>'"
All the other lines had a filename/line/method name format as:
/...../gems/pry-0.9.12.6/lib/pry/pry_instance.rb:328:in `eval'
The regular expresion that I was using [/\/(?:.(?!\/))+$/] was expected to capture the filename as the line had no a filename it returned nil and the b[-1..2] was throwing an error as b was `nil.
While I'm debugging the caller variable got replaced on the binding.pry execution time, making the code work.
This is how I fixed the code to make it work:
def log_method_backtrace
backtrace = []
(4..8).map do |i| # 4 because before is ... map, log_method_backtrace...
line = caller[i]
b = line[/\/(?:.(?!\/))+$/] || line
b = b[1..-2]
b = b.sub(':in `', '#')
backtrace << "#{b} <- "
end
log "(Method called from #{backtrace.join})"
end
Related
I am getting an error when executing my test.
Failure/Error: expect(industry_sic_code).to include page.sic_code
TypeError:
no implicit conversion of Array into String
# ./spec/os/bal/company/company_filter_clean_harbors_industries_stub.rb:62:in `block (2 levels) in <top (required)>'
The Method:
def sic_code
subtables = #b.table(:class => 'industry-codes').tables(:class => 'industry-code-table')
subtables.each do |subtable|
if subtable.tbody.h4.text == "US SIC 1987:"
subtable.tr.next_siblings.each do |tr|
codes = tr.cell
puts codes.text.to_s
end
end
end
end
The Test:
it 'Given I search for a random Clean Harbors Industry' do
#Pick a random clean industry from the file
data = CSV.foreach(file_path, headers: true).map{ |row| row.to_h }
random = data.sample
random_industry = random["Class"]
industry_sic_code = random["SIC Code"]
end
it 'Then the result has the expected SIC code' do
page = DetailPage.new(#b)
page.view
expect(industry_sic_code).to include page.sic_code
end
I have tried to implicitly change each variable to a string but it still complain about the array issue.
When I include some puts statments, I get some really wonky responses. The method itself returns the expected result.
When I used the method in the test I end up with the code gibberish below.
here are the sic codes from the method
5511
Here are the codes from the test
#<Watir::Table:0x00007fa3cb23f020>
#<Watir::Table:0x00007fa3cb23ee40>
#<Watir::Table:0x00007fa3cb23ec88>
#<Watir::Table:0x00007fa3cb23ead0>
#<Watir::Table:0x00007fa3cb23e918>
#<Watir::Table:0x00007fa3cb23e738>
#<Watir::Table:0x00007fa3cb23e580>
Your sic_code method returns subtables array, that's why you have this error. It doesn't matter that the method puts something, every method in ruby implicitly returns result of its last line, in your case it is subtables.each do ... end, so you have an array.
You need to explicitly return needed value. Not sure if I correctly understood what are you doing in your code, but try something like this:
def sic_code
subtables = #b.table(:class => 'industry-codes').tables(:class => 'industry-code-table')
result = [] # you need to collect result somewhere to return it later
subtables.each do |subtable|
if subtable.tbody.h4.text == "US SIC 1987:"
subtable.tr.next_siblings.each do |tr|
codes = tr.cell
result << codes.text.to_s
end
end
end
result.join(', ')
end
Hi I have a string passed back from rspec.
It should show
"alias/public_html/ab1/ab2/"
but I am getting "\"alias/public_html/ab1/ab2/\""
I am getting the rspec error below:
WebServer::HttpdConf#alias_path returns the aliased path
Failure/Error: expect(httpd_file.alias_path('/ab/')).to eq 'alias/public_html/ab1/ab2/'
expected: "alias/public_html/ab1/ab2/"
got: "\"alias/public_html/ab1/ab2/\""
(compared using ==)
# ./spec/lib/config/httpd_conf_spec.rb:90:in `(root)'
And here is my actual program file
def alias_path(path)
#hash_httpd['Alias'][path]
end
Please help
EDIT
Sorry, I am new to RUby, here is the httpd_file
def initialize(httpd_file_content)
#hash_httpd = Hash.new
httpd_file_content.each_line do | line |
#commands = line.split
if #commands.length == 2
#hash_httpd[#commands[0]] = #commands[1]
else
if !#hash_httpd.has_key?(#commands[0])
al = Hash.new
#hash_httpd[#commands[0]] = al
else
al = #hash_httpd[#commands[0]]
end
al[#commands[1]] = #commands[2]
end
end
end
If you are sure that your alias_path output will be "alias/public_html/ab1/ab2/", then you can just modify your alias_path method definition by removing the quotes (if any) from the returned path:
def alias_path(path)
#hash_httpd['Alias'][path].gsub('"', '')
end
I'm looking for some help with my code...
# save text file to string
data = File.read("workdata.txt")
# split string into blocks of text relevant to each journey
journeys = data.split(/\n\s\n/)
# store the amount of journeys as a variable called journeys_size
journeys_size = journeys.length
# split each journey into lines and save to an array called "journey_lines"
#journey_lines = journeys.map { |i| i.split(/\n/) }
# cretae an array called "all_journey_objects" to hold all journeys
all_journey_objects = []
# step through the journey arrays
#journey_lines.each do |line|
next if line[0].include?("position") # skip the journey block of text if it contains position
destinations = []
destination1 = line[12].upcase
destination2 = line[13].scan(/[a-z]+/i).join(" ").upcase
# destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase # <---- When i uncomment this line **
# destination4 = line[15].scan(/[a-z]+/i).join(" ").upcase
# destination5 = line[16].scan(/[a-z]+/i).join(" ").upcase
puts destination1
puts destination2
# puts destination3 # <---- When i uncomment this line **
# puts destination5
# puts destination4
# journey = Journey.new(line[0] , line[1] , line[6] , destinations, etas, windows)
# all_journey_objects << journey
end
The problem I am having is the following error when executed:
watcher.rb:47: in 'block in <main>': undefined method'scan' for nil:NilClass (NoMethodError)
I think the reason is because the "workdata.txt" file that I am working with, contains some journeys which only have two destinations. So, as soon as i uncomment the lines to create a third destination variable it throws an error. Maybe because it is trying to run a method against an object that doesn't exist?
I am stuck with finding a way around this. Any help would be appreciated...
If this is line 47:
destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase
undefined method `scan' for nil:NilClass indicates that you are sending scan to nil. In other words, line[14] is nil.
You could simply add an if statement:
if line[14]
destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase
end
Or an inline if:
destination3 = line[14].scan(/[a-z]+/i).join(" ").upcase if line[14]
I'm not sure why I get this error, since it does seem to be an array in Ruby 1.8.7.
Here is the relevant code:
rows.each_with_index do |row, index|
if (index == 0) then
log "Found the following slow statements (took over #{slow_query_threshold} seconds):"
end
row_data = row.strip().split('|')
connections = row_data[1].split(', ')
n_more = '... and #{connections.length - 3} more' if connections.length > 3
log %{[#{row_data[0]}] on #{connections.take(3).join(', ')} #{n_more}}
end
Which gives me this error:
2013-04-10T05:36:45.04Z : Found the following slow statements (took over 5.0 seconds):
/myscript.rb:111: undefined method `take' for ["App15(28.39sec)"]:Array (NoMethodError)
from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `each_with_index'
You must be running on 1.8.6. Upgrade, or require 'backports/1.8.7/enumerable/take'
I am using the Mongo Ruby driver and have this block of Ruby code before and after line 171 in my code, which is apparently the source of the error below it (the query.each line is line 171):
query = get_callback.call( "databases", id )
if query.count > 0
puts query.count.inspect + " results: " + query.inspect
res = {}
query.each do |result|
puts result.inspect
end
else
puts "No results" + res.inspect
res = {}
end
The error:
1 results: <Mongo::Cursor:0x3fc15642c154 namespace='myproj.databases' #selector={"_id"=>BSON::ObjectId('4fe120e4a2f9a386ed000001')} #cursor_id=>
TypeError - can't convert Mongo::Cursor into Integer:
/Users/myuser/.rvm/gems/ruby-1.9.3-p194/gems/bson-1.6.4/lib/bson/byte_buffer.rb:156:in `pack'
/Users/myuser/.rvm/gems/ruby-1.9.3-p194/gems/bson-1.6.4/lib/bson/byte_buffer.rb:156:in `put_int'
/Users/myuser/.rvm/gems/ruby-1.9.3-p194/gems/mongo-1.6.4/lib/mongo/cursor.rb:603:in `construct_query_message'
/Users/myuser/.rvm/gems/ruby-1.9.3-p194/gems/mongo-1.6.4/lib/mongo/cursor.rb:466:in `send_initial_query'
/Users/myuser/.rvm/gems/ruby-1.9.3-p194/gems/mongo-1.6.4/lib/mongo/cursor.rb:459:in `refresh'
/Users/myuser/.rvm/gems/ruby-1.9.3-p194/gems/mongo-1.6.4/lib/mongo/cursor.rb:128:in `next'
/Users/myuser/.rvm/gems/ruby-1.9.3-p194/gems/mongo-1.6.4/lib/mongo/cursor.rb:291:in `each'
/Users/myuser/Code/myproj/my_file.rb:171:in `block in initialize'
My query object: {"_id"=>BSON::ObjectId('4fe120e4a2f9a386ed000001')}
I have not the faintest idea what's causing this. I've verified the object I'm finding exists and the query.count shows that there's a result in my Mongo::Cursor.
I've not found any examples of the issue on Google and every Mongo/Ruby on the web I've found uses an each iterator just like I do. Anyone know what's the cause of this error? I notice I also get it when trying to use to_a to cast the collection to a JSON-usable object.
For what it's worth, here's the relevant part of byte_buffer.rb is below. The line with << is line 156.
def put_int(i, offset=nil)
#cursor = offset if offset
if more?
#str[#cursor, 4] = [i].pack(#int_pack_order)
else
ensure_length(#cursor)
#str << [i].pack(#int_pack_order)
end
#cursor += 4
end
This happens when you pass nil to a Ruby Mongo driver limit() method.