The Artima Developer Community
Sponsored Link

Ruby Buzz Forum
Ruby: State pattern using Modules and Facets

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: State pattern using Modules and Facets Posted: Aug 23, 2007 4:51 PM
Reply to this message Reply

This post originated from an RSS feed registered with Ruby Buzz by Jay Fields.
Original Post: Ruby: State pattern using Modules and Facets
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
While browsing the docs for Facets I noticed the Kernel.as method. Then, a day later I needed a solution that added behavior using the state pattern; however, it was more elegant for our solution if the state instances could call methods on the class containing the state object. Our first solution was to delegate to the containing class via the method_missing method of the state instances. While this did work, debugging became problematic when things went wrong.

I did a quick spike to see if Kernel.as could provide a solution.

require 'rubygems'
require 'facets'

module James
protected

def name
"James #{last_name}"
end
end

module Lynn
protected

def name
"Lynn #{last_name}"
end
end

class FamilyMember
attr_accessor :person
include James
include Lynn

def name
as(person).name
end

def last_name
"Holbrook"
end
end


member = FamilyMember.new
member.person = James
member.name # => "James Holbrook"
member.person = Lynn
member.name # => "Lynn Holbrook"
member.first_name rescue "first_name is not defined" # => "first_name is not defined"

There's a few interesting things about this solution. I can change the behavior at runtime by changing the person attribute. Also, the behavior is actually on the class instead of living on an independent state object that delegates back to the class. Lastly, each method is protected so they must be accessed via the delegations, and an error will occur if they are accessed directly.

Read: Ruby: State pattern using Modules and Facets

Topic: Free Ruby Lessons Previous Topic   Next Topic Topic: Collaborative Bookmarking... UNLEASHED

Sponsored Links



Google
  Web Artima.com   

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