This post originated from an RSS feed registered with Ruby Buzz
by rwdaigle.
Original Post: Roxy: A Ruby Proxy-Object Library
Feed Title: Ryan's Scraps
Feed URL: http://feeds.feedburner.com/RyansScraps
Feed Description: Ryan Daigle's various technically inclined rants along w/ the "What's new in Edge Rails" series.
Proxies are a powerful tool in software development, allowing you to transparently provide extra functionality or a slight abstraction to an underlying object. One of the more visible uses of proxies is in ActiveRecord which uses a proxy to represent its many associations. For instance, in the following article definition:
when you call article.comments what you get back is actually a proxy object that wraps the comments collection with some extra functionality like the << and build methods. Although it looks like a normal Array when you directly access comments, it’s really a proxy that’s marshaling method calls to an underlying collection or intercepting the method calls if it’s functionality it wants to handle itself. Named scopes also work in a similar manner.
That’s great and all, but these proxies are tied very specifically to their implementations within ActiveRecord .. and that’s what Roxy is intended to address. Roxy brings some serious moxie to your development with the ability to easily define and use proxies in your non ActiveRecord classes.
Let’s take a look at an example: Suppose I have a person object that has a list of parents and children (again, this is outside the scope of ActiveRecord or any other persistence framework where you might be able to do this with some other mechanism).
If you want add functionality to a person that determines if their parents are divorced, or if they have any stepchildren you could easily enough add that functionality directly to the Person object:
123456789101112131415161718
classPerson attr_accessor :first, :last, :parents, :childrendefinitialize(first, last)@first, @last = first, lastend# If my parents have different last names, then assume they're divorceddefparents_divorced? parents.size > 1and parents.collect { |parent| parent.last }.uniq.size > 1end# Any child with a different last name than mine is considered# a step-child.defstep_children children.select { |child| self.last != child.last }endend
but this approach has always seemed very obtuse, however. If I am strictly modeling my domain to the real world, which is the approach I favor until it becomes unwieldy to do so, what I really want to do is ask a person’s parents if they’re divorced. After all, their divorce status is a property of the parents, not the person itself. With Roxy this structure is easy to model:
require 'roxy'classPerson# Add in proxy ability include Roxy::Moxie attr_accessor :first, :last, :parents, :children# Add ability to ask the parents collection if they are divorced proxy :parentsdodefdivorced? proxy_target.size > 1and proxy_target.collect { |parent| parent.last }.uniq.size > 1endend# Add ability to ask the children collection for only the step-children proxy :childrendodefstep proxy_target.select { |child| proxy_owner.last != child.last }endenddefinitialize(first, last)@first, @last = first, lastendend# Now the following is possible:person.parents.divorced? #=> true|falseperson.children.step #=> [<Person...>, <Person...>]
Roxy allows you transparently adorn existing attributes and methods with added functionality, making a more realistic domain model. This is very similar to rails’ association proxies except that you are now free to add functionality to all methods and objects.
Proxy methods are defined in the block that is passed to the proxy call. Within each proxy method you can reference the object that owns the proxy (the person instance here) as proxy_owner and the thing that is being proxied (the parents and children collections here) as proxy_target.
Advanced
You’re not limited to proxying existing methods, you can just as easily proxy to another object using the :to option.
1234567891011121314151617
require 'roxy'classPerson# Add in proxy ability include Roxy::Moxie attr_accessor :address proxy :shipping, :to => ShippingMethod.all dodefcheapest proxy_target.min { |m| m.cost_from(proxy_owner.address) }endendend# Find the cheapest shipping method from all methodsperson.shipping.cheapest #=> <ShippingMethod...>
If the value you want to proxy needs to be evaluated at runtime just pass in a proc. The proc should accept a single argument which will be the proxy_owner instance:
123456789101112131415161718
require 'roxy'classPerson# Add in proxy ability include Roxy::Moxie attr_accessor :address proxy :shipping, :to => proc { |person| ShippingMethod.available_for(person) } dodefcheapest proxy_target.min { |m| m.cost_from(proxy_owner.address) }endendend# Find the cheapest shipping method from the methods# only available to 'person'person.shipping.cheapest #=> <ShippingMethod...>
You’ll notice that the best use of proxies is as a lightweight relationship between two things. I.e. instead of creating a whole other object to represent the relationship between a person and the various shipping methods you can quickly add functionality directly to that object-relationship as a proxy method.
A sign of abuse of this particular proxy pattern is when you reference only one of the proxy_owner or proxy_target and neither depends on the other in any way. That is usually an indication that the functionality should live solely in the referenced proxy owner/target and not in the proxy itself.
Proxy methods can also be defined as modules (as in Rails’ association extensions) for greater re-use between similar proxies with the :extend option (which can take one or more modules):
12345678910111213141516171819202122
require 'roxy'classPerson# Add in proxy ability include Roxy::Moxie attr_accessor :age, :children, :parents# Re-usable functionality to find the oldest person in a collectionmodulePersonCollectiondefoldest proxy_target.max { |p| p.age }endend proxy :children, :extend => PersonCollectionend# Now the following is possible:person.parents.oldest #=> <Person...>person.children.oldest #=> <Person...>
Once you grasp the beauty, simplicity and power of proxies you’ll likely find many uses for them. They’re a great tool to have in your toolbox and Roxy would love it if she found a place in yours.
I hope to have an extension library up soon that utilizes Roxy to provide ActiveRecord-like association definitions in ActiveResource. Something like:
12345678910111213141516
require 'roxy'classUser < ActiveResource::Base include Roxy::Moxie proxy :articles,:to => proc { |u| Article.find(:all, :params => { :user_id => u.id } } dodefdestroy_all proxy_target.each { |a| a.destroy }endendend# Now a remote user looks a lot like a first class active record object:user.articles #=> [<Article...>, <Article...>, ...]user.articles.destroy_all
Stay tuned for that, and let me know where you’ve found proxies to be a great tool to have around. I’m always looking for better example scenarios.