Technology Agnostic Rubyist : Open Source Lights The Way

Saturday, May 30, 2009

Extending the String class

Feeling inspired after 2009 Gotham Ruby Conference, I finally wrote this.

class String

def nationalize
# retrieve a full xml list of countries and attributes
# if string matches the country name on the list return the
# nationality of the goods that originate from that country
# may not be the most efficient way, but it sure is extensible
@xml = open('http://originify.us/originify.us.xml')
country = REXML::Document.new(@xml)
country.elements.each('/countries/country') do |p|
return p.attributes['nationality'] if self.to_s == p.text.to_s
end
# returns self or superclass
self || super
end

end

It's an extension of the String class. I wanted to present the idea at the Reject Conference session but I'm glad I didn't. There were about 10 reject presentations and some were really good.

The way it works is simple. Just take any text string and use the nationalize method on it. For example, "France".nationalize => "French", "Switzerland".nationalize => "Swiss", "Australia".nationalize => "Australian".

This could be useful. Suppose you are a clothing retailer and have data for sweater in your database. The sweater has been assigned the attributes "Wool" and originating from "Australia" or "Switzerland" using a dropdown.

In describing the sweater on a web site, one might want to say that it is made of Swiss Wool.

This could be refactored.

Tweets

Contributors