Skip to content

Instantly share code, notes, and snippets.

@ConradIrwin
Forked from rf-/function.rb
Created December 15, 2012 08:49
Show Gist options
  • Save ConradIrwin/4292203 to your computer and use it in GitHub Desktop.
Save ConradIrwin/4292203 to your computer and use it in GitHub Desktop.
require 'binding_of_caller'
def self.method_missing(name, *args, &block)
if binding.of_caller(1).eval("defined?(#{name})")
binding.of_caller(1).eval("#{name}").call(*args, &block)
else
name
end
end
def function(*param_names, &block)
klass = Class.new { attr_accessor :this, *param_names }
this = TOPLEVEL_BINDING.eval('self')
proc do |*params|
context = klass.new
context.this = this
param_names.each do |param_name|
context.send "#{param_name}=", params.shift
end
context.instance_eval &block
end
end
fn = function(foo, bar) { foo + bar * 10; }
puts fn(1, 2) # => 21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment