Created
February 8, 2012 08:44
-
-
Save jimweirich/1766932 to your computer and use it in GitHub Desktop.
Vital Ruby Lab 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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