Skip to content

Instantly share code, notes, and snippets.

@pjb3
Created February 6, 2010 21:20

Revisions

  1. pjb3 created this gist Feb 6, 2010.
    40 changes: 40 additions & 0 deletions floppy.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    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