Instantly share code, notes, and snippets.

Embed
What would you like to do?
Only setting getter's apparently doesn't prevent manipulation of instance variables. The shovel is a great and dangerous too.
# 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