<?xml version="1.0" encoding="UTF-8" standalone="no"?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:gd="http://schemas.google.com/g/2005" xmlns:georss="http://www.georss.org/georss" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-6761142148052793737</atom:id><lastBuildDate>Thu, 12 Mar 2026 10:11:10 +0000</lastBuildDate><category>javascript</category><category>ruby on rails</category><category>news</category><category>google maps api</category><category>presentation</category><category>css</category><category>mysql</category><category>ruby</category><category>web</category><category>gears</category><category>yui</category><category>rest</category><category>rmagick</category><title>Web Development</title><description>Web 2.0, Ruby, Rails, TDD, BDD, &lt;br&gt;rSpec, XMPP, BOSH, REST,&lt;br&gt;Javascript, Ajax, Google Maps API, &lt;br&gt;Google Gears API, CSS, &lt;br&gt;Java, C#, Social Network, RMagick, Nginx</description><link>http://chamnapchhorn.blogspot.com/</link><managingEditor>noreply@blogger.com (chamnap)</managingEditor><generator>Blogger</generator><openSearch:totalResults>103</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><language>en-us</language><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-3132186931082736371</guid><pubDate>Wed, 23 May 2012 12:56:00 +0000</pubDate><atom:updated>2012-05-24T09:54:26.301+07:00</atom:updated><title>My blog is moved!</title><description>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;
&lt;span style="font-size: x-large;"&gt;I stopped using blogger to do blogging. My new blog is&amp;nbsp;&lt;a href="http://chamnap.github.com/"&gt;chamnap.github.com&lt;/a&gt;.&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-size: x-large;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-size: x-large;"&gt;See you there!&lt;/span&gt;&lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2012/05/blog-moved.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>76</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-8404703751548354636</guid><pubDate>Mon, 02 May 2011 02:24:00 +0000</pubDate><atom:updated>2011-05-02T09:26:38.926+07:00</atom:updated><title>High Performance Website Presentation at Hackerspacepp</title><description>I’m a little bit disappointed in myself. What I intended to do presentation is about Web Scaling, but I ended up with go through the front end side. This presentation will focus on how to make your website faster on the front end side. I did focus on some aspects on HTTP concept as well. Those are rules from Steve Souders, but I modify and adjust to make it clear to the audience.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px" id="__ss_7783873"&gt; &lt;strong style="display:block;margin:12px 0 4px"&gt;&lt;a href="http://www.slideshare.net/cchamnap/high-performance-website-7783873" title="High performance website"&gt;High performance website&lt;/a&gt;&lt;/strong&gt; &lt;iframe src="http://www.slideshare.net/slideshow/embed_code/7783873" width="425" height="355" frameborder="0" marginwidth="0" marginheight="0" scrolling="no"&gt;&lt;/iframe&gt; &lt;div style="padding:5px 0 12px"&gt; View more &lt;a href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a href="http://www.slideshare.net/cchamnap"&gt;Chamnap Chhorn&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2011/05/high-performance-website-presentation.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>21</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-7641631831709968702</guid><pubDate>Tue, 29 Mar 2011 03:42:00 +0000</pubDate><atom:updated>2011-03-29T10:56:32.420+07:00</atom:updated><title>REST Presenation on DevCamp, Hackerspacepp</title><description>Last sunday, I talked to some people, around 10 software developers, about how to build web services using REST architecture. However, I didn't talk on &lt;a href="http://www.slideshare.net/cchamnap/rest-web-services-in-rails"&gt;my previous slide presentation&lt;/a&gt;. I took on &lt;a href="www.slideshare.net/kjbuckley/doing-rest-right-3385800"&gt;Doing REST Right&lt;/a&gt; by Kerry Buckley. I decided to choose this slide because I feel I learnt something new and it's recommended by my boss, Chris. Actually, I were not well-prepared, but the presentation went well. I missed some slides before I went to do this presentation.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px" id="__ss_3385800"&gt; &lt;strong style="display:block;margin:12px 0 4px"&gt;&lt;a href="http://www.slideshare.net/kjbuckley/doing-rest-right-3385800" title="Doing REST Right"&gt;Doing REST Right&lt;/a&gt;&lt;/strong&gt; &lt;object id="__sse3385800" width="425" height="355"&gt; &lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=doingrestright-100310081847-phpapp01&amp;stripped_title=doing-rest-right-3385800&amp;userName=kjbuckley" /&gt; &lt;param name="allowFullScreen" value="true"/&gt; &lt;param name="allowScriptAccess" value="always"/&gt; &lt;embed name="__sse3385800" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=doingrestright-100310081847-phpapp01&amp;stripped_title=doing-rest-right-3385800&amp;userName=kjbuckley" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt; &lt;/object&gt; &lt;div style="padding:5px 0 12px"&gt; View more &lt;a href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a href="http://www.slideshare.net/kjbuckley"&gt;Kerry Buckley&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2011/03/rest-presenation-on-devcamp.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>24</thr:total><enclosure length="3332" type="application/x-shockwave-flash" url="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=doingrestright-100310081847-phpapp01&amp;stripped_title=doing-rest-right-3385800&amp;userName=kjbuckley"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-6963897337485578850</guid><pubDate>Mon, 30 Aug 2010 03:26:00 +0000</pubDate><atom:updated>2010-09-04T15:58:46.974+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>Load Balancer Algorithm Explained</title><description>I've been googling around 2 days just want to know the best way that heavy-load rails sites was handled. I'm having trouble with mongrel clusters, one of which usually dies because of some heavy requests and nginx still forwards request to that frozen mongrel (using nginx simple load balancer). I was curious what are the options to solve this. I have looked at various solutions: &lt;span style="font-weight:bold;"&gt;simple nginx load balancer&lt;/span&gt;, &lt;span style="font-weight:bold;"&gt;fair nginx load balancer&lt;/span&gt;, &lt;span style="font-weight:bold;"&gt;HAProxy&lt;/span&gt;, and finally &lt;span style="font-weight:bold;"&gt;Phusion Passenger&lt;/span&gt;. However, I didn't go through JRuby for deploy rails app and Unicorn.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Simple Load Balancer&lt;/span&gt;&lt;br /&gt;By default, nginx is only a simple robin-round load balancer. What it does is just send those requests to one of those backends (mongrel in this case) in simple manner (a,b,a,b, ...). The round-robin algorithm is often an acceptable tool: if every request finishes within a few milliseconds, there’s no problem. In this scenario, each backend has its own queue for processing concurrent requests. Therefore, if the heavy request comes in, the queue requests in that backend will be waiting and is able to process until that long-running request finishes. So what if that heavy request process longer than 60 seconds, those queue requests will never be able to process because it has been timeout.&lt;br /&gt;Another problem is that nginx would flood mongrels with too many requests and mongrel's request queue was not solid and it would quickly get stuck with too many queued requests.&lt;br /&gt;&lt;br /&gt;Here is the &lt;a href="http://wiki.nginx.org/NginxLoadBalanceExample"&gt;configuration &lt;/a&gt;of nginx simple load balancer.&lt;br /&gt;&lt;pre&gt;http {&lt;br /&gt;  upstream myproject {&lt;br /&gt;    server 127.0.0.1:8000;&lt;br /&gt;    server 127.0.0.1:8001;&lt;br /&gt;    server 127.0.0.1:8002;    &lt;br /&gt;    server 127.0.0.1:8003;&lt;br /&gt;  }&lt;br /&gt; &lt;br /&gt;  server {&lt;br /&gt;    listen 80;&lt;br /&gt;    server_name www.domain.com;&lt;br /&gt;    location / {&lt;br /&gt;      proxy_pass http://myproject;&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Fair Load Balancer&lt;/span&gt;&lt;br /&gt;Seeing this problem, a guy from Engine Yard wrote a &lt;a href="http://nginx.localdomain.pl/wiki/UpstreamFair"&gt;personal patch&lt;/a&gt; by adding a module in nginx called &lt;span style="font-weight:bold;"&gt;fair load balancer&lt;/span&gt;. What it basically does it know many requests each backend is processing and it will avoid sending further requests to already busy backends. By default, fair load balancer will assign request to idle backend first, when all are busy it will use &lt;span style="font-weight:bold;"&gt;weighted least-connection round-robin&lt;/span&gt; (WLC-RR) algorithm, meaning that it will assign the requests using a score that depends on both the number of requests assigned to the peer (as most important) and if all equal, to the peer that had the earliest assignment.&lt;br /&gt;Another mode is whenever the first backend is idle, it's going to get the next request. If it's busy, the request will go to the second backend unless it's busy too etc. &lt;br /&gt;&lt;br /&gt;As you can see, the backend still has its queue requests, and it will run into this scenario:&lt;br /&gt;Suppose we have 3 backends which have 3 requests in their queue, except for the first backend which has only 1 request in its queue.&lt;br /&gt;Backend process A:  [*     ]  (1 request in queue)&lt;br /&gt;Backend process B:  [***   ]  (3 requests in queue)&lt;br /&gt;Backend process C:  [***   ]  (3 requests in queue)&lt;br /&gt;Backend process D:  [***   ]  (3 requests in queue)&lt;br /&gt;&lt;br /&gt;Next, new request comes in, so backend A will have 2 requests where X is the new request.&lt;br /&gt;Backend process A:  [*X    ]  (2 request in queue)&lt;br /&gt;Backend process B:  [***   ]  (3 requests in queue)&lt;br /&gt;Backend process C:  [***   ]  (3 requests in queue)&lt;br /&gt;Backend process D:  [***   ]  (3 requests in queue)&lt;br /&gt;&lt;br /&gt;Assuming that B, C and D are still processing its queues, the next request comes in (called Y), it will be forwarded to backend A because it has the least number of request queues.&lt;br /&gt;Backend process A:  [*XY   ]  (3 requests in queue)&lt;br /&gt;Backend process B:  [***   ]  (3 requests in queue)&lt;br /&gt;Backend process C:  [***   ]  (3 requests in queue)&lt;br /&gt;Backend process D:  [***   ]  (3 requests in queue)&lt;br /&gt;&lt;br /&gt;The problem arises if Backend A needs 60 seconds to process X. Y will never be processed because it has been timeout. It would be much better if Y was forward to other Backends.&lt;br /&gt;&lt;br /&gt;Here is the configuration:&lt;br /&gt;&lt;pre&gt;upstream mongrel {&lt;br /&gt;    fair;&lt;br /&gt;    server 127.0.0.1:5000;&lt;br /&gt;    server 127.0.0.1:5001;&lt;br /&gt;    server 127.0.0.1:5002;&lt;br /&gt;  }&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;HAProxy&lt;/span&gt;&lt;br /&gt;Rails was traditionally and mostly deployed using Apache or nginx  with either a built-in or standalone proxy (like &lt;a href="http://haproxy.1wt.eu/"&gt;HAProxy&lt;/a&gt;) against a cluster of Mongrels or Unicorns.&lt;br /&gt;&lt;blockquote&gt;HAProxy is a free, very fast and reliable solution offering high availability, load balancing, and proxying for TCP and HTTP-based applications.&lt;/blockquote&gt;&lt;br /&gt;&lt;br /&gt;If using HAProxy, the setup is similar to this:&lt;br /&gt;&lt;br /&gt;  &lt;span style="font-weight:bold;"&gt;Web &lt;/span&gt;=&gt; &lt;span style="font-weight:bold;"&gt;Nginx &lt;/span&gt;=&gt; &lt;span style="font-weight:bold;"&gt;HAProxy &lt;/span&gt;=&gt; &lt;span style="font-weight:bold;"&gt;Mongrel&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;In this setup nginx just proxies to a single haproxy instance and haproxy has all registered mongrels configured. HAProxy queue is much more stable and it better balances all the requests between backends than nginx does. HAProxy has better support for upstream ok/fail detection and can also limit each app server to 1 connection (maxconn directive) which is key for mongrel. HAProxy limits the number of requests sent to mongrel instead of blindly forward requests. The fact that mongrel has only 1 request to process makes the application more scalable since the previous problem never happens. If there is one heavy request, processing that request won't affect on other requests since HAProxy only forwards request to the idle mongrel.&lt;br /&gt;&lt;br /&gt;One downside of using this is that it brings any additional latencies.&lt;br /&gt;Another thing is that it's more complicated to setup and administrate than using &lt;a href="http://www.modrails.com/"&gt;Phusion Passenger&lt;/a&gt; a.k.a. modrails or modrack.&lt;br /&gt;&lt;br /&gt;Just to take the advantage of the &lt;span style="font-weight:bold;"&gt;maxconn&lt;/span&gt; directive, try &lt;a href="http://github.com/ry/nginx-ey-balancer"&gt;nginx-ey-balancer&lt;/a&gt;. One thing to keep in mind is that the maxconn is per nginx worker.&lt;br /&gt;&lt;pre&gt;upstream mongrels {&lt;br /&gt;    server 127.0.0.1:8001;&lt;br /&gt;    server 127.0.0.1:8002;&lt;br /&gt;    max_connections 1;&lt;br /&gt;  }&lt;/pre&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Phusion Passenger&lt;/span&gt;&lt;br /&gt;&lt;blockquote&gt;Phusion Passenger is an Nginx module, which makes deploying Ruby and Ruby on Rails applications on Nginx a breeze.&lt;/blockquote&gt;&lt;br /&gt;It's a great tool for me to deploy rails and rack-based ruby applications. Passenger has both nginx and apache module. Passenger comes with feature called &lt;a href="http://www.modrails.com/documentation/Users%20guide%20Nginx.html#PassengerUseGlobalQueue"&gt;global queuing&lt;/a&gt;, which works similar to what I mentioned above.&lt;br /&gt;&lt;br /&gt;The good thing about passenger, it's easier to configure than HAProxy. It has a couple of strategies to load rails application (smart, smart-lv2, conservative). It can even reduce memory to 33% if using &lt;a href="http://www.rubyenterpriseedition.com/"&gt;Ruby Enterprise Edition&lt;/a&gt;. The installation process is to install passenger gem, which is quite up-to-date and support ruby 1.9.&lt;br /&gt;&lt;br /&gt;I won't dig into detail about passenger, you might go through the &lt;a href="http://www.modrails.com/documentation.html"&gt;documentation &lt;/a&gt;by yourself.</description><link>http://chamnapchhorn.blogspot.com/2010/08/load-balancer-algorithm-explained.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>13</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-2503661580222697536</guid><pubDate>Tue, 17 Aug 2010 03:13:00 +0000</pubDate><atom:updated>2010-08-23T13:41:04.479+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">presentation</category><category domain="http://www.blogger.com/atom/ns#">ruby</category><title>Ruby Object Model</title><description>I conduct a training on Ruby Object Model this week. I start talking about Ruby from scratch then the object model of Ruby. At the same time, I discussed about JavaScript object model.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px" id="__ss_4978263"&gt;&lt;strong style="display:block;margin:12px 0 4px"&gt;&lt;a href="http://www.slideshare.net/cchamnap/ruby-object-model-4978263" title="Ruby object model"&gt;Ruby object model&lt;/a&gt;&lt;/strong&gt;&lt;object id="__sse4978263" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=rubyobjectmodel-100816032824-phpapp01&amp;stripped_title=ruby-object-model-4978263" /&gt;&lt;param name="allowFullScreen" value="true"/&gt;&lt;param name="allowScriptAccess" value="always"/&gt;&lt;embed name="__sse4978263" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=rubyobjectmodel-100816032824-phpapp01&amp;stripped_title=ruby-object-model-4978263" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;div style="padding:5px 0 12px"&gt;View more &lt;a href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a href="http://www.slideshare.net/cchamnap"&gt;cchamnap&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2010/08/ruby-object-model.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>5</thr:total><enclosure length="3332" type="application/x-shockwave-flash" url="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=rubyobjectmodel-100816032824-phpapp01&amp;stripped_title=ruby-object-model-4978263"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-8469432277758439455</guid><pubDate>Sat, 31 Jul 2010 01:50:00 +0000</pubDate><atom:updated>2010-08-20T08:54:12.708+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><category domain="http://www.blogger.com/atom/ns#">presentation</category><category domain="http://www.blogger.com/atom/ns#">web</category><title>Cross-Domain Solutions</title><description>Recently, I found a presentation on how to solve cross domain issues. I think it's quite useful for web developers.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px" id="__ss_1636202"&gt;&lt;strong style="display:block;margin:12px 0 4px"&gt;&lt;a href="http://www.slideshare.net/mehmetakin/ajax-world" title="Solving Cross-Domain Issues When Building Mashups"&gt;Solving Cross-Domain Issues When Building Mashups&lt;/a&gt;&lt;/strong&gt;&lt;object id="__sse1636202" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=ajaxworld-090624204735-phpapp01&amp;stripped_title=ajax-world" /&gt;&lt;param name="allowFullScreen" value="true"/&gt;&lt;param name="allowScriptAccess" value="always"/&gt;&lt;embed name="__sse1636202" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=ajaxworld-090624204735-phpapp01&amp;stripped_title=ajax-world" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;div style="padding:5px 0 12px"&gt;View more &lt;a href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a href="http://www.slideshare.net/mehmetakin"&gt;mehmetakin&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2010/07/cross-domain-solutions.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>133</thr:total><enclosure length="3332" type="application/x-shockwave-flash" url="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=ajaxworld-090624204735-phpapp01&amp;stripped_title=ajax-world"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-8799523426899345039</guid><pubDate>Fri, 16 Jul 2010 03:46:00 +0000</pubDate><atom:updated>2010-08-20T08:54:19.019+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">presentation</category><category domain="http://www.blogger.com/atom/ns#">rest</category><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>REST and RAILS</title><description>I made a presentation to InStedd guys recently on REST. This slide cover most parts related to REST and RAILS. Hope it could help.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px" id="__ss_4758443"&gt;&lt;strong style="display:block;margin:12px 0 4px"&gt;&lt;a href="http://www.slideshare.net/cchamnap/rest-web-services-in-rails" title="Rest and Rails"&gt;Rest and Rails&lt;/a&gt;&lt;/strong&gt;&lt;object id="__sse4758443" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=restwebservicesinrails-100715000911-phpapp01&amp;stripped_title=rest-web-services-in-rails" /&gt;&lt;param name="allowFullScreen" value="true"/&gt;&lt;param name="allowScriptAccess" value="always"/&gt;&lt;embed name="__sse4758443" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=restwebservicesinrails-100715000911-phpapp01&amp;stripped_title=rest-web-services-in-rails" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;div style="padding:5px 0 12px"&gt;View more &lt;a href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a href="http://www.slideshare.net/cchamnap"&gt;cchamnap&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2010/07/rest-and-rails.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>2</thr:total><enclosure length="3332" type="application/x-shockwave-flash" url="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=restwebservicesinrails-100715000911-phpapp01&amp;stripped_title=rest-web-services-in-rails"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-5301529849123717727</guid><pubDate>Mon, 31 May 2010 07:01:00 +0000</pubDate><atom:updated>2010-08-20T16:51:27.701+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby</category><title>ruby alias_method for class methods</title><description>Generally, a ruby programmer could alias instance methods of a ruby object, but how could he alias class methods instead? The answer is he needs to understand how "self" works in ruby. If not yet knows, check out my &lt;a href="http://www.slideshare.net/cchamnap/ruby-object-model-4978263"&gt;presentation&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="ruby"&gt;&lt;br /&gt;class Foo&lt;br /&gt;  def a; 'a'; end&lt;br /&gt;  alias_method :alias_for_a, :a&lt;br /&gt;&lt;br /&gt;  def self.b; 'b'; end&lt;br /&gt;  class &amp;lt;&amp;lt;self&lt;br /&gt;    alias_method :alias_for_b, :b&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;puts Foo.new.a&lt;br /&gt;puts Foo.new.alias_for_a&lt;br /&gt;&lt;br /&gt;puts Foo.b&lt;br /&gt;puts Foo.alias_for_b&lt;br /&gt;&lt;/pre&gt;</description><link>http://chamnapchhorn.blogspot.com/2010/05/ruby-aliasmethod-for-class-methods.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>11</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-4129043679609270801</guid><pubDate>Fri, 19 Feb 2010 10:50:00 +0000</pubDate><atom:updated>2010-09-05T08:57:07.849+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><category domain="http://www.blogger.com/atom/ns#">ruby</category><title>Meta-programming in Ruby and JavaScript</title><description>Recently, I have been working with writing a ruby gem, Yoolk API Gem. What is really interesting for me is I do some meta programming and object-oriented programming in Ruby which I have never experienced before. A few month later, there is a requirement that my team needs to write in JavaScript, but I don't want to touch JavaScript really much. Therefore, my team member took over this task. Whenever I write code in Ruby, I just try to think how to do it in JavaScript as well. Several things that came up to my mind with some from my team member:&lt;br /&gt;&lt;br /&gt;1. Defer class from a variable.&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;// JavaScript&lt;br /&gt;var klass = "Person";&lt;br /&gt;p = new window[klass]; //class without namespace&lt;br /&gt;p = new yoolk[klass]; //class with namespace&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;pre name="code" class="ruby"&gt;&lt;br /&gt;# Ruby&lt;br /&gt;klass = "Person"&lt;br /&gt;p = Object.const_get(klass).new #class without namespace&lt;br /&gt;p = Yoolk.const_get(klass).new #class with namespace&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;2. Access class method from instance object&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;// JavaScript&lt;br /&gt;var p = new Person();&lt;br /&gt;p.constructor.getCount();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;pre name="code" class="ruby"&gt;&lt;br /&gt;#Ruby&lt;br /&gt;p = Person.new&lt;br /&gt;p.class.count&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;3. Define method of an object&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;//JavaScript&lt;br /&gt;var p = new Person();&lt;br /&gt;p.hello = function() {&lt;br /&gt;  alert('hello');&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;pre name="code" class="ruby"&gt;&lt;br /&gt;//Ruby&lt;br /&gt;p = Person.new&lt;br /&gt;def p.hello&lt;br /&gt;  puts "hello"&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;4. Define class methods&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;//JavaScript&lt;br /&gt;Person.hello = function() {&lt;br /&gt;  alert('hello');&lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;pre name="code" class="ruby"&gt;&lt;br /&gt;//Ruby&lt;br /&gt;def Person.hello&lt;br /&gt;  puts "hello"&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;</description><link>http://chamnapchhorn.blogspot.com/2010/02/meta-programming-in-ruby-and-javascript.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>22</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-4360924167161407139</guid><pubDate>Wed, 14 Oct 2009 07:16:00 +0000</pubDate><atom:updated>2009-10-19T11:46:25.984+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>Script Console Tricks</title><description>Script console in rails helps me very much to debug my applications. However, I usually encounter an annoying problem with ActiveRecord. I want to see the generated SQL that has been executed. I never have enough time to figure out this until last week. Just add the following code to your environment.rb, you could see the generated SQL statement.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;if "irb" == $0&lt;br /&gt;  ActiveRecord::Base.logger = Logger.new(STDOUT)  # ActiveRecord&lt;br /&gt;  ActiveResource::Base.logger = Logger.new(STDOUT)  # ActiveResource&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;For more information:&lt;br /&gt;&lt;a href="http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord"&gt;http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord&lt;/a&gt;&lt;br /&gt;&lt;a href="http://railscasts.com/episodes/48-console-tricks"&gt;http://railscasts.com/episodes/48-console-tricks&lt;/a&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/10/script-console-tricks.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>9</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-419767841573897220</guid><pubDate>Thu, 08 Oct 2009 04:26:00 +0000</pubDate><atom:updated>2010-08-20T08:54:33.369+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">presentation</category><category domain="http://www.blogger.com/atom/ns#">web</category><title>My Presentation at Barcamp Phnom Penh 2009</title><description>I did two presentations at Barcampp in last week. One is for people who starts learning about the web. I talked on many basic concepts, the history, and how the web works. Some of friends complained me that my slide is too much. Anyway, I think I missed several main points. I just feel it is a prime concept of the web, and it drives me really well since I started learning it. The other is about JavaScript in OOP way. It is the same topic but very compact as I used to do presentation in my office. I did fairly good with borey since some of the audiences interest my presentation.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px;text-align:left" id="__ss_2046225"&gt;&lt;a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/cchamnap/introduction-to-web-architecture" title="Introduction to Web Architecture"&gt;Introduction to Web Architecture&lt;/a&gt;&lt;object style="margin:0px" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=introductiontowebarchitecture-090922221506-phpapp01&amp;stripped_title=introduction-to-web-architecture" /&gt;&lt;param name="allowFullScreen" value="true"/&gt;&lt;param name="allowScriptAccess" value="always"/&gt;&lt;embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=introductiontowebarchitecture-090922221506-phpapp01&amp;stripped_title=introduction-to-web-architecture" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;"&gt;View more &lt;a style="text-decoration:underline;" href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a style="text-decoration:underline;" href="http://www.slideshare.net/cchamnap"&gt;cchamnap&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/10/my-presentation-at-barcamp-phnom-penh.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>1</thr:total><enclosure length="3332" type="application/x-shockwave-flash" url="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=introductiontowebarchitecture-090922221506-phpapp01&amp;stripped_title=introduction-to-web-architecture"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-7037022000664296624</guid><pubDate>Sat, 05 Sep 2009 04:33:00 +0000</pubDate><atom:updated>2010-08-20T08:53:56.690+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">presentation</category><title>Principles in Refactoring</title><description>This week, in my office we did a study group, and vorleak and I were moderators in that session. We studied the book from Refactoring the Existing Code by Martin Fowler. Here is the slide I prepared.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px;text-align:left" id="__ss_1961578"&gt;&lt;a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/cchamnap/principles-in-refactoring" title="Principles in Refactoring"&gt;Principles in Refactoring&lt;/a&gt;&lt;object style="margin:0px" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=principlesinrefactoring-090906230021-phpapp01&amp;stripped_title=principles-in-refactoring" /&gt;&lt;param name="allowFullScreen" value="true"/&gt;&lt;param name="allowScriptAccess" value="always"/&gt;&lt;embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=principlesinrefactoring-090906230021-phpapp01&amp;stripped_title=principles-in-refactoring" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;"&gt;View more &lt;a style="text-decoration:underline;" href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a style="text-decoration:underline;" href="http://www.slideshare.net/cchamnap"&gt;cchamnap&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/09/principles-in-refactoring.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>1</thr:total><enclosure length="3332" type="application/x-shockwave-flash" url="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=principlesinrefactoring-090906230021-phpapp01&amp;stripped_title=principles-in-refactoring"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-5801985646602093655</guid><pubDate>Sat, 29 Aug 2009 08:29:00 +0000</pubDate><atom:updated>2010-08-20T08:54:53.957+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>Action Caching</title><description>Recently, I have been working with RESTful web services. I came to a caching stage where I need to cache some requests that map to my actions. The problem is that I have actions with multiple possible routes, therefore those routes should be cached differently. For example:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;/people/1?display=details&lt;br /&gt;/people/1?display=summary&lt;br /&gt;/people/1?display=details&amp;format=xml&lt;br /&gt;/people/1?display=summary&amp;format=json&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Fortunately, there is an option inside caches_action called :cache_path. All you need to do is to pass a proc object and return the path you want to cache. It is called with the current controller instance. In this case,&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;  caches_action :index, :show, :cache_path =&gt; Proc.new { |c|&lt;br /&gt;    request_url = { :controller =&gt; c.params[:controller], :action =&gt; c.params[:action] }.merge(c.request.query_parameters)&lt;br /&gt;    c.url_for request_url&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;There is another problem when the request is coming without format, the cache returns the result with content-type: text/html. To solve this, add a before_filter inside application controller to assign the headers['Content-type'].&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;  def set_default_response_format&lt;br /&gt;    response.headers['Content-type'] = 'application/xml; charset=utf-8' if params[:format].nil?&lt;br /&gt;  end&lt;br /&gt;&lt;/pre&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/08/action-caching.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-1543620890150642532</guid><pubDate>Sat, 22 Aug 2009 02:30:00 +0000</pubDate><atom:updated>2010-08-20T08:55:01.947+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">web</category><title>MVC</title><description>Many Rails newcomers, even some people who know MVC quite well, often confuse how to code in the right way. The controller are usually fat, and the logic spreads across the whole application. The views still messy because it contains logic and even worse people often code like a controller (query to db). However, the model are usually skinny. I could say there is no restrictions in the way you code. It is a set of disciplines that every developers must know in order to have a cheaper maintenance.&lt;br /&gt;&lt;br /&gt;MVC has been successful for many reasons, and some of those reasons are “readability”, “maintainability”, “modularity”, and “separation of concerns”. You’d like your code to have those properties, right? The rules of thumb are:&lt;br /&gt;&lt;br /&gt;1. Controller should be skinny. This is what it means to have a controller know what to do without knowing the details of how to do it. &lt;br /&gt;2. Any complexity related to building a business logic will be specified and implemented in the Model.&lt;br /&gt;3. Inside View, access to instance variables that have been defined in Controller. Try not to use if-else condition or loop as much as possible.&lt;br /&gt;&lt;br /&gt;By putting everything in the right place, you would benefit from a lot of MVC pattern.&lt;br /&gt;&lt;br /&gt;Good example can be found on:&lt;br /&gt;&lt;a href="http://www.therailsway.com/2007/6/1/railsconf-recap-skinny-controllers"&gt;http://www.therailsway.com/2007/6/1/railsconf-recap-skinny-controllers&lt;/a&gt;&lt;br /&gt;&lt;a href="http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model"&gt;http://weblog.jamisbuck.org/2006/10/18/skinny-controller-fat-model&lt;/a&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/08/this-is-what-it-means-to-have.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-7544957222579683619</guid><pubDate>Tue, 21 Jul 2009 10:08:00 +0000</pubDate><atom:updated>2009-07-25T17:36:12.684+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>Sending mail to developer about exception errors</title><description>I want my application to send me a mail about any errors that occurs during production. Basically, I want to see a detail report like in development environment. All I have to do is to override &lt;code&gt;rescue_action_in_public&lt;/code&gt;. This method by default calls &lt;code&gt;render_optional_error_file&lt;/code&gt; method to render a static page based on status code thrown. &lt;code&gt;rescue_action_locally&lt;/code&gt; method by default will render details diagnostics from a controller action. Therefore, I just combine all of these methods into rescue_action_in_public and add some code to send mail.&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;def rescue_action_in_public(exception)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;render_optional_error_file response_code_for_rescue(exception)&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;@template.instance_variable_set("@exception", exception)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;@template.instance_variable_set("@rescues_path", RESCUES_TEMPLATE_PATH)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;@template.instance_variable_set("@contents",&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;@template.render(:file =&gt; template_path_for_local_rescue(exception)))&lt;br /&gt;&lt;br /&gt;    # send mail to developers&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;mail = ExceptionNotifier.create_sent(@template)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;mail.set_content_type("text/html")&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;ExceptionNotifier.deliver(mail)&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here is my ExceptionNotifier class, just extract needed variable to be available inside my view.&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;class ExceptionNotifier &lt; ActionMailer::Base&lt;br /&gt;  &lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;def sent(template)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@subject               = 'Bug Reports'&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@body["request"]       = template.request&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@body["response"]      = template.response&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@body["exception"]     = template.instance_variable_get("@exception")&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@body["rescues_path"]  = template.instance_variable_get("@rescues_path")&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@recipients = ['chamnapchhorn@gmail.com', 'ungsophy@gmail.com']&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@from       = 'noreply@gmail.com'&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@headers    = {}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;end&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here is my view, the default view for exception. I just change to locate new variables only.&lt;br /&gt;&lt;pre name="code" class="html"&gt;&lt;br /&gt;&amp;lt;h1&amp;gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;%=h @exception.class.to_s %&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;% if @request.parameters['controller'] %&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;in &lt;%=h @request.parameters['controller'].humanize %&gt;Controller&lt;% if @request.parameters['action'] %&gt;#&lt;%=h @request.parameters['action'] %&gt;&lt;% end %&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;% end %&gt;&lt;br /&gt;&amp;lt;/h1&amp;gt;&lt;br /&gt;&amp;lt;pre&amp;gt;&lt;%=h @exception.clean_message %&gt;&amp;lt;/pre&amp;gt;&lt;br /&gt;&lt;br /&gt;&lt;%= render :file =&gt; @rescues_path["rescues/_trace.erb"] %&gt;&lt;br /&gt;&lt;br /&gt;&lt;%= render :file =&gt; @rescues_path["rescues/_request_and_response.erb"], :locals =&gt; { :request =&gt; @request, :response =&gt; @response } %&gt;&lt;br /&gt;&lt;/pre&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/07/sending-report-developer.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>3</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-2672112506476727939</guid><pubDate>Fri, 10 Jul 2009 09:55:00 +0000</pubDate><atom:updated>2009-07-25T17:42:39.274+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>Handling Exception at the Application Level in Rails</title><description>At last the point of the project, I found one more important thing that is quite useful and it could reduce the code 20%. That's when I did a handling service error on both server and client. I find myself have been repeating the code on the way. Luckily, after discussion with my colleague, I came up with idea to handle in application controller. It means that instead of handle exception on all of my controllers, I could just handle in a single place whenever exception has raised from these controllers.&lt;br /&gt;Basically, there are two methods (&lt;code&gt;rescue_action&lt;/code&gt; and &lt;code&gt;rescue_action_in_public&lt;/code&gt;) that you would need to override based on your needs. By default, these two methods do the best job to handle exception both in development and production mode. &lt;code&gt;rescue_action&lt;/code&gt; method will be called with an exception parameter that raises inside an action method. &lt;code&gt;rescue_action_in_public method&lt;/code&gt;, however, is used for public exception handling (for requests answering false to &lt;code&gt;local_request?&lt;/code&gt;). &lt;code&gt;local_request?&lt;/code&gt; method tells which rescue_*** method to call.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://api.rubyonrails.org/classes/ActionController/Rescue.html"&gt;http://api.rubyonrails.org/classes/ActionController/Rescue.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;More importantly, we can handle exceptions for specific controller instead of the whole. All you need to do is to override one of these methods inside that controller.&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;class PostsController &lt; ApplicationController&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;def rescue_action_in_public(exception)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case(exception)&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;when ActiveRecord::RecordNotFound then render :file =&gt; '/bad_record'&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;when NoMethodError then render :file =&gt; '/no_method'&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;else render :file =&gt; '/error'&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;end&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We can even handle them in a much cleaner way rather than if/else statement by using rescue_from. What it does is that it maps an exception type to handler method. This handler method can take either an exception parameter or a non-argument. We can even specify a proc or block.&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;class PostsController &lt; ApplicationController&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;# Declare exception to handler methods&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;rescue_from ActiveRecord::RecordNotFound, :with =&gt; :bad_record&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;rescue_from NoMethodError, :with =&gt; :show_error&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;def bad_record; render :file =&gt; '/bad_record'; end&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;def show_error(exception); render :text =&gt; exception.message; end&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;a href="http://ryandaigle.com/articles/2007/9/24/what-s-new-in-edge-rails-better-exception-handling"&gt;http://ryandaigle.com/articles/2007/9/24/what-s-new-in-edge-rails-better-exception-handling&lt;/a&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/07/handling-exception-at-application-level.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-3156078894202383489</guid><pubDate>Sat, 27 Jun 2009 11:05:00 +0000</pubDate><atom:updated>2009-07-27T11:08:18.571+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><title>Maintaining Javascript Pop-Up Window Communication Across Window Opener Page Loads</title><description>I came across a blog post that talks how to maintain a reference to javascript popup window while the parent window has been navigated away. This scenario doesn't want to reload the child popup window. I just quoted out from &lt;a href="http://www.1pixelout.net/2006/12/15/cross-window-javascript-communication-20/"&gt;1 Pixel Out&lt;/a&gt;. There is a really nick trick.&lt;br /&gt;&lt;br /&gt;In the main window:&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;var popupWin = null;&lt;br /&gt;&lt;br /&gt;function openPopup() {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;var url = "popup.htm";&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;popupWin = open( "", "popupWin", "width=500,height=400" );&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;if( !popupWin || popupWin.closed || !popupWin.doSomething ) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;popupWin = window.open( url, "popupWin", "width=500,height=400" );&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;} else {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;popupWin.focus();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;function doSomething() {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;openPopup();&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;popupWin.doSomething();&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;In the popup:&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;self.focus();&lt;br /&gt;&lt;br /&gt;function doSomething() {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;alert("I'm doing something");&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;a href="http://www.bennadel.com/blog/89-Maintaining-Javascript-Pop-Up-Window-Communication-Across-Window-Opener-Page-Loads.htm"&gt;http://www.bennadel.com/blog/89-Maintaining-Javascript-Pop-Up-Window-Communication-Across-Window-Opener-Page-Loads.htm&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.1pixelout.net/2005/04/19/cross-window-javascript-communication/"&gt;http://www.1pixelout.net/2005/04/19/cross-window-javascript-communication/&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.1pixelout.net/2006/12/15/cross-window-javascript-communication-20/"&gt;http://www.1pixelout.net/2006/12/15/cross-window-javascript-communication-20/&lt;/a&gt;&lt;br /&gt;&lt;a href="http://www.1pixelout.net/wp-content/downloads/popups20.zip"&gt;http://www.1pixelout.net/wp-content/downloads/popups20.zip&lt;/a&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/06/maintaining-javascript-pop-up-window.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-8426930390371482210</guid><pubDate>Sat, 27 Jun 2009 07:10:00 +0000</pubDate><atom:updated>2009-07-27T11:10:14.969+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><title>Cross-window Javascript communication</title><description>It reminds me about uploading via iframe that I did a year ago when my colleague asked me to help with login openid in a popup window. It's a similar story with this problem. Actually, login with openid could not place in a iframe because you could the code that prevents this.&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;&amp;lt;script type="text/javascript"&amp;gt;if(top == self) { document.write(""); } else  { top.location.href = "http://www.yahoo.com"; }&amp;lt;/script&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now, let's see a quick summary on this basic communication.&lt;br /&gt;&lt;br /&gt;Communication from parent to child window, you need to a reference of the child window so that can call any function in the child window.&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;// Create a new popup window&lt;br /&gt;var popupWin = window.open(url, "popupWin");&lt;br /&gt;&lt;br /&gt;// To call functions defined in the popup:&lt;br /&gt;popupWin.doSomething();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Communication from child to parent window, you need to use this way:&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;window.opener.doSomethingOnParent();&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here is the problem, the parent window needs to know when the uploading (in iframe) or logging in (in popup window) is done. The only way that the parent window can notified by the child window after finish processing. Usually, for uploading and logging in with openid, the action in your controller would render a view back. The trick is here on the onload of the body, you could notify the parent window.&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;def login&lt;br /&gt;  @status = "something"&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;#view&lt;br /&gt;&amp;lt;html&amp;gt;&amp;lt;head&amp;gt;&amp;lt;/head&amp;gt;&lt;br /&gt;&amp;lt;body onload="window.opener.handleOpenIDResponse('" + @status + "');window.close();"&amp;gt;&lt;br /&gt;&amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;That would solve the problem, and you could send any information back through your view.</description><link>http://chamnapchhorn.blogspot.com/2009/06/cross-window-javascript-communication.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-8509927370996612874</guid><pubDate>Thu, 18 Jun 2009 08:46:00 +0000</pubDate><atom:updated>2009-07-27T11:16:22.953+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>has_and_belongs_to_many or has_many :through?</title><description>Well, I had been quite confusing about these two topics before I read some rails books. These are just different ways to do many to many relationships in ActiveRecord.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;has_and_belongs_to_many (habtm)&lt;/b&gt;&lt;br /&gt;habtm is the very old way since rails 1.2. It creates a link between associated models through an intermediate join table.&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;class CreateProjectsProgrammers &lt; ActiveRecord::Migration&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;def self.up&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;create_table :projects_programmers, :id =&gt; false do |t|&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;t.column :project_id, :integer, :null =&gt; false&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;t.column :programmer_id, :integer, :null =&gt; false&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;end&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;end&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;def self.down&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;drop_table :projects_programmers&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;end&lt;br /&gt;end&lt;br /&gt;class Programmer &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_and_belongs_to_many :projects       # foreign keys in the join table&lt;br /&gt;end&lt;br /&gt;class Project &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_and_belongs_to_many :programmers    # foreign keys in the join table&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Note that an id primary key is not needed in the join table and there is no join model, only join table. Here we will face a problem when we want to add extra columns on the join table. If it is in rails 1.2, we would have used &lt;code&gt;push_with_attributes&lt;/code&gt; to do this. However, &lt;code&gt;push_with_attributes&lt;/code&gt; has been deprecated in favor of a far more powerful technique, where regular Active Record models are used as join tables (remember that with habtm, the join table is not an Active Record object).&lt;br /&gt;&lt;br /&gt;To conclude, habtm is a simple way to do a many-to-many relationship using a join table when the join table doesn't have extra columns. You will need to upgrade the relationship to use &lt;code&gt;has_many :through&lt;/code&gt; once you need to add additional columns.&lt;br /&gt;&lt;br /&gt;&lt;b&gt;has_many :through&lt;/b&gt;&lt;br /&gt;Records in the join table of habtm implementation has no independent existence. Later, we will find it very soon that the join table has a life of its own and should have a model when we add extra columns on that join table. Let's talk about relationship between article, user, and the join model is reading.&lt;br /&gt;&lt;br /&gt;When a user reads an article, we can record the fact.&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;class Article &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_many :readings&lt;br /&gt;end&lt;br /&gt;class User &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_many :readings&lt;br /&gt;end&lt;br /&gt;class Reading &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;belongs_to :article&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;belongs_to :user&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;reading = Reading.new&lt;br /&gt;reading.rating = params[:rating]&lt;br /&gt;reading.read_at = Time.now&lt;br /&gt;reading.article = current_article&lt;br /&gt;reading.user = session[:user]&lt;br /&gt;reading.save&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here we lost what habtm solved. We could not ask a user which articles that they has read and vice versa. To solve this, use :through options inside has_many.&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;class Article &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_many :readings&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_many :users, :through =&gt; :readings&lt;br /&gt;end&lt;br /&gt;class Reading &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;belongs_to :article&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;belongs_to :user&lt;br /&gt;end&lt;br /&gt;class User &lt; ActiveRecord::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_many :readings&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;has_many :articles, :through =&gt; :readings&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Now, you could do query both direction:&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;readers = an_article.users&lt;br /&gt;articles = a_reader.articles&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Unlike a normal has_many, ActiveRecord won’t let us add an object to the the has_many :through association if both ends of the relationship are unsaved records. The create method saves the record before adding it, so it does work as expected, provided the parent object isn’t unsaved itself. To add extra attributes:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;user.readings.create(:read_at =&gt; Time.now,&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;:rating =&gt; params[:rating],&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;:article =&gt; Article.new)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Choosing which way to build a many-to-many relationship is not always simple. If you need to work with the relationship model as its own entity, use has_many :through. Use has_and_belongs_to_many when working with legacy schemas or when you never work directly with the relationship itself.&lt;br /&gt;&lt;br /&gt;&lt;a href="http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off"&gt;http://blog.hasmanythrough.com/2006/4/20/many-to-many-dance-off&lt;/a&gt;&lt;br /&gt;&lt;a href="http://blog.hasmanythrough.com/2006/4/17/join-models-not-proxy-collections"&gt;http://blog.hasmanythrough.com/2006/4/17/join-models-not-proxy-collections&lt;/a&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/06/hasandbelongstomany-or-hasmany-through.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-2856585702419930140</guid><pubDate>Wed, 03 Jun 2009 01:23:00 +0000</pubDate><atom:updated>2009-07-27T11:12:21.377+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>Proper use of session</title><description>Consider the following scenario, you want to store information about current user. After successful login, you might do this.&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;user = User.authenticate(params[:user_name], params[:password])&lt;br /&gt;if user&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;session[:current_user] = user.attributes&lt;br /&gt;else&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;flash[:notice] = "Email and password do not match."&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;redirect_to :controller =&gt; "login"&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Everything would work as you expected except when you try to change the structure of your session. This would make sessions of online users invalid while they are using your web application. For example, they will feel annoying while they are adding items to their wish lists. Another problem is that you want to make that session invalid after you delete that user account, for example. That won't work because you stored the entire record in his session. The only way to do is to add before_filter in application controller to check the existence of the current user. That would make another job to do it.&lt;br /&gt;&lt;br /&gt;The best practice is  store only simple data in the session: strings, numbers, and so on. Keep your application objects in the database, and then reference them using their primary keys from the session data. &lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&lt;br /&gt;class ApplicationController &lt; ActionController::Base&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;before_filter :get_current_user&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;private&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;def get_current_user&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;@current_user = User.find_by_id(session[:user_id])&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;end&lt;br /&gt;end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here you can access @current_user everywhere in your application and solve many issues during development.</description><link>http://chamnapchhorn.blogspot.com/2009/06/proper-use-of-session.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-7762041590822974093</guid><pubDate>Thu, 14 May 2009 04:03:00 +0000</pubDate><atom:updated>2009-07-27T11:15:16.358+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>Custom Rake Tasks</title><description>I came across to write a custom rake script for my rails application. Because my application is rich client side application and doesn't use id for any of my models. Instead, it used UUID as a primary key. I got some problems while changing this, and one of them is rails rake commands such as rake &lt;code&gt;db:test:prepare, rake test:functionals&lt;/code&gt;, .... For my application, these two commands didn't work really well since it makes my test database messed with autonumber id of all tables. Here, my rake script to load to my test database. Pay attention to mysql command, in this case, I need to run several commands inside mysql command.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="rails"&gt;&lt;br /&gt;  task :load_test_db do&lt;br /&gt;    #load data to development&lt;br /&gt;    Rake::Task["db:fixtures:load"].invoke&lt;br /&gt;    &lt;br /&gt;    #clone development to test&lt;br /&gt;    Rake::Task["db:test:clone_structure"].invoke&lt;br /&gt;    &lt;br /&gt;    #pull data from development&lt;br /&gt;    sh "mysqldump &gt; test.sql development_ncdd_templates -u root"&lt;br /&gt;&lt;br /&gt;    sh "mysql -u root &lt;&lt; EOF&lt;br /&gt;       use test_ncdd_templates;&lt;br /&gt;       source test.sql;&lt;br /&gt;       exit&lt;br /&gt;    EOF"&lt;br /&gt;  end&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;If you want to run bash command, take this as an example. I'm not a expert of shell script, but it works for me anyway.&lt;br /&gt;&lt;br /&gt;   sh "#!/bin/bash&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;cd lib&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;ruby to_yml.rb&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;cd .."&lt;br /&gt;&lt;br /&gt;Here are some excellent sources:&lt;br /&gt;&lt;a href="http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial"&gt;http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial&lt;/a&gt;&lt;br /&gt;&lt;a href="http://railscasts.com/episodes/66-custom-rake-tasks"&gt;http://railscasts.com/episodes/66-custom-rake-tasks&lt;/a&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/05/custom-rake-tasks.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-4515566835543181045</guid><pubDate>Wed, 13 May 2009 03:59:00 +0000</pubDate><atom:updated>2009-05-13T11:08:03.262+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><title>JavaScript in Object-Oriented Way</title><description>I conducted a training to some developers in my office about one full day, yesterday. It is quite exhausted anyway, but everyone seems understand really well. This slide covers many advanced features of JavaScript: Function, Object, Closure,.... Some other points I have pointed out in this slide are about how to make private variable, public variable, static variable, privileged variable and how to do inheritance. I took about 20 different sources as my references and three famous authors. It took me two weeks, at every weekend, to finish this slide.&lt;br /&gt;&lt;br /&gt;&lt;div style="width:425px;text-align:left" id="__ss_1426608"&gt;&lt;a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/cchamnap/javascript-in-objectoriented-way?type=powerpoint" title="JavaScript in Object-Oriented Way"&gt;JavaScript in Object-Oriented Way&lt;/a&gt;&lt;object style="margin:0px" width="425" height="355"&gt;&lt;param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=javascriptinobject-orientedway-090512225827-phpapp02&amp;stripped_title=javascript-in-objectoriented-way" /&gt;&lt;param name="allowFullScreen" value="true"/&gt;&lt;param name="allowScriptAccess" value="always"/&gt;&lt;embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=javascriptinobject-orientedway-090512225827-phpapp02&amp;stripped_title=javascript-in-objectoriented-way" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"&gt;&lt;/embed&gt;&lt;/object&gt;&lt;div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;"&gt;View more &lt;a style="text-decoration:underline;" href="http://www.slideshare.net/"&gt;presentations&lt;/a&gt; from &lt;a style="text-decoration:underline;" href="http://www.slideshare.net/cchamnap"&gt;cchamnap&lt;/a&gt;.&lt;/div&gt;&lt;/div&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/05/javascript-in-object-oriented-way.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>2</thr:total><enclosure length="3332" type="application/x-shockwave-flash" url="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=javascriptinobject-orientedway-090512225827-phpapp02&amp;stripped_title=javascript-in-objectoriented-way"/></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-5429879078678621629</guid><pubDate>Thu, 07 May 2009 04:41:00 +0000</pubDate><atom:updated>2009-06-14T15:50:38.107+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><title>JavaScript Mixins</title><description>I have just reviewed JavaScript Design Patterns, and I think it is good to mention this.&lt;br /&gt;&lt;br /&gt;It is possible to do a mixin class in JavaScript as in Ruby. This is another way to make our code reuse without inheritance. Consider you have a function, and you wish to use in many classes. In practice, you create a class that contains your general-purpose methods, and then use it to augment other classes. Class with these general-purpose methods is called Mixin class. It is generally not instantiated or called directly, instead it exists to provide methods to other classes.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;var Mixin = function() {};&lt;br /&gt;Mixin.prototype = {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;serialize: function() {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;var output = [];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;for(key in this) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;output.push(key + ': ' + this[key]);&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;return output.join(', ');&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;};&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;This sort of method could potentially be useful in many different types of classes, but it doesn’t make sense to have each of these classes inherit from Mixin. Similarly, duplicating the code in each class doesn’t make much sense either. The best approach is to use the augment function to add this method to each class that needs it:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;augment(Author, Mixin);&lt;br /&gt;&lt;br /&gt;var author = new Author('Ross Harmes', ['JavaScript Design Patterns']);&lt;br /&gt;var serializedString = author.serialize();&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;This can be thought of as a way to implement multiple inheritance in JavaScript.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/* Augment function. */&lt;br /&gt;function augment(receivingClass, givingClass) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;for(methodName in givingClass.prototype) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if(!receivingClass.prototype[methodName]) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;receivingClass.prototype[methodName] = givingClass.prototype[methodName];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;A more robust augment allows copying one or two of them over to another class.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/* Augment function, improved. */&lt;br /&gt;function augment(receivingClass, givingClass) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;if(arguments[2]) { // Only give certain methods.&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;for(var i = 2, len = arguments.length; i &lt; len; i++) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;else { // Give all methods.&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;for(methodName in givingClass.prototype) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if(!receivingClass.prototype[methodName]) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;receivingClass.prototype[methodName] = givingClass.prototype[methodName];&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;You can now write augment(Author, Mixin, 'serialize'); to only augment Author with the single serialize method.&lt;br /&gt;&lt;br /&gt;In other times, you don't have to need this augment function in order to do Mixins. You could do this by using apply or call method inside constructor function.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;var Author = function(name, books) {&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;this.name = name || "";&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;this.books = books || [];&lt;br /&gt;&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;Mixin.apply(this);&lt;br /&gt;};&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Often it makes more sense to augment a class with a few methods than it does to make&lt;br /&gt;one class inherit from another. This is a lightweight way to prevent code duplication. Unfortunately, there aren’t many situations where it can be used. Only methods general enough to be used in very dissimilar classes make good candidates for sharing (if the classes aren’t that dissimilar, normal inheritance is often a better choice).</description><link>http://chamnapchhorn.blogspot.com/2009/05/javascript-mixins.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>108</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-8560760159261924</guid><pubDate>Thu, 07 May 2009 04:40:00 +0000</pubDate><atom:updated>2010-01-11T09:52:47.042+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">javascript</category><title>Prototypal Inheritance vs. Classical Inheritance</title><description>While it is possible to emulate classical inheritance like Java or C#, it is clear that we do prototypal inheritance by taking advantages of prototype lookup chains. Each has its own advantages and disadvantages. Here I quoted from JavaScript Design Patterns:&lt;br /&gt;&lt;br /&gt;The classical approach to creating an object is to (a) define the structure of the object, using&lt;br /&gt;a class declaration, and (b) instantiate that class to create a new object. Objects created in this&lt;br /&gt;manner have their own copies of all instance attributes, plus a link to the single copy of each&lt;br /&gt;of the instance methods.&lt;br /&gt;&lt;br /&gt;In prototypal inheritance, instead of defining the structure through a class, you simply&lt;br /&gt;create an object. This object then gets reused by new objects, thanks to the way that prototype&lt;br /&gt;chain lookups work. It is called the &lt;span style="font-style:italic;"&gt;prototype object&lt;/span&gt; because it provides a prototype for what the other objects should look like.&lt;br /&gt;&lt;br /&gt;Instead of using a constructor function named Person to define the class structure, Person&lt;br /&gt;is now an object literal. It is the prototype object for any other Person-like objects that you want to create. Define all attributes and methods you want these objects to have, and give them&lt;br /&gt;default values. &lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/* Person Prototype Object. */&lt;br /&gt;var Person = {&lt;br /&gt;   name: 'default name',&lt;br /&gt;   getName: function() {&lt;br /&gt;     return this.name;&lt;br /&gt;   }&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;var reader = clone(Person);&lt;br /&gt;alert(reader.getName()); // This will output 'default name'.&lt;br /&gt;reader.name = 'John Smith';&lt;br /&gt;alert(reader.getName()); // This will now output 'John Smith'.&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;To create a new Person-like object, use the clone function. This provides an empty object with&lt;br /&gt;the prototype attribute set to the prototype object. This means that if any method or attribute&lt;br /&gt;lookup on this object fails, that lookup will instead look to the prototype object.&lt;br /&gt;To create Author, you make a clone.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/* Author Prototype Object. */&lt;br /&gt;var Author = clone(Person);&lt;br /&gt;Author.books = []; // Default value.&lt;br /&gt;Author.getBooks = function() {&lt;br /&gt;  return this.books;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;var author0 = clone(Author);&lt;br /&gt;author0.name = 'Dustin Diaz';&lt;br /&gt;author0.books = ['JavaScript Design Patterns'];&lt;br /&gt;var author1 = clone(Author);&lt;br /&gt;author1.name = 'Ross Harmes';&lt;br /&gt;author1.books = ['JavaScript Design Patterns'];&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;Here is the clone function. First the clone function creates a new and empty function, F. It then sets the prototype attribute of F to the prototype object. Lastly, the function creates a new object by calling the new operator on F. The cloned object that is returned is completely empty, except for the prototype attribute, which is (indirectly) pointing to the prototype object, by way of the F object.&lt;br /&gt;&lt;code&gt;&lt;br /&gt;/* Clone function. */&lt;br /&gt;function clone(object) {&lt;br /&gt;    function F() {}&lt;br /&gt;    F.prototype = object;&lt;br /&gt;    return new F;&lt;br /&gt;}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;In classical inheritance, each instance of Author has its own copy of the books array. You could add to it by writing author1.books.push('New Book Title'). That is not initially possible with the object you created using prototypal inheritance because of the way prototype chaining works. A clone is not a fully independent copy of its prototype object; it is a new empty object with its prototype attribute set to the prototype object. When it is just created, author1.name is actually a link back to the primitive Person.name. When you write to author1.name, you are defining a new attribute directly on the author1 object.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;var authorClone = clone(Author);&lt;br /&gt;alert(authorClone.name); // Linked to the primative Person.name, which is the&lt;br /&gt;                         // string 'default name'.&lt;br /&gt;authorClone.name = 'new name'; // A new primative is created and added to the&lt;br /&gt;                               // authorClone object itself.&lt;br /&gt;alert(authorClone.name); // Now linked to the primative authorClone.name, which&lt;br /&gt;                         // is the string 'new name'.&lt;br /&gt;authorClone.books.push('new book'); // authorClone.books is linked to the array&lt;br /&gt;                                    // Author.books. We just modified the&lt;br /&gt;                                    // prototype object's default value, and all&lt;br /&gt;                                    // other objects that link to it will now&lt;br /&gt;                                    // have a new default value there.&lt;br /&gt;authorClone.books = []; // A new array is created and added to the authorClone&lt;br /&gt;                        // object itself.&lt;br /&gt;authorClone.books.push('new book'); // We are now modifying that new array.&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Classical inheritance is well understood, both in JavaScript and the programmer commu-&lt;br /&gt;nity in general. Almost all object-oriented code written in JavaScript uses this paradigm. If you&lt;br /&gt;are creating an API for widespread use, or if there is the possibility that other programmers not&lt;br /&gt;familiar with prototypal inheritance will be working on your code, it is best to go with classical.&lt;br /&gt;&lt;br /&gt;JavaScript is the only popular, widely used language that uses prototypal inheritance, so odds&lt;br /&gt;are most people will never have used it before. It can also be confusing to have an object with&lt;br /&gt;links back to its prototype object. Programmers who don’t fully understand prototypal inheri-&lt;br /&gt;tance will think of this as some sort of reverse inheritance, where the parent inherits from its&lt;br /&gt;children. Even though this isn’t the case, it can still be a very confusing topic. But since this&lt;br /&gt;form of classical inheritance is only imitating true class-based inheritance, advanced JavaScript&lt;br /&gt;programmers need to understand how prototypal inheritance truly works at some point any-&lt;br /&gt;way. Some would argue that hiding this fact does more harm than good.</description><link>http://chamnapchhorn.blogspot.com/2009/05/prototypal-inheritance-vs-classical.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-6761142148052793737.post-3190805459986718748</guid><pubDate>Wed, 29 Apr 2009 01:33:00 +0000</pubDate><atom:updated>2009-05-23T09:57:06.203+07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">ruby on rails</category><title>ActiveRecord::Dirty</title><description>Another powerful feature of ActiveRecord is dirty objects. This module tracks unsaved attribute changes. This feature is available probably since &lt;a href="http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects"&gt;March, 2008&lt;/a&gt;. See examples below:&lt;br /&gt;&lt;br /&gt;&lt;b&gt;A newly instantiated object is unchanged:&lt;/b&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  person = Person.find_by_name('uncle bob')&lt;br /&gt;  person.changed?       # =&gt; false&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;b&gt;Change the name:&lt;/b&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  person.name = 'Bob'&lt;br /&gt;  person.changed?       # =&gt; true&lt;br /&gt;  person.name_changed?  # =&gt; true&lt;br /&gt;  person.name_was       # =&gt; 'uncle bob'&lt;br /&gt;  person.name_change    # =&gt; ['uncle bob', 'Bob']&lt;br /&gt;  person.name = 'Bill'&lt;br /&gt;  person.name_change    # =&gt; ['uncle bob', 'Bill']&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;b&gt;Save the changes:&lt;/b&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  person.save&lt;br /&gt;  person.changed?       # =&gt; false&lt;br /&gt;  person.name_changed?  # =&gt; false&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;b&gt;Assigning the same value leaves the attribute unchanged:&lt;/b&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  person.name = 'Bill'&lt;br /&gt;  person.name_changed?  # =&gt; false&lt;br /&gt;  person.name_change    # =&gt; nil&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;b&gt;Which attributes have changed?&lt;/b&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  person.name = 'bob'&lt;br /&gt;  person.changed        # =&gt; ['name']&lt;br /&gt;  person.changes        # =&gt; { 'name' =&gt; ['Bill', 'bob'] }&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;b&gt;Before modifying an attribute in-place:&lt;/b&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  person.name_will_change!&lt;br /&gt;  person.name &lt;&lt; 'by'&lt;br /&gt;  person.name_change    # =&gt; ['uncle bob', 'uncle bobby']&lt;br /&gt;&lt;/code&gt;</description><link>http://chamnapchhorn.blogspot.com/2009/04/activerecorddirty.html</link><author>noreply@blogger.com (chamnap)</author><thr:total>2</thr:total></item></channel></rss>