Skip to content

Instantly share code, notes, and snippets.

@matthewrudy
Forked from pjb3/floppy.rb
Created February 12, 2010 03:38
Show Gist options
  • Save matthewrudy/302269 to your computer and use it in GitHub Desktop.
Save matthewrudy/302269 to your computer and use it in GitHub Desktop.
class Floppy
def metaclass
class << self
return self
end
end
def metaclass_eval(&block)
metaclass.class_eval(&block)
end
def method_missing(method_name, *args)
super unless method_name.to_s.end_with?("=") && args.length == 1
proc = args.first
reader_name = method_name.to_s[0..-2] # :abc= => "abc"
unless proc.is_a?(Proc) # for define method we must use a proc
proc = lambda { args.first } # if we said "lambda { proc }" we'd just get our lambda back
end
metaclass_eval do
define_method(reader_name, proc)
end
end
end
require 'test/unit'
class FloppyTest < Test::Unit::TestCase
def setup
@foo = Floppy.new
end
def test_assign_proc_adds_method
@foo.bar = lambda { "bar" }
assert_equal "bar", @foo.bar
end
def test_assign_object_add_attr
@foo.name = "Foo"
assert_equal "Foo", @foo.name
end
def test_assign_object_then_attr
@foo.name = "Foo"
assert_equal "Foo", @foo.name
@foo.name = lambda {|n| "Foo #{n}"}
assert_equal "Foo 4", @foo.name(4)
@foo.name = "Fooble"
assert_equal "Fooble", @foo.name
end
def test_method_method_still_works
assert_raise NoMethodError do
@foo.alakazam
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment