Skip to content

Instantly share code, notes, and snippets.

@pasberth
Created August 31, 2011 13:11
Show Gist options
  • Select an option

  • Save pasberth/1183506 to your computer and use it in GitHub Desktop.

Select an option

Save pasberth/1183506 to your computer and use it in GitHub Desktop.
これで Ruby でも Java の匿名クラスみたいに書ける!!!
module Kernel
def method_missing(klass_name, *args, &definition)
klass = (self.is_a?(Module) ? self : self.class)
begin
const = klass.const_get(klass_name)
if const.instance_of? Class
define_singleton_method(klass_name) do |*args, &definition|
obj = const.new *args
obj.instance_eval(&definition || proc {})
obj
end
elsif const.instance_of? Module
define_singleton_method(klass_name) do |*args, &definition|
obj = Object() { extend const }
obj.instance_eval(&definition || proc {})
obj
end
else
return
end
send(klass_name, *args, &definition)
rescue
$@ = caller
super
end
end
end
if __FILE__ == $PROGRAM_NAME
require "test/unit"
class Test__call__ < Test::Unit::TestCase
def test_call
assert_equal({}, Hash())
end
def test_subclass
assert_equal("hello", Hash() { def hello; "hello"; end }.hello)
end
def test_anoclass
assert_equal("hello", Kernel() { def hello; "hello"; end }.hello)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment