Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created November 13, 2008 13:48
Show Gist options
  • Save jcoglan/24429 to your computer and use it in GitHub Desktop.
Save jcoglan/24429 to your computer and use it in GitHub Desktop.
# Make Ruby Hashes look more like JavaScript objects. Uses
# instance_exec so you can store lambdas on the object and
# call them like methods
#
# o = {}
# o.foo = 'foostring'
# o.bar = lambda { |s| s + foo }
#
# o.bar('barstring') #=> 'barstringfoostring'
class Hash
def method_missing(symbol, *args)
m = symbol.to_s
self[m[0...-1].to_sym] = args.first and return args.first if m =~ /=$/
value = self[symbol]
value.is_a?(Proc) ? instance_exec(*args, &value) : value
end
end
# http://eigenclass.org/hiki/instance_exec
class Object
module InstanceExecHelper; end
include InstanceExecHelper
def instance_exec(*args, &block) # !> method redefined; discarding old instance_exec
mname = "__instance_exec_#{Thread.current.object_id.abs}_#{object_id.abs}"
InstanceExecHelper.module_eval{ define_method(mname, &block) }
begin
ret = send(mname, *args)
ensure
InstanceExecHelper.module_eval{ undef_method(mname) } rescue nil
end
ret
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment