Created
July 2, 2012 15:51
-
-
Save anonymous/3033911 to your computer and use it in GitHub Desktop.
Ruby Custom Setters and Getters
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 AttributeNotDefinedException < Exception; end | |
class Activity | |
def duration(dur=nil) | |
return @duration = dur if dur | |
return @duration if @duration | |
raise AttributeNotDefinedException, "Attribute '#{__method__}' hasn't been set" | |
#rescue AttributeNotDefinedException => e | |
#p e.message | |
end | |
def priority(pty=nil) | |
return @priority = pty if pty | |
return @priority if @priority | |
raise AttributeNotDefinedException, "Attribute '#{__callee__}' hasn't been set" | |
#rescue AttributeNotDefinedException => e | |
#p e.message | |
end | |
end | |
require 'minitest/spec' | |
require 'minitest/autorun' | |
describe "testing setting and getting attributes in a single method" do | |
before do | |
@act = Activity.new | |
end | |
it "must raise an exception when attribute hasn't been set" do | |
lambda {@act.duration}.must_raise(AttributeNotDefinedException) | |
lambda {@act.priority}.must_raise(AttributeNotDefinedException) | |
#@act.duration.must_equal "Attribute 'duration' hasn't been set" | |
#@act.priority.must_equal "Attribute 'priority' hasn't been set" | |
end | |
it "must set the attribute from method param" do | |
@act.duration(15).must_equal 15 | |
@act.instance_variable_get(:@duration).must_equal 15 | |
@act.duration(3).must_equal 3 | |
@act.instance_variable_get(:@duration).must_equal 3 | |
end | |
it "must get the attribute value when called with no params" do | |
@act.duration 15 | |
@act.duration.must_equal 15 | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment