开发者

Ruby: check if object is nil

  def parse( line )
    _, remote_addr, status, request, size, referrer, http_user_agent, http_x_forwarded_for = /^([^\s]+) - (\d+) \"(.+)\" (\d+) \"(.*)\" \"([^\"]*)\" \"(.*)\"/.match(line).to_a

    print line
    print request
    if request && request != nil
      _, referrer_host, referrer_url = /^ht开发者_运维技巧tp[s]?:\/\/([^\/]+)(\/.*)/.match(referrer).to_a if referrer
      method, full_url, _ = request.split(' ')

in parse: private method 'split' called for nil:NilClass (NoMethodError)

So as i understand it's calling split not on a string, but on nil. This part is parsing web server log. But I can't understand why it's getting nil. As I understand it's null.

Some of the subpatterns in regex failed? So it's the webserver's fault, which sometimes generates wrong logging strings?

By the way how do I write to file in ruby? I can't read properly in this cmd window under windows.


You seem to have a few questions here, so I'll take a stab at what seems to be the main one:

If you want to see if something is nil, just use .nil? - so in your example, you can just say request.nil?, which returns true if it is nil and false otherwise.


Ruby 2.3.0 added a safe navigation operator (&.) that checks for nil before calling a method.

request&.split(' ')

This is functionally* equivalent to

!request.nil? && request.split(' ')

*(They are slightly different. When request is nil, the top expression evaluates to nil, while the bottom expression evaluates to false.)


To write to a file:

File.open("file.txt", "w") do |file|
  file.puts "whatever"
end

As I write in a comment above - you didn't say what is nil. Also, check whether referrer contains what you think it contains. EDIT I see it's request that is nil. Obviously, regexp trouble.

Use rubular.com to easily test your regexp. Copy a line from your input file into "Your test string", and your regexp into "Your regular expression", and tweak until you get a highlight in "Match result".

Also, what are "wrong logging strings"? If we're talking Apache, log format is configurable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜