Last active
December 14, 2015 20:39
-
-
Save stevenosloan/5145549 to your computer and use it in GitHub Desktop.
Only setting getter's apparently doesn't prevent manipulation of instance variables. The shovel is a great and dangerous too.
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
# create a class with an attr_reader for | |
# a string and an array | |
class Thing | |
attr_reader :arr | |
attr_reader :str | |
def initialize | |
@arr = [] | |
@str = "" | |
end | |
end | |
# initialize the class | |
thing = Thing.new | |
# putting the array and string work | |
# as we would expect | |
p thing.arr | |
# => [] | |
p thing.str | |
# => "" | |
# but if we shovel into them, we can | |
# alter their state -- even though we | |
# only exposed a getter method | |
thing.arr << "hello" | |
p thing.arr | |
# => ["hello"] | |
thing.str << "hello" | |
p thing.str | |
# => "hello" | |
# Lets try protecting our vars using dup | |
class Protected | |
attr_accessor :exposed | |
def initialize | |
@exposed = "safe" | |
@safe = "safe" | |
end | |
def safe | |
@safe.dup | |
end | |
end | |
# again, a sanity check to see that | |
# our values both equal "safe" | |
example = Protected.new | |
p example.safe == example.exposed | |
# => true | |
# we'll shovel to try and modify them | |
example.exposed << " or not" | |
example.safe << " or not" | |
# and test equality again | |
p example.safe == example.exposed | |
# => false | |
# we can see @safe keeps its original value | |
p example.safe | |
# => "safe" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment