Gsub string override

I am new to ruby ​​and I just run into the first difficult problem. I am trying to override some String methods in order to attach some functionality to them. The problematic method seems to be gsub. (EDIT) Let me insert my main.rb, which demonstrates this error.

require 'rubygems' if RUBY_VERSION < "1.9" require 'sinatra' class String alias_method :old_gsub, :gsub def gsub (*params, &block ) old_gsub *params, &block end end get '/' do s="Hello world! " end 

This is my starting point, and I expect this to work the same as the original line. Unfortunately, with this redefinition in place, there are some existing code breaks.

As you can see in this script, I am trying to load Sinatra and serve the page. When I do this and request the index, the web server fails with the next console output.

127.0.0.1 - - [25 / Feb / 2011 17:56:26] "GET / HTTP / 1.1" 200 13 0.0012 [2011-02-25 17:56:26] ERROR NoMethodError: undefined `upcase 'method for nil: NilClass / usr / local / ruby ​​/ lib / ruby ​​/ 1.9.1 / webrick / httpresponse.rb: 172: in `block (2 levels) in send_header '/data/Dropbox/Ruby/RubyTrack/lib/main.rb:227 : in `gsub '/data/Dropbox/Ruby/RubyTrack/lib/main.rb:227:in` gsub' / usr / local / ruby ​​/ lib / ruby ​​/ 1.9.1 / webrick / httpresponse.rb: 172: in `block in send_header '+ plus more stuff in the trace
[2011-02-25 17:56:26] ERROR NoMethodError: undefined `[] 'method for nil: NilClass / usr / local / ruby ​​/ lib / ruby ​​/ 1.9.1 / webrick / accesslog.rb: 52: in block in the format '/data/Dropbox/Ruby/RubyTrack/lib/main.rb:227:in `gsub' /data/Dropbox/Ruby/RubyTrack/lib/main.rb:227:in` gsub '/ usr / local / ruby / lib / ruby ​​/ 1.9.1 / webrick / accesslog.rb: 50: in `format '+ more stuff in the trace

The first exception (httpresponse.rb: 172) is on the line

 tmp = key.gsub(/\bwww|^te$|\b\w/){ $&.upcase } 

and the second error is caused by the result (accesslog.rb: 50)

 format_string.gsub(/\%(?:\{(.*?)\})?>?([a-zA-Z%])/) 

From the above it can be seen that I'm using Ruby 1.9.1 (although ruby ​​-v gives me 1.9.2p0). I'm on Ubuntu 10.04. It’s true that there might be something wrong with my Ruby configuration, the installation on Ubuntu was a bit dirty.

So, to summarize, why does my gsub override behave differently than the original gsub?

+4
source share
1 answer

The internal implementation of the Ruby CRI code inside gsub does some magic to customize $& , $1 , etc. in the calling method. When you override gsub , they end up being set in your override, not the override that calls you.

I don’t know how to do this in an MRI. In Rubinius, enough internal components are implemented in Ruby and made available to user level code, which is possible. This is what Yehuda Katz touches on in this post .

+2
source

Source: https://habr.com/ru/post/1341311/


All Articles