This post originated from an RSS feed registered with Ruby Buzz
by Red Handed.
Original Post: Method Check: Param Hacks
Feed Title: RedHanded
Feed URL: http://redhanded.hobix.com/index.xml
Feed Description: sneaking Ruby through the system
It’s all about finding out where Ruby’s syntax is flexible, isn’t it? So, did you know you can use instance variables or arbitrary code to set the defaults in your method parameters? All executed in the same context as your method.
class LineArtist
attr_accessor :distance, :thickness
def draw( dist = @distance, thick = self.thickness ); end
end
And, check this out—you can refer to earlier parameters when setting defaults!
class BlogEntry
attr_accessor :author, :title, :created_at, :content
def initialize( blog, title, content,
created_at = Time.now,
author = blog.default_author )
end
end
This is especially useful for methods where you’re passing in a set of paths. If some of the paths are deleted, you want to default to an earlier path (or a new path based on an earlier path.)
class Blog
def setup( path, template_path = File.join( path, "skel" ) )
end
end