The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby: Use class methods to reduce duplication

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: Use class methods to reduce duplication Posted: Dec 16, 2006 12:56 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jay Fields.
Original Post: Ruby: Use class methods to reduce duplication
Feed Title: Jay Fields Thoughts
Feed URL: http://blog.jayfields.com/rss.xml
Feed Description: Thoughts on Software Development
Latest Ruby Buzz Posts
Latest Ruby Buzz Posts by Jay Fields
Latest Posts From Jay Fields Thoughts

Advertisement
Context: I had two method definitions in my class that were similar to the code below.
class TaxRemoteFacade

def state_tax
...
@remote.close
end

def federal_tax
...
@remote.close
end

end
I've only shown two, but we actually needed the @remote.close code at the end of several methods.

Solution: To reduce the duplication we introduced a super class with a class method that would remove the duplication.
class RemoteFacade
def self.remote_call(method_name, &block)
class_eval do
define_method name do
instance_eval &block
@remote.close
end
end
end
end
The TaxRemoteFacade can now be defined as the code below.
class TaxRemoteFacade

remote_call do :state_tax do
...
end

remote_call do :federal_tax do
...
end

end

Read: Ruby: Use class methods to reduce duplication

Topic: Why I still look at the jroller homepage sometimes Previous Topic   Next Topic Topic: Rake: --dry-run, --trace, and -T

Sponsored Links



Google
  Web Artima.com   

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