Skip to content

Instantly share code, notes, and snippets.

@severin
Forked from pjb3/floppy.rb
Created February 8, 2010 22:15
Show Gist options
  • Save severin/298640 to your computer and use it in GitHub Desktop.
Save severin/298640 to your computer and use it in GitHub Desktop.
assigning Procs as methods in Ruby
class Floppy
def method_missing(method, *args)
super unless args.length > 0 && method.to_s[-1..-1] == "="
if args.first.is_a?(Proc)
(class << self; self; end).class_eval do
define_method(method.to_s[0..-2].to_sym, args.first)
end
else
(class << self; self; end).send(:attr_accessor, method.to_s[0...-1])
send(method, args.first)
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_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