Micro-patterns in Ruby
February 5th, 2008
Yup. Micro-patterns. I've always wanted to begin a blog post with some highly sophisticated buzzword so it might as well be this one (sadly, I can't say I'm the first to use it).
This is a tiny one. Let's say we have a Factory that gives me Adapters#1 to a series of hosted media services (Flickr, YouTube, Vimeo, PhotoBucket, etc.).
The user of my code provides a service prefix and a URL to a picture or photo page in a given service, and the factory returns an instance from which the user can fetch different media sizes through a standardized API.
flickr_pic = ServiceParser.instance(
'flickr', 'http://www.flickr.com/photos/new_bamboo_london/2158168775/'
)
puts flickr_pic.thumbnail
# => http://farm3.static.flickr.com/2147/2158168775_01ae89cbfb_s.jpg
yt_video = ServiceParser.instance(
'youtube', 'http://www.youtube.com/watch?v=PCunD-_mOwQ'
)
puts yt_video.thumbnail
# => http://i.ytimg.com/vi/PCunD-_mOwQ/default.jpg
Simple enough. But it seems a bit redundant to have the user declare both the service name and the page URL. Since URL's are unique anyway, those should be enough for our smart factory to know what adapter to hand us, kindly.
We could have a set of regular expressions in the factory, one for each URL/service.
class ServiceParser
SERVICES = {
FlickrAdapter => /flickr\.com/,
YouTubeAdapter => /youtube\.com/,
VimeoAdapter => /vimeo\.com/,
PhotoBucketAdapter => /photobucket\.com/
}
# Factory method
#
def self.instance( url )
subclass = SERVICES.find(nil) {|klass, exp| url =~ exp}
raise 'not implemented' if subclass.nil?
subclass.new url
end
end
We could. But if we did, all hell would break loose and a mob of angry Design Patterns advocates would ram our door and... reprimand us.
While they're at it, they would tell us that one of the many golden rules of Object Oriented software design is, blockquote please:
The superclass should have no knowledge of the subclasses.
But you already know that. We need to take those URL's out of the factory class and into where they belong, in each adapter class. Also, adapters should be able to register their URL's with the factory, so it knows where to look. Ruby to the rescue.
# = The superclass / factory
class ServiceParser
# We register adapters into this class variable
#
@@adapters = []
# class reader
#
def self.adapters
@@adapters
end
# Factory method here, se below...
#
end
# = An example subclass / adapter
class FlickrAdapter < ServiceParser
def initialize( url)
end
# API methods
#
def thumbnail
# do something clever here...
end
# register ourselves with the Factory
#
ServiceParser.adapters << [self, /flickr\.com/]
end
The fun thing about Ruby, class definitions being executable code and all, is that you can just have subclasses add themselves (and their corresponding regex.) to the factory's list of adapters in load time.
ServiceParser.adapters << [self, /flickr\.com/]
Then it is a matter of modifying the factory method to search for matching URL's in the dynamically populated list of subclasses / URL expressions.
# Refactored factory. No pun intended.
#
def self.instance( url )
match = @@adapters.find(nil) {|klass, exp| url =~ exp}
raise 'not implemented' if match.nil?
match.first.new url
end
Finally, a little more elegance to make our adapter authors happy (and less prone to mess with the internals of our superclass!)
class FlickrAdapter < ServiceParser
# Initializer, API and protected methods here...
#
# We register our URL with a neat class method on the superclass
#
register_url /flickr\.com/
end
class ServiceParser
# Factory, abstract methods and cross-adapter utilities here...
#
# Class method for subclasses to register themselves.
#
@@adapters = [] #2 See note on class variables
def self.register_url( exp )
@@adapters << [self, exp]
end
end
#1 Two more buzzwords and just the second paragraph! And there's more...
#2 Class @@variables. These variables are not inherited but shared by all classes in the inheritance tree. That means that, whenever a subclass adds to the superclass' version of @@adapters, it'll actually have the new value in all subclasses. This is not an issue in our simple example, though.
6 Responses to “Micro-patterns in Ruby”
Sorry, comments are closed for this article.






I’m a bit puzzled as to why FlickrAdapter is a sub-class of ServiceParser. Aren’t they two entirely different things? It seems like an abuse of inheritance merely to create the convenience of just calling register_url at the bottom of the adapter’s definition. I would be more inclined to go with a more open interface:
class ServiceParser def register_adapter(url_matcher, adapter) @@adapters[url_matcher] = adapter end end
class FlickrAdapter # knows nothing about ServiceParser end
OK, that didn’t work – there doesn’t seem to be any indication of whether you can use Textile or similar here so let’s give HTML a bash:
Hi Luke. Yes, inheritance is probably misleading in my example, and it would certainly be an abuse if I was using ServiceParser only as a factory.
I actually based the examples on real code where ServiceParser has lots of private methods that are used by the subclasses. In my particular code, the parent class (ServiceParser) initializes with an instance of hPricot, which is available to all subclasses to use on their particular services, and some shared exception handling routines.
Thanks for an interesting and informative post Ismael. It’s seeing compact but expressive examples like this that makes ruby fun to learn. Keep it up!
That threw me for a minute.
@Eric – No, self.instance is a class method, meant to be called on the class instead of an instance of that class.
SomeFactoryClass.instance( parameter) # => some instance of some class