Last active
August 6, 2019 19:56
-
-
Save sowcow/4603064 to your computer and use it in GitHub Desktop.
define_method + super in refinements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ruby version: ruby 2.0.0dev (2012-12-01 trunk 38126) | |
END{ | |
using Test | |
p '123'.to_i # => 123 - ok | |
p '123'.size # => 3 - works! | |
p '123'.inspect # => error | |
} | |
module Test | |
refine String do | |
def to_i | |
super.to_s + ' - ok' | |
end | |
define_method :size do | |
unwrap(self).size.to_s + ' - works!' | |
end | |
define_method :inspect do | |
super() + ' - stack level too deep (SystemStackError)' | |
end | |
end | |
end | |
# to call method out of refinement scope | |
class Unwrapped < BasicObject | |
def initialize obj; @obj = obj end | |
private; attr_reader :obj | |
def method_missing *a,&b; obj.send *a,&b end # fixed | |
end | |
def unwrap(object) | |
Unwrapped.new object | |
# require 'object-proxy' | |
# OP::proxy(object) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment