Created
February 27, 2010 04:30
-
-
Save rubyworks/316477 to your computer and use it in GitHub Desktop.
instance_eval.rb
This file contains hidden or 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
require 'facets/functor' | |
class Object | |
# Use #instance_eval with a fluid notation. | |
# | |
# class X | |
# attr :a | |
# private :a | |
# def initialize | |
# @a = 1 | |
# end | |
# end | |
# | |
# x = X.new | |
# p x.instance_eval.a #=> 1 | |
# p x.a #=> Error | |
# | |
# A useful example might include adding accessors to a metaclass. | |
# | |
# class X | |
# metaclass.instance_eval.attr :x | |
# end | |
# | |
# Will only support calls with blocks as of Ruby 1.8.7+. | |
# | |
def instance_eval(*args, &block) | |
return super if block or !args.empty? | |
@_instance_eval ||= Functor.new do |op, *a, &b| | |
instance_eval{ send(op, *a, &b) } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment