Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Created February 8, 2012 08:44
Show Gist options
  • Save jimweirich/1766932 to your computer and use it in GitHub Desktop.
Save jimweirich/1766932 to your computer and use it in GitHub Desktop.
Vital Ruby Lab 5
class ReadOnlyProxy
def initialize(target)
@target = target
end
def method_missing(sym, *args, &block)
if sym.to_s !~ /=$/
@target.send(sym, *args, &block)
end
end
end
require 'test/unit'
require 'read_only_proxy'
class ReadOnlyProxyTest < Test::Unit::TestCase
class Thing
attr_accessor :name
end
def setup
super
@thing = Thing.new
@thing.name = "THING"
@ro = ReadOnlyProxy.new(@thing)
end
def test_creating_proxy
assert_not_nil @ro
end
def test_normal_methods_pass_thru
assert_equal "THING", @ro.name
end
def test_writing_methods_are_blocked
@ro.name = "HACKED"
assert_equal "THING", @thing.name
end
end
class ShadowProxy
def initialize(target)
@target = target
@shadow = {}
end
def method_missing(sym, *args, &block)
name = sym.to_s
if sym.to_s =~ /=$/
name.gsub!(/=$/,'')
@shadow[name] = args.first
elsif @shadow.has_key?(name)
@shadow[name]
else
@target.send(sym, *args, &block)
end
end
end
require 'test/unit'
require 'shadow_proxy'
class ShadowProxyTest < Test::Unit::TestCase
class Thing
attr_accessor :name
end
def setup
super
@thing = Thing.new
@thing.name = "THING"
@sh = ShadowProxy.new(@thing)
end
def test_creating_proxy
assert_not_nil @sh
end
def test_normal_methods_pass_thru
assert_equal "THING", @sh.name
end
def test_writing_methods_are_blocked
@sh.name = "HACKED"
assert_equal "THING", @thing.name
end
def test_writing_methods_are_shadowed
@sh.name = "HACKED"
assert_equal "HACKED", @sh.name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment