Skip to content

Instantly share code, notes, and snippets.

@rubyworks
Created February 27, 2010 04:30
Show Gist options
  • Save rubyworks/316477 to your computer and use it in GitHub Desktop.
Save rubyworks/316477 to your computer and use it in GitHub Desktop.
instance_eval.rb
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