<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Khelll&#039;s Blog &#187; Design Patterns</title>
	<atom:link href="http://khelll.com/blog/category/design-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://khelll.com/blog</link>
	<description>Cool Web Development...</description>
	<lastBuildDate>Thu, 13 Oct 2011 03:48:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Observer and Singleton design patterns in Ruby</title>
		<link>http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/</link>
		<comments>http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 14:36:05 +0000</pubDate>
		<dc:creator>khelll</dc:creator>
				<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Observer]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://www.khelll.com/blog/?p=551</guid>
		<description><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/' addthis:title='Observer and Singleton design patterns in Ruby '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div>This is my first article in http://railsmagazine.com, it was published in issue 3, so basically I&#8217;m just republishing it here again. Observer and singleton are two common design patterns that a programmer should be familiar with, however what made me &#8230; <a href="http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/">Continue reading <span class="meta-nav">&#8594;</span></a><div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/' addthis:title='Observer and Singleton design patterns in Ruby' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></description>
			<content:encoded><![CDATA[<div class="addthis_toolbox addthis_default_style " addthis:url='http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/' addthis:title='Observer and Singleton design patterns in Ruby '  ><a class="addthis_button_facebook_like" fb:like:layout="button_count"></a><a class="addthis_button_tweet"></a><a class="addthis_counter addthis_pill_style"></a></div><p><em>This is my first article in <a href="http://www.railsmagazine.com/">http://railsmagazine.com</a>, it was published in <a href="http://railsmagazine.com/issues/3">issue 3</a>, so basically I&#8217;m just republishing it here again.</em></p>
<p>Observer and singleton are two common design patterns that a programmer should be familiar with, however what made me write about them, is that both are there out of the box for you to use in ruby.<br />
So let’s have a look at both and see how ruby help you use them directly:</p>
<h2>Observer Design Pattern</h2>
<p>According to Wikipedia:</p>
<blockquote><p>The observer pattern (sometimes known as publish/subscribe) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.</p></blockquote>
<p>So how does ruby help you implementing this design pattern? Well, the answer is by mixing the observable module into your subject (observed object).<br />
Let’s take an example, let’s suppose we have a banking mechanism that notifies the user by several ways upon withdrawal operations that leaves the account with balance less or equal to $0.5.<br />
If we look deeply at this problem, we can qualify it as a good candidate for observer design pattern, where the bank account is our subject and the notification system as the observer.<br />
Here is a code snippet for this problem and it’s solution:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># require the observer lib file</span>
<span style="color:#CC0066; font-weight:bold;">require</span> “observer”
<span style="color:#9966CC; font-weight:bold;">class</span> Notifier
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> EmailNotifier <span style="color:#006600; font-weight:bold;">&lt;</span> Notifier
  <span style="color:#9966CC; font-weight:bold;">def</span> update<span style="color:#006600; font-weight:bold;">&#40;</span>bank_account<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> bank_account.<span style="color:#9900CC;">balance</span> <span style="color:#006600; font-weight:bold;">&lt;</span>= <span style="color:#006666;">10</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> “Sending email to: ‘<span style="color:#008000; font-style:italic;">#{bank_account.owner}’ informing him with his account balance: #{bank_account.balance}$.”</span>
      <span style="color:#008000; font-style:italic;"># send the email mechanism</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> SMSNotifier <span style="color:#006600; font-weight:bold;">&lt;</span> Notifier
  <span style="color:#9966CC; font-weight:bold;">def</span> update<span style="color:#006600; font-weight:bold;">&#40;</span>bank_account<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">if</span> bank_account.<span style="color:#9900CC;">balance</span> <span style="color:#006600; font-weight:bold;">&lt;</span>= <span style="color:#006666;">0.5</span> 
      <span style="color:#CC0066; font-weight:bold;">puts</span> “Sending SMS to: ‘<span style="color:#008000; font-style:italic;">#{bank_account.owner}’ informing him with his account balance: #{bank_account.balance}$.”</span>
      <span style="color:#008000; font-style:italic;"># send sms mechanism</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> BankAccount
  <span style="color:#008000; font-style:italic;"># include the observable module</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#CC00FF; font-weight:bold;">Observable</span> 
  attr_reader <span style="color:#ff3333; font-weight:bold;">:owner</span>,:balance
  <span style="color:#9966CC; font-weight:bold;">def</span> initialize<span style="color:#006600; font-weight:bold;">&#40;</span>owner,amount<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@owner</span>,@balance = owner,amount
    <span style="color:#008000; font-style:italic;"># adding list of observes to the account</span>
    add_observer EmailNotifier.<span style="color:#9900CC;">new</span>  
    add_observer SMSNotifier.<span style="color:#9900CC;">new</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># withdraw operation</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> withdraw<span style="color:#006600; font-weight:bold;">&#40;</span>amount<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;"># do whatever you need</span>
    <span style="color:#0066ff; font-weight:bold;">@balance</span> <span style="color:#006600; font-weight:bold;">-</span>=amount <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#006600; font-weight:bold;">&#40;</span>@balance <span style="color:#006600; font-weight:bold;">-</span> amount<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&gt;</span> <span style="color:#006666;">0</span>
    <span style="color:#008000; font-style:italic;"># now here comes our logic</span>
    <span style="color:#008000; font-style:italic;"># issue that the account has changed</span>
    changed
    <span style="color:#008000; font-style:italic;"># notify the observers</span>
    notify_observers <span style="color:#0000FF; font-weight:bold;">self</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
account = BankAccount.<span style="color:#9900CC;">new</span> “Jim Oslen”, <span style="color:#006666;">100</span>
account.<span style="color:#9900CC;">withdraw</span> <span style="color:#006666;">99.5</span>
<span style="color:#008000; font-style:italic;">#=&gt;Sending email to: ‘Jim Oslen’ informing him with his account balance: 0.5$.</span>
<span style="color:#008000; font-style:italic;">#=&gt;Sending SMS to: ‘Jim Oslen’ informing him with his account balance: 0.5$.</span></pre></div></div>

<p>So to user ruby observer lib we have to implement four things:<br />
1- Require the ‘observer’ lib and include it inside the subject (observed) class.<br />
2- Declare the object to be ‘changed’ and then notify the observers when needed – just like we did in ‘withdraw’ method.<br />
3- Declare all needed observers objects that will observe the subject.<br />
4- Each observer must implement an ‘update’ method that  will be called by the subject.</p>
<h2>Observers in Rails</h2>
<p>You can find observers in rails when using ActiveRecord, it’s a way to take out all <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html">ActiveRecord callbacks</a> out of the model, for example a one would do this:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> User <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  after_create <span style="color:#ff3333; font-weight:bold;">:send_email</span>
  private
  <span style="color:#9966CC; font-weight:bold;">def</span> send_email
    <span style="color:#008000; font-style:italic;">#send a welcome email</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>A neater solution is to use Observers:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> UserObserver <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Observer</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> after_create<span style="color:#006600; font-weight:bold;">&#40;</span>user<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;">#send a welcome email</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>You can generate the previous observer using the following command:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">ruby script<span style="color: #000000; font-weight: bold;">/</span>generate observer User</pre></div></div>

<p>You still can have observers that map to models that don’t match with the observer name using the ‘observe’ class method, you also can observe multiple models using the same method:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> NotificationObserver <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Observer</span>
  observe <span style="color:#ff3333; font-weight:bold;">:user</span>, <span style="color:#ff3333; font-weight:bold;">:post</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> after_create<span style="color:#006600; font-weight:bold;">&#40;</span>record<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;">#send thanks email</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Finally don’t forget to add the following line inside config/environment.rb to define observers:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">config.<span style="color:#9900CC;">active_record</span>.<span style="color:#9900CC;">observers</span> = <span style="color:#ff3333; font-weight:bold;">:user_observer</span></pre></div></div>

<h2>Singleton Design Pattern</h2>
<p>According to Wikipedia:</p>
<blockquote><p>In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. (This concept is also sometimes generalized to restrict the instance to a specific number of objects – for example, we can restrict the number of instances to five objects.) This is useful when exactly one object is needed to coordinate actions across the system.</p></blockquote>
<p>The singleton design pattern is used to have one instance of some class, typically there are many places where you might want to do so, just like having one database connection, one LDAP connection, one logger instance or even one configuration object for your application.<br />
In ruby you can use the singleton module to have the job done for you, let’s take ‘application configuration’ as an example and check how we can use ruby to do the job:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># require singleton lib</span>
<span style="color:#CC0066; font-weight:bold;">require</span> ‘singleton’
<span style="color:#9966CC; font-weight:bold;">class</span> AppConfig
  <span style="color:#008000; font-style:italic;"># mixin the singleton module</span>
  <span style="color:#9966CC; font-weight:bold;">include</span> <span style="color:#CC00FF; font-weight:bold;">Singleton</span>
  <span style="color:#008000; font-style:italic;"># do the actual app configuration</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> load_config<span style="color:#006600; font-weight:bold;">&#40;</span>file<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;"># do your work here</span>
    <span style="color:#CC0066; font-weight:bold;">puts</span> “Application configuration file was loaded from file: <span style="color:#008000; font-style:italic;">#{file}”</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
conf1 = AppConfig.<span style="color:#9900CC;">instance</span>
conf1.<span style="color:#9900CC;">load_config</span> “<span style="color:#006600; font-weight:bold;">/</span>home<span style="color:#006600; font-weight:bold;">/</span>khelll<span style="color:#006600; font-weight:bold;">/</span>conf.<span style="color:#9900CC;">yml</span>”
<span style="color:#008000; font-style:italic;">#=&gt;Application configuration file was loaded from file: /home/khelll/conf.yml</span>
conf2 = AppConfig.<span style="color:#9900CC;">instance</span>
<span style="color:#CC0066; font-weight:bold;">puts</span> conf1 == conf2
<span style="color:#008000; font-style:italic;">#=&gt;true</span>
<span style="color:#008000; font-style:italic;"># notice the following 2 lines won’t work</span>
<span style="color:#008000; font-style:italic;"># new method is private</span>
AppConfig.<span style="color:#9900CC;">new</span> <span style="color:#9966CC; font-weight:bold;">rescue</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">puts</span> $!<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;">#=&gt;private method `new’ called for AppConfig:Class</span>
<span style="color:#008000; font-style:italic;"># dup won’t work</span>
conf1.<span style="color:#9900CC;">dup</span> <span style="color:#9966CC; font-weight:bold;">rescue</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">puts</span> $!<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#008000; font-style:italic;">#=&gt;can’t dup instance of singleton AppConfig</span></pre></div></div>

<p>So what does ruby do when you include the singleton method inside your class?<br />
1- It makes the ‘new’ method private and so you can’t use it.<br />
2- It adds a class method called instance that instantiates only one instance of the class.<br />
So to use ruby singleton module you need two things:<br />
1- Require the lib ‘singleton’ then include it inside the desired<br />
class.<br />
2- Use the ‘instance’ method to get the instance you need.</p>
<div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/' addthis:title='Observer and Singleton design patterns in Ruby' ><a class="addthis_button_twitter"></a><a class="addthis_button_facebook"></a><a class="addthis_button_email"></a><a class="addthis_button_print"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://khelll.com/blog/ruby/observer-and-singleton-design-patterns-in-ruby/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

