The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby: Default method arguments to instance variables

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Jay Fields

Posts: 765
Nickname: jayfields
Registered: Sep, 2006

Jay Fields is a software developer for ThoughtWorks
Ruby: Default method arguments to instance variables Posted: Apr 11, 2007 7:09 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jay Fields.
Original Post: Ruby: Default method arguments to instance variables
Feed Title: Jay Fields Thoughts
Feed URL: http://feeds.feedburner.com/jayfields/mjKQ
Feed Description: Blog about Ruby, Agile, Testing and other topics related to software development.
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jay Fields
Latest Posts From Jay Fields Thoughts

Advertisement
Several projects ago I worked with Brent Cryder. One night over dinner, he told me that on occasion he would pass instance variables to instance methods of the same class to improve testability. His assertion was that by passing in the variable you could test the method without depending on the state of the object (instance variables). Below is a contrived example to demonstrate the idea.
class Radio
def add_battery(battery)
@battery = battery
end
def on
@battery.on
end
end

class Battery
def on
@on = true
end
def on?
@on
end
end

require 'test/unit'
class RadioTest < Test::Unit::TestCase
def test_on_turns_battery_on
battery = Battery.new
radio = Radio.new
radio.add_battery(battery)
radio.on
assert_equal true, battery.on?
end
end
In the above test, you are required to add the battery before you can test that the on method delegates to the battery. The following example demonstrates how you can test the same thing without requiring a call to the add_battery method.
class Radio
..
def on(battery=@battery)
battery.on
end
end

class Battery
def on
@on = true
end
def on?
@on
end
end

require 'test/unit'
class RadioTest < Test::Unit::TestCase
def test_on_turns_battery_on
battery = Battery.new
radio = Radio.new
radio.on(battery)
assert_equal true, battery.on?
end
end
This is a fairly common idea; however, I like that Ruby allows me to specify a value for the test, but in the production code I would still call radio.on with no parameters and it would use the battery instance variable.

Read: Ruby: Default method arguments to instance variables

Topic: Embracing Failure, part 1 Previous Topic   Next Topic Topic: Rails: Use Ruby Schema syntax without using Migrations

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use