<?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>{&#124;ihower.tw&#124; blog } &#187; Ruby</title>
	<atom:link href="http://ihower.tw/blog/archives/category/ruby/feed" rel="self" type="application/rss+xml" />
	<link>http://ihower.tw/blog</link>
	<description>Ruby, Ruby on Rails, Mac and Agile development</description>
	<lastBuildDate>Tue, 16 Mar 2010 17:13:30 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>深入Rails3: ActiveSupport::Concern</title>
		<link>http://ihower.tw/blog/archives/3949</link>
		<comments>http://ihower.tw/blog/archives/3949#comments</comments>
		<pubDate>Thu, 11 Mar 2010 23:29:45 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3949</guid>
		<description><![CDATA[ActiveSupport::Concern 是 Rails3 做 Modularity 的一個重要的小工具。他的任務是讓管理 modules 之間的 dependencies 變得容易。
假設我們有兩個 Modules 有依存關係，module Bar 依存於 module Foo，然後有一個宿主 Host 類別希望 include Bar 的功能，我們可以這樣寫:


module Foo
   # self.included 這個函式會在 Foo 被 include 時執行
    def self.included(base)
        base.send(:do_host_something) # 對宿主做某些操作，例如增強功能等等
    end
end

module Bar
    def [...]]]></description>
			<content:encoded><![CDATA[<p>ActiveSupport::Concern 是 Rails3 做 Modularity 的一個重要的小工具。他的任務是讓管理 modules 之間的 dependencies 變得容易。</p>
<p>假設我們有兩個 Modules 有依存關係，module Bar 依存於 module Foo，然後有一個宿主 Host 類別希望 include Bar 的功能，我們可以這樣寫:</p>
<pre>
<code>
module Foo
   # self.included 這個函式會在 Foo 被 include 時執行
    def self.included(base)
        base.send(:do_host_something) # 對宿主做某些操作，例如增強功能等等
    end
end

module Bar
    def self.included(base)
        base.send(:do_host_something)
    end
end

class Host
  include Foo, Bar
end
</code>
</pre>
<p>這有個討厭的缺點就是，我們必須在宿主中同時 include Foo 跟 Bar，也就是要把所有依存的 modules 都 include 進來。這很糟糕啊，為什麼我們需要在 Host 裡面知道這些 modules 的依存關係呢 :/</p>
<p>我們希望能夠將 modules 的依存關係寫在 module 中，而宿主 Host 就只要使用就好了。所以我們試著改寫成:</p>
<pre>
<code>
module Bar
  include Foo # 因為 Bar 依存於 Foo，所以我們在這裡 include 它

  def self.included(base)
    base.send(:do_host_something)
  end

end

class Host
  include Bar # 只要 include Bar 就好，不需要知道 Bar 還依存哪些 modules
end
</code>
</pre>
<p>這樣乍看之下好像沒問題，但是卻有個嚴重的問題導致無法執行，因為 Foo 變成是由 Bar 所 include，所以對 Foo 的 self.included 來說，他的參數 base 變成了 Bar 了，所以他就沒辦法存取到宿主 Host 的任何函式及變數，do_host_something 時就會失敗。</p>
<p>Okay，ActiveSupport::Concern 就是來幫助解決這個難題，我們希望宿主可以不需要知道 modules 之間的 dependencies 關係。dependencies 關係寫在 module 裡面就好了。</p>
<pre>
<code>
require 'active_support/concern'

module Foo
    extend ActiveSupport::Concern
    included do
        self.send(:do_host_something)
    end
end

module Bar
    extend ActiveSupport::Concern
    include Foo # 因為 Bar 依存於 Foo，所以我們在這裡 include 它

    included do
        self.send(:do_host_something)
    end
end

class Host
  include Bar # 只要 include Bar 就好，不需要知道 Bar 還依存哪些 modules
end

</code>
</pre>
<p>如此就搞定了。One more thing，如果你有定義 module ClassMethods 和 module InstanceMethods 在裡面的話，它也會自動幫你載入到宿主裡面去，就不用自己寫 send(:include, InstanceMethods) 跟 send(:extend, ClassMethods) 了。用法舉例：</p>
<pre>
<code>

module Foo
    extend ActiveSupport::Concern
    included do
        self.send(:do_host_something)
    end

   module ClassMethods
      def bite
        # do something
      end
   end

   module InstanceMethods
      def poke
         # do something
      end
   end
end

</code>
</pre>
<p>想知道 ActiveSupport::Concern 到底怎麼實作的話，請看 <a href="http://github.com/rails/rails/blob/master/activesupport/lib/active_support/concern.rb">/activesupport/lib/active_support/concern.rb</a>，只有 29 行，而且 ActiveSupport::Concern 也沒有再依存其他東西了，嘿。</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3949/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby Tuesday #9 講題更換及 #10 開催</title>
		<link>http://ihower.tw/blog/archives/3901</link>
		<comments>http://ihower.tw/blog/archives/3901#comments</comments>
		<pubDate>Sun, 28 Feb 2010 04:17:34 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[WWW]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3901</guid>
		<description><![CDATA[這次很難得臨時邀請到即將前往日本慶應大學 W3C 擔任研究員的 Kenny 來跟我們分享語意網(Semantic Web)的現況、概論與鍵連資料(Linked Data)雲，所以臨時將 #9 我的 Rails Performance &#038; Security 講題移到 Ruby Tuesday #10。
這裡的雲指的是這張圖，其中一個圈大概是一個RDF資料庫，連結就是跨domain的RDF的連結，這個架構可以把全部的資料庫們視為一個資料庫查詢，所以我們把這整個RDF Web稱為一個雲。
語意網的技術包括有RDF+SPARQL(RDF版的SQL)+RDFa+OWL+RIF，因為時間有限，講者會跟我們分享其中的概念總論，參考資料是講者老闆(Tim Berners-Lee，WWW 發明人) 在TED 2009的演講。當然，也會分享 RDFa on Rails 實作。
報名 #9 請前往: http://registrano.com/events/ruby-tuesday-9，時間是 2010/3/9 (二)
報名 #10 請前往: http://registrano.com/events/ruby-tuesday-10，時間是 2010/3/23 (二)
]]></description>
			<content:encoded><![CDATA[<p>這次很難得臨時邀請到即將前往日本慶應大學 <a href="http://www.w3.org/">W3C</a> 擔任研究員的 Kenny 來跟我們分享語意網(Semantic Web)的現況、概論與鍵連資料(Linked Data)雲，所以臨時將 #9 我的 Rails Performance &#038; Security 講題移到 Ruby Tuesday #10。</p>
<p>這裡的雲指的是<a href="http://www4.wiwiss.fu-berlin.de/bizer/pub/lod-datasets_2009-07-14.html">這張圖</a>，其中一個圈大概是一個RDF資料庫，連結就是跨domain的RDF的連結，這個架構可以把全部的資料庫們視為一個資料庫查詢，所以我們把這整個RDF Web稱為一個雲。</p>
<p>語意網的技術包括有RDF+SPARQL(RDF版的SQL)+RDFa+OWL+RIF，因為時間有限，講者會跟我們分享其中的概念總論，參考資料是講者老闆(<a href="http://en.wikipedia.org/wiki/Tim_Berners-Lee">Tim Berners-Lee</a>，WWW 發明人) 在TED 2009的<a href="http://www.ted.com/talks/tim_berners_lee_on_the_next_web.html">演講</a>。當然，也會分享 RDFa on Rails 實作。</p>
<p>報名 #9 請前往: <a href="http://registrano.com/events/ruby-tuesday-9">http://registrano.com/events/ruby-tuesday-9</a>，時間是 2010/3/9 (二)</p>
<p>報名 #10 請前往: <a href="http://registrano.com/events/ruby-tuesday-10">http://registrano.com/events/ruby-tuesday-10</a>，時間是 2010/3/23 (二)</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3901/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby Tuesday #9 開始報名</title>
		<link>http://ihower.tw/blog/archives/3890</link>
		<comments>http://ihower.tw/blog/archives/3890#comments</comments>
		<pubDate>Mon, 22 Feb 2010 14:32:41 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3890</guid>
		<description><![CDATA[Update(2010/2/28): Ruby Tuesday #9 講題更換及 #10 開催
Ruby Tuesday 聚會辦到第九次啦，這一次很難得由 Josh Moore 帶來 JRuby on the Google App Engine，終於找到人來講 JRuby 了，我特別好奇 JRuby 跟我們一般用的 MRI 到底用起來有什麼差別的地方。 
另一場演講則是由我帶來 Rails Best Performance and Security Practices，這個題目從我在準備 Rails Best Practices 就肖想了，當時的重點著重在程式怎樣寫的容易擴充跟維護，所以有一些效能跟安全性的最佳實務只好忍痛割愛。這次趁與 OSSF 合作，就來準備這個題目。
時間: 2010/3/9（週二）晚上七點到九點半。
地點: 台北市 果子咖啡
報名網頁: http://registrano.com/events/ruby-tuesday-9
]]></description>
			<content:encoded><![CDATA[<p>Update(2010/2/28): <a href="http://ihower.tw/blog/archives/3901">Ruby Tuesday #9 講題更換及 #10 開催</a></p>
<p>Ruby Tuesday 聚會辦到第九次啦，這一次很難得由 <a href="http://www.codingforrent.com/">Josh Moore</a> 帶來 JRuby on the Google App Engine，終於找到人來講 <a href="http://jruby.org/">JRuby</a> 了，我特別好奇 JRuby 跟我們一般用的 MRI 到底用起來有什麼差別的地方。 </p>
<p>另一場演講則是由我帶來 Rails Best Performance and Security Practices，這個題目從我在準備 <a href="http://ihower.tw/blog/archives/3075">Rails Best Practices</a> 就肖想了，當時的重點著重在程式怎樣寫的容易擴充跟維護，所以有一些效能跟安全性的最佳實務只好忍痛割愛。這次趁與 OSSF <a href="http://whoswho.openfoundry.org/workshop/details/74-ruby-sinica--rails-best-performance-and-security-practices.html">合作</a>，就來準備這個題目。</p>
<p>時間: 2010/3/9（週二）晚上七點到九點半。</p>
<p>地點: 台北市 果子咖啡</p>
<p>報名網頁: <a href="http://registrano.com/events/ruby-tuesday-9">http://registrano.com/events/ruby-tuesday-9</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3890/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RubyConf Taiwan 2010 開始報名</title>
		<link>http://ihower.tw/blog/archives/3751</link>
		<comments>http://ihower.tw/blog/archives/3751#comments</comments>
		<pubDate>Sat, 13 Feb 2010 05:15:03 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3751</guid>
		<description><![CDATA[疑？怎麼今年的 OSDC.TW 大會沒有任何 Ruby 場次? 這是因為今年我們 Ruby Taiwan 社群決定與 OSDC.TW 並行獨立出來一整天的 Ruby 議程啦，詳細內容及報名請前往 RubyConf Taiwan 網頁。
台灣的 Ruby 社群很小，但是我們的眼界跟志向不低。這是我們第一次舉辦國際性的 Ruby 程式語言研討會，講者群中包含了來自美國、日本以及大陸的朋友，相信可以帶給我們不同的視野及經驗。一天的議程安排地非常緊湊(也許明年可以來辦兩天了)，真是非常興奮又期待。
身為活動主辦人，我要特別感謝 OSDC.TW 與我們分享了會場、EvenDesign 贊助了專業的網頁設計，以及 Handlino 贊助了網域名稱費用和提供 Registrano 報名網站。如果貴單位有意願贊助這項活動，歡迎與我們聯繫(2010@rubyconf.tw)。
]]></description>
			<content:encoded><![CDATA[<p>疑？怎麼今年的 <a href="http://osdc.tw">OSDC.TW</a> 大會沒有任何 Ruby 場次? 這是因為今年我們 Ruby Taiwan 社群決定與 OSDC.TW 並行獨立出來一整天的 Ruby 議程啦，詳細內容及報名請前往 <a href="http://rubyconf.tw/2010">RubyConf Taiwan</a> 網頁。</p>
<p>台灣的 Ruby 社群很小，但是我們的眼界跟志向不低。這是我們第一次舉辦國際性的 Ruby 程式語言研討會，講者群中包含了來自美國、日本以及大陸的朋友，相信可以帶給我們不同的視野及經驗。一天的議程安排地非常緊湊(也許明年可以來辦兩天了)，真是非常興奮又期待。</p>
<p>身為活動主辦人，我要特別感謝 <a href="http://osdc.tw">OSDC.TW</a> 與我們分享了會場、<a href="http://evendesign.tw/">EvenDesign</a> 贊助了專業的網頁設計，以及 <a href="http://handlino.com/">Handlino</a> 贊助了網域名稱費用和提供 <a href="http://registrano.com">Registrano</a> 報名網站。如果貴單位有意願贊助這項活動，歡迎與我們聯繫(2010@rubyconf.tw)。</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3751/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails 由淺入深課程(2/27,28) 開放報名</title>
		<link>http://ihower.tw/blog/archives/3792</link>
		<comments>http://ihower.tw/blog/archives/3792#comments</comments>
		<pubDate>Fri, 12 Feb 2010 14:33:51 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3792</guid>
		<description><![CDATA[又要開課啦，由 中央研究院 資訊創新研究中心自由軟體鑄造場主辦的自由軟體技術分享工作坊—Ruby On Rails由淺入深課程。這是兩整天共 12hr 的上機實作課程，名額有限、完全免費。
活動名稱：自由軟體技術分享工作坊—Ruby On Rails由淺入深
活動時間：2010.02.27（六）/ 2010.02.28（日）
活動講者：ihower
報名首頁：http://whoswho.openfoundry.org/workshop.html
活動地點：台北市復興北路99號2樓 (恆逸教育訓練中心)
]]></description>
			<content:encoded><![CDATA[<p>又要開課啦，由 中央研究院 資訊創新研究中心<a href="http://www.openfoundry.org">自由軟體鑄造場</a>主辦的自由軟體技術分享工作坊—Ruby On Rails由淺入深課程。這是兩整天共 12hr 的上機實作課程，名額有限、完全免費。</p>
<p>活動名稱：自由軟體技術分享工作坊—Ruby On Rails由淺入深<br />
活動時間：2010.02.27（六）/ 2010.02.28（日）<br />
活動講者：ihower<br />
報名首頁：<a href="http://whoswho.openfoundry.org/workshop.html">http://whoswho.openfoundry.org/workshop.html</a><br />
活動地點：台北市復興北路99號2樓 (恆逸教育訓練中心)</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3792/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails3 Beta 發佈: 重點導覽</title>
		<link>http://ihower.tw/blog/archives/3653</link>
		<comments>http://ihower.tw/blog/archives/3653#comments</comments>
		<pubDate>Mon, 08 Feb 2010 09:36:40 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3653</guid>
		<description><![CDATA[Update(2010/2/22): The Rails 3 Upgrade Handbook 可以買來看。
從 Merb 和 Rails 決定合併開始，過了一年多的努力終於發佈 Beta 版啦。Rails3 最重要的人物就是總架構師 Yehuda Katz 了，整個把 Rails core 翻了好幾翻，徹底改頭換面。
Why? 我是這麼想的，DHH 一開始開發 Rails 的時候，Ruby 社群還不像現在這麼發達，所以很多事情必須自己造(連  prototype 都是為了 Rails 而造的)，為了達到非常容易設定跟快速開發的理想，得包山包海什麼功能都要做，再加上有限的資源，造成了 Rails core 其實綁得很緊，基本上就是一整包給你。要修改擴充它，常常就必須 monkeypatch 一下。另一方面，對怎樣的 Ruby 程式是好程式，一開始也沒有這麼多人想清楚，例如 Rails core 充滿了  alias_method_chain，這件事情現在也被認為是比較不好的寫法。
Rails3 的時代不同了，Ruby 社群起來了。我們有標準的 Rack 介面、我們有不同的ORM甚至是 NoSQL 的儲存庫、我們有不同 JS Libary、我們有不同測試方式 RSpec、我們也有許多現成不需要自己造的新函式庫。Rails3 基本上就是這麼一個接近改掉重寫的版本，但是以重構的方式達成了這個兼容並蓄的目標：將 API 重新釐清、徹底模組化、低耦合度元件、大幅提昇效能等。具體來說，有幾個成果：
使用 Ruby [...]]]></description>
			<content:encoded><![CDATA[<p>Update(2010/2/22): <a href="http://www.railsupgradehandbook.com/">The Rails 3 Upgrade Handbook</a> 可以買來看。</p>
<p>從 Merb 和 Rails 決定<a href="http://weblog.rubyonrails.org/2008/12/23/merb-gets-merged-into-rails-3">合併</a>開始，過了一年多的努力終於發佈 <a href="http://weblog.rubyonrails.org/2010/2/5/rails-3-0-beta-release">Beta</a> 版啦。Rails3 最重要的人物就是總架構師 <a href="http://yehudakatz.com/">Yehuda Katz</a> 了，整個把 Rails core 翻了好幾翻，徹底改頭換面。</p>
<p>Why? 我是這麼想的，DHH 一開始開發 Rails 的時候，Ruby 社群還不像現在這麼發達，所以很多事情必須自己造(連  <a href="http://prototypejs.org">prototype</a> 都是為了 Rails 而造的)，為了達到非常容易設定跟快速開發的理想，得包山包海什麼功能都要做，再加上有限的資源，造成了 Rails core 其實綁得很緊，基本上就是一整包給你。要修改擴充它，常常就必須 monkeypatch 一下。另一方面，對怎樣的 Ruby 程式是好程式，一開始也沒有這麼多人想清楚，例如 Rails core 充滿了  alias_method_chain，這件事情現在也被認為是比較不好的寫法。</p>
<p>Rails3 的時代不同了，Ruby 社群起來了。我們有標準的 <a href="http://rack.rubyforge.org/">Rack</a> 介面、我們有不同的ORM甚至是 NoSQL 的儲存庫、我們有不同 JS Libary、我們有不同測試方式 <a href="http://rspec.info/">RSpec</a>、我們也有許多現成不需要自己造的新函式庫。Rails3 基本上就是這麼一個接近改掉重寫的版本，但是以重構的方式達成了這個兼容並蓄的目標：將 API 重新釐清、徹底模組化、低耦合度元件、大幅提昇效能等。具體來說，有幾個成果：</p>
<h3>使用 Ruby 1.8.7 或 Ruby 1.9.2</h3>
<p>1.9 的時代終於要來臨了 :) 可以複習一下我去年演講的<a href="http://ihower.tw/blog/archives/2722">投影片</a>。</p>
<h3>Dependencies 管理</h3>
<p>本來的 config.gem 換成新的 <a href="http://github.com/carlhuda/bundler ">Bundler</a> 來管理所有用到的函式庫，使用新的 Gemfiles 格式，本來的 config.gem sucks 問題多功能有限。現在，我們真的做到可以完全不依靠系統 gems。可以參考這篇 <a href="http://www.lindsaar.net/2010/2/6/bundle_me_some_rails">Bundle me some Rails</a> 和 <a href="http://yehudakatz.com/2010/02/09/using-bundler-in-real-life/">Using Bundler in Real Life</a> 示範 Bundle 的用法</p>
<h3>新的 Routes</h3>
<p>由於全面導入 Rack 的關係，現在的 Route 其實也是一個 Rack middleware，實作上就是 <a href="http://github.com/josh/rack-mount">rack-mount</a>。新的 Route 第一眼看到就是 API 的改變了，可以參考這篇  <a href="http://rizwanreza.com/2009/12/20/revamped-routes-in-rails-3">Revamped Routes in Rails 3</a>，不過這其實不是最重要的地方，最厲害的地方是，它參數 :to 接的端點其實是 rack 端點，而 main#home 是 MainController.action(:home) 的簡寫( 是的!! Rails3 中每個 Controller actions 全都是一個標準的 Rack app!! 超酷!!)，可以看看 Yehuda 的<a href="http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/">實作說明</a>。既然是 Rack 端點，我們就可以給它接其他 Rack app，例如 Sinatra，這一篇就示範了怎麼接 <a href="http://lindsaar.net/2010/2/7/rails_3_routing_with_rack">Rails 3 Routing with Rack</a>，真是超級簡單啊。我們可以預期，會有更多有趣的 <a href="http://www.rubyinside.com/21-rack-middlewares-2649.html">Rack middlewares</a> 可以與 Rails 結合。</p>
<p>另外，我們也可以直接在 Routes 層直接辦到 redirect 和 render template，可以看看 Yehuda 的實作說明：<a href="http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3">Generic Actions in Rails 3</a>，基本上就是簡單的 Rack middleware。</p>
<h3>新的 Active Model</h3>
<p>為了達到與不同 ORM 銜接的目標，Rails3 的 ActiveModel 將本來的 ActiveRecord 的個別功能抽出來成為 Module，例如 callbacks, validations, serialization, observing,  dirty tracking 等。任何 Class 只要符合 ActiveModel 定義的幾個 API，再加上 include 你需要的 Module，就可以與 Rails3 接在一起了。請參閱 <a href="http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/">ActiveModel: Make Any Ruby Object Feel Like ActiveRecord</a>。</p>
<p>其中 Validation 有新的 API，請參閱 <a href="http://lindsaar.net/2010/1/31/validates_rails_3_awesome_is_true">validates :rails_3, :awesome => true</a></p>
<h3>ActiveRecord</h3>
<p>那 ActiveRecord 本身呢? 引入了 <a href="http://github.com/brynary/arel">ARel</a> 這套 SQL 產生工具(<a href="http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/">why Arel?</a>)，大幅採用 &#8220;method chain&#8221; 的串接用法，讓每個操作都變成了 scope。</p>
<p>ActiveRecord 因此也有了新的 API: <a href="http://m.onkey.org/2010/1/22/active-record-query-interface">Active Record Query Interface 3.0</a></p>
<h3>ActionController</h3>
<p>Responder 帶來了 respond_with，可以簡化 controller 的寫法，用法參考 <a href="http://ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with">Cleaner RESTful Controllers w/ respond_with</a>、<a href="http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering">Default RESTful Rendering</a> 和 <a href="http://weblog.rubyonrails.org/2009/8/31/three-reasons-love-responder">Three reasons to love ActionController::Responder</a> 這幾篇。這工具非常有趣，我之前甚至寫了一個 plugin <a href="http://github.com/ihower/respond_methods">respond_methods</a> 來讓  Rails 2.x 支援這個功能。</p>
<p>另外，新的 Render 實作可以讓你輕易擴展，這一篇 <a href="http://www.engineyard.com/blog/2010/render-options-in-rails-3/">Render Options in Rails 3</a> 示範了怎麼做出你自己的 render :pdf。</p>
<h3>ActionView</h3>
<p>幾個大的改變： </p>
<p>1. 採用  <a href="http://www.kuwata-lab.com/erubis/">Erubis</a> 實作<br />
2. 預設 XSS protection 打開，再也不用忘記加上 h 逸出了。請參考 <a href="http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/">SafeBuffers and Rails 3.0</a> 有更多細節<br />
3. 將所有 JavaScript helpers 改成 unobtrusive。你會發現 Rails3 的 public/javascripts 多了一個 rails.js，這就是一個 JS driver，預設是接 prototype.js，要換成 jQuery 非常簡單，只要用 jQuery 版本的 <a href="http://github.com/rails/jquery-ujs/raw/master/src/rails.js">rails.js</a> 就可以了。因此本來的一些 Ajax Helper 就被移除了，有需要的話可以在 <a href="http://github.com/rails/prototype_legacy_helper">prototype_legacy_helper</a> plugin 找回來。<br />
4. Helpers 預設輸出格式是 HTML 5。</p>
<p>說到 HTML5，我另外推薦這份閱讀材料 <a href="http://diveintohtml5.org/">Dive into HTML5</a> 以及 <a href="http://html5demos.com/">HTML 5 Demos and Examples</a>。</p>
<h3>ActionMailer</h3>
<p>首先底層換成 <a href="http://github.com/mikel/mail">Mail</a> 這套工具了，可以參考這篇<a href="http://lindsaar.net/2010/1/23/mail-gem-version-2-released">介紹</a>。接著，受益於 Controller 的重構成果，新的 ActionMailer 終於和 Controller 繼承自同一個 AbstractController，讓 ActionMailer 的功能增加不少，也大大的 DRY 了。</p>
<p>新的 API 請參考 <a href="http://lindsaar.net/2010/1/26/new-actionmailer-api-in-rails-3">New ActionMailer API in Rails 3.0</a></p>
<p>最後它的位置改放在 app/mailers 了，放在 app/models 下實在讓人搞混啊。</p>
<h3>ActiveSupport</h3>
<p>之前的 ActiveSupport 有個討厭的地方是，如果你只想要用到其中的幾個功能，很不容易搞懂到底要 require 哪些東西，最後只好通通載入以求保險。新的 Rails3 把這件事情弄清楚了，你可以只載入你要的部分。</p>
<h3>Rails Application object</h3>
<p>為了讓一個 Process 可以跑多個 Rails app，Rails3 使用了一個 Rails Application 物件來表示一整個 Application 的所有設定，因此本來的 config/environment.rb 的功能，幾乎都搬到 config/application.rb 了。另外，Rack 的標準 config.ru 檔案也被加到了根目錄，因此要特別注意到你的 Application 名稱，這會是跟其他 Application 互動時使用的名稱，預設是目錄的名字。</p>
<h3>新的 Rails Module</h3>
<p>幾個常數被拿掉了，RAILS_ROOT 要改用 Rails.root、RAILS_ENV 要改用 Rails.env、RAILS_DEFAULT_LOGGER 要改用  Rails.logger 等，詳細請參閱這篇 <a href="http://litanyagainstfear.com/blog/2010/02/03/the-rails-module/">The Rails Module (in Rails 3)</a>。改成物件的好處是，我們就不需要做字串操作這種事情了。</p>
<h3>新的 rails 指令</h3>
<p>本來的 script/* 指令全部拿掉了，都改成用 rails。例如 script/console 變成 rails console (可以簡寫成 rails c)、script/generate 變成 rails generate (可以簡寫成 rails g)、script/server 變成 rails server(可以簡寫成 rails s)。使用 rails &#8211;help 可以看到完整說明。</p>
<h3>推薦閱讀</h3>
<p>Rails3 的閱讀資料非常多，官方的 <a href="http://guides.rails.info/3_0_release_notes.html">Rails 3.0: Release Notes</a> 是必讀。如果你從升級的方向切入，可以使用官方的升級 Plugin <a href="http://omgbloglol.com/post/364624593/rails-upgrade-is-now-an-official-plugin">rails-upgrade is now an official plugin</a>，它可以幫助你 1. 檢查需要升級的地方 2. 產生 Gemfile 3. 產生新的 routes.rb。請搭配這篇 <a href="http://omgbloglol.com/post/353978923/the-path-to-rails-3-approaching-the-upgrade">The Path to Rails 3: Approaching the upgrade</a> 服用。不過，嗯，現在還是不要在 Production 環境上升級比較好，畢竟很多 Plugin 還沒跟上來哩 (可以看看 <a href="http://railsplugins.org/">Is Your Plugin Ready For Rails 3?</a> 和 <a href="http://wiki.rubyonrails.org/rails/version3/plugins_and_gems">Rails Wiki</a> 有整理哪些 Plugins OK 了)。</p>
<p>如果是從重新開始會容易得多，可以看 <a href="http://omgbloglol.com/post/371893012/the-path-to-rails-3-greenfielding-new-apps-with-the">The Path to Rails 3: Greenfielding new apps with the Rails 3 beta</a> 這篇。十分建議你有空的話，現在就可以開始玩玩看了。</p>
<p>如果想多了解 Rails 的架構，有幾篇文章可以看看：</p>
<ul>
<li><a href="http://omgbloglol.com/post/344792822/the-path-to-rails-3-introduction">The Path to Rails 3: Introduction</a> (算是最簡單的一篇，可以看看)</li>
<li><a href="http://www.engineyard.com/blog/2010/rails-3-beta-is-out-a-retrospective/">Rails 3 Beta is Out — A Retrospective</a></li>
<li><a href="http://yehudakatz.com/2009/07/19/rails-3-the-great-decoupling">Rails 3: The Great Decoupling</a></li>
<li><a href="http://yehudakatz.com/2009/06/11/rails-edge-architecture/">Rails Edge Architecture</a></li>
<li><a href="http://www.engineyard.com/blog/2009/rails-and-merb-merge-the-anniversary-part-1-of-6/">Rails and Merb Merge: The Anniversary (Part 1 of 6)</a></li>
<li><a href="http://www.engineyard.com/blog/2009/rails-and-merb-merge-performance-part-2-of-6/">Rails and Merb Merge: Performance (Part 2 of 6)</a></li>
<li><a href="http://www.engineyard.com/blog/2010/rails-and-merb-merge-plugin-api-part-3-of-6/">Rails and Merb Merge: Plugin API (Part 3 of 6)</a></li>
<li><a href="http://www.engineyard.com/blog/2010/rails-and-merb-merge-rails-core-part-4-of-6/">Rails and Merb Merge: Rails Core (Part 4 of 6)</a></li>
<li><a href="http://www.engineyard.com/blog/2010/rails-and-merb-merge-orm-agnosticism-part-5-of-6/">Rails and Merb Merge: ORM Agnosticism (Part 5 of 6)</a></li>
<li><a href="http://www.engineyard.com/blog/2010/rails-and-merb-merge-rack-part-6-of-6/">Rails and Merb Merge: Rack (Part 6 of 6)</a></li>
</ul>
<p>最後，如果你還想找更多，英文的懶人包有：<a href="http://edgerails.info/articles/what-s-new-in-edge-rails/2010/02/10/rails-3-resources/">Rails 3 Resources</a>、<a href="http://www.rubyinside.com/rails-3-0-beta-links-2966.html">Rails 3.0 Beta: 36 Links and Resources To Get You Going</a>、<a href="http://mediumexposure.com/rails-3-reading-material/">Rails 3 Reading Material</a>、<a href="http://railslove.com/weblog/2010/02/02/on-the-way-to-rails-3-a-link-list/">On the way to Rails 3 &#8211; a link list</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3653/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sketches: 在 irb 中使用文字編輯器</title>
		<link>http://ihower.tw/blog/archives/3633</link>
		<comments>http://ihower.tw/blog/archives/3633#comments</comments>
		<pubDate>Fri, 29 Jan 2010 22:15:34 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3633</guid>
		<description><![CDATA[Sketches 是個很有趣的工具，它讓你可以在 irb 中打開你最愛的文字編輯器直接編輯，然後無需重開 irb 環境就可以使用。
首先是安裝：
sudo gem install sketches
然後編輯你的 ~/.irbrc 檔案，加上：
require &#8217;sketches&#8217;
Sketches.config :editor => &#8216;mate&#8217;
接著在 irb 裡面就可以：
sketch 就會打開你的編輯器，存檔之後就可以使用。
sketches 會列出曾經編輯過的記錄
name_sketch 可以命名這些記錄
save_sketch 則可以存成檔案
不過有個缺點是 local variable 區域變數是讀不到的，不過我想最常用的方式是打開編輯器寫一些類別跟函式定義 :)
如果你還是不知道這是怎麼回事，可以看看 RubyPulse 的示範。
突然想到，上課用來 live demo 似乎非常適合 :p
]]></description>
			<content:encoded><![CDATA[<p><a href="http://sketches.rubyforge.org/">Sketches</a> 是個很有趣的工具，它讓你可以在 <a href="http://en.wikipedia.org/wiki/Interactive_Ruby_Shell">irb</a> 中打開你最愛的文字編輯器直接編輯，然後無需重開 irb 環境就可以使用。</p>
<p>首先是安裝：</p>
<p>sudo gem install sketches</p>
<p>然後編輯你的 ~/.irbrc 檔案，加上：</p>
<p>require &#8217;sketches&#8217;<br />
Sketches.config :editor => &#8216;mate&#8217;</p>
<p>接著在 irb 裡面就可以：</p>
<p>sketch 就會打開你的編輯器，存檔之後就可以使用。<br />
sketches 會列出曾經編輯過的記錄<br />
name_sketch 可以命名這些記錄<br />
save_sketch 則可以存成檔案</p>
<p>不過有個缺點是 local variable 區域變數是讀不到的，不過我想最常用的方式是打開編輯器寫一些類別跟函式定義 :)</p>
<p>如果你還是不知道這是怎麼回事，可以看看 <a href="http://www.rubypulse.com/episode-0.4-sketches.html">RubyPulse</a> 的示範。</p>
<p>突然想到，上課用來 live demo 似乎非常適合 :p</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3633/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby Tuesday 2010 首場</title>
		<link>http://ihower.tw/blog/archives/3627</link>
		<comments>http://ihower.tw/blog/archives/3627#comments</comments>
		<pubDate>Fri, 29 Jan 2010 10:21:47 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3627</guid>
		<description><![CDATA[Update(2010/2/10): 這場的投影片和 Distributed Ruby and Rails 那場一樣 :)
Ruby Tuesday 今年的第一場聚會，由 godfat 和我帶來 EventMachine 和 Distributed Ruby&#038;Background-Processing in Rails 兩場演講。
EventMachine 是一套使用 Reactor pattern 的 event-driven I/O 函式庫，你可以在許多 Ruby networking 工具發現它的蹤跡，像是 Thin、starling、amqp、cramp 等
我的部份則是將上次在中研院的題目 Distributed Ruby and Rails 中的 Distributed Ruby 和 Background-Processing in Rails 這兩個準備比較完整的部分拿出來分享。
時間: 2010/2/9（週二）晚上七點到九點。
地點: 台北市 果子咖啡
報名網頁: http://registrano.com/events/ruby-tuesday-201002
]]></description>
			<content:encoded><![CDATA[<p>Update(2010/2/10): 這場的投影片和 <a href="http://ihower.tw/blog/archives/3589">Distributed Ruby and Rails</a> 那場一樣 :)</p>
<p>Ruby Tuesday 今年的第一場聚會，由 <a href="http://blogger.godfat.org/">godfat</a> 和我帶來 <a href="http://eventmachine.rubyforge.org/EventMachine.html">EventMachine</a> 和 Distributed Ruby&#038;Background-Processing in Rails 兩場演講。</p>
<p>EventMachine 是一套使用 <a href="http://en.wikipedia.org/wiki/Reactor_pattern">Reactor pattern</a> 的 event-driven I/O 函式庫，你可以在許多 Ruby networking 工具發現它的蹤跡，像是 <a href="http://code.macournoyer.com/thin/">Thin</a>、<a href="http://github.com/starling/starling">starling</a>、<a href="http://github.com/tmm1/amqp">amqp</a>、<a href="http://github.com/lifo/cramp">cramp</a> 等</p>
<p>我的部份則是將上次在中研院的題目 <a href="http://ihower.tw/blog/archives/3589">Distributed Ruby and Rails</a> 中的 Distributed Ruby 和 Background-Processing in Rails 這兩個準備比較完整的部分拿出來分享。</p>
<p>時間: 2010/2/9（週二）晚上七點到九點。</p>
<p>地點: 台北市 果子咖啡</p>
<p>報名網頁: <a href="http://registrano.com/events/ruby-tuesday-201002">http://registrano.com/events/ruby-tuesday-201002</a></p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3627/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Distributed Ruby and Rails</title>
		<link>http://ihower.tw/blog/archives/3589</link>
		<comments>http://ihower.tw/blog/archives/3589#comments</comments>
		<pubDate>Thu, 21 Jan 2010 21:42:30 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3589</guid>
		<description><![CDATA[應中研院OSSF工作坊邀請，這次很有野心的挑戰這個題目，試圖涵蓋 Ruby 生態圈中，有關分散式 Ruby 程式設計和 Ruby on Rails 架構的相關內容：
Distributed Ruby and Rails
View more documents from Wen-Tien Chang.


Distributed Ruby

 DRb
Rinda
Starfish
MapReduce
MagLev VM


Distributed Message Queues

Starling
AMQP/RabbitMQ
Stomp/ActiveMQ
beanstalkd

Background-processing in Rails

script/runner
rake
cron
daemon
run_later plugin
spawn plugin


Message Queues for Rails

ar_mailer
BackgroundDRb
workling
delayed_job
resque


SOA for Rails

What’s SOA
Why SOA
Considerations
The tool set


Distributed Filesystem
Distributed database

訂出這麼大的 Agenda 範圍，自己也嚇了一跳，簡直就是差點準備不完。像是 RabbitMQ、MagLev VM、XMPP、MapReduce、SOA 等我還希望可以準備些實際的程式範例。本來預定一個小時的演講，最後也膨脹到快兩個小時才講的完。 
Anyway，這是最後的投影片了，相信你也可以獲得這個領域的大局觀。之後有機會我會繼續分享更多實作經驗。
]]></description>
			<content:encoded><![CDATA[<p>應<a href="http://whoswho.openfoundry.org/workshop/details/69-ruby-sinica--rubyrails-soa.html">中研院OSSF</a>工作坊邀請，這次很有野心的挑戰這個題目，試圖涵蓋 Ruby 生態圈中，有關分散式 Ruby 程式設計和 Ruby on Rails 架構的相關內容：</p>
<div style="width:425px;text-align:left" id="__ss_2972360"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/ihower/distributed-ruby-and-rails" title="Distributed Ruby and Rails">Distributed Ruby and Rails</a><object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=distributed-rails-100122081731-phpapp02&#038;stripped_title=distributed-ruby-and-rails" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=distributed-rails-100122081731-phpapp02&#038;stripped_title=distributed-ruby-and-rails" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/ihower">Wen-Tien Chang</a>.</div>
</div>
<ul>
<li>Distributed Ruby
<ul>
<li> DRb</li>
<li>Rinda</li>
<li>Starfish</li>
<li>MapReduce</li>
<li>MagLev VM</li>
</ul>
</li>
<li>Distributed Message Queues
<ul>
<li>Starling</li>
<li>AMQP/RabbitMQ</li>
<li>Stomp/ActiveMQ</li>
<li>beanstalkd</li>
</ul>
<li>Background-processing in Rails
<ul>
<li>script/runner</li>
<li>rake</li>
<li>cron</li>
<li>daemon</li>
<li>run_later plugin</li>
<li>spawn plugin</li>
</ul>
</li>
<li>Message Queues for Rails
<ul>
<li>ar_mailer</li>
<li>BackgroundDRb</li>
<li>workling</li>
<li>delayed_job</li>
<li>resque</li>
</ul>
</li>
<li>SOA for Rails
<ul>
<li>What’s SOA</li>
<li>Why SOA</li>
<li>Considerations</li>
<li>The tool set</li>
</ul>
</li>
<li>Distributed Filesystem</li>
<li>Distributed database</li>
</ul>
<p>訂出這麼大的 Agenda 範圍，自己也嚇了一跳，簡直就是差點準備不完。像是 RabbitMQ、MagLev VM、XMPP、MapReduce、SOA 等我還希望可以準備些實際的程式範例。本來預定一個小時的演講，最後也膨脹到快兩個小時才講的完。 </p>
<p>Anyway，這是最後的投影片了，相信你也可以獲得這個領域的大局觀。之後有機會我會繼續分享更多實作經驗。</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3589/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>傳參數到 Rake 中</title>
		<link>http://ihower.tw/blog/archives/3546</link>
		<comments>http://ihower.tw/blog/archives/3546#comments</comments>
		<pubDate>Wed, 30 Dec 2009 21:14:49 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3546</guid>
		<description><![CDATA[傳統作法是用 rake blah foo=1 這樣的指令，於是就可以透過環境變數拿到：


  task :blah do
    puts ENV['foo']
  end


但是，最近看到新的 API 使用中括號的用法 (也不新了，從 0.8.2 開始支援)，覺得挺有趣的：


  desc "passing 1 parameter to rake task"
  task :blah1, [:a] do &#124;t,args&#124;
    puts args.inspect
  end
   

 執行 rake blah1[9] 會輸出 {:a=>"9"}，注意到傳進來的變數值是字串。



  desc "passing 2 parameters [...]]]></description>
			<content:encoded><![CDATA[<p>傳統作法是用 rake blah foo=1 這樣的指令，於是就可以透過環境變數拿到：</p>
<pre>
<code>
  task :blah do
    puts ENV['foo']
  end
</pre>
<p></code></p>
<p>但是，最近看到新的 API 使用中括號的用法 (也不新了，從 <a href="http://github.com/jimweirich/rake/commit/f0df74a0b7368cddf6718164bc7ce3d0ccd91e33">0.8.2</a> 開始支援)，覺得挺有趣的：</p>
<pre>
<code>
  desc "passing 1 parameter to rake task"
  task :blah1, [:a] do |t,args|
    puts args.inspect
  end
   </code>
</pre>
<p> 執行 rake blah1[9] 會輸出 {:a=>"9"}，注意到傳進來的變數值是字串。</p>
<pre>
<code>

  desc "passing 2 parameters to rake task"
  task :blah2, [:a, :b] do |t,args|
    puts args.inspect
  end

 </code>
</pre>
<p> 執行 rake blah2[foo,bar] 會輸出 {:a=>"foo", :b=>"bar"}</p>
<p>如果要有預設值，可以這樣做：</p>
<pre>
<code>
  desc "passing parameters with default values to rake task"
  task :blah3, [:a, :b] do |t,args|
    args.with_defaults(:a => 'foobar', :b => 1)
    puts args.inspect
  end    

</code>
</pre>
<p>此時執行 rake blah3 則是輸出 {:a=>"foobar", :b=>1}</p>
<p>對了，好奇 t 是什麼? 那是 <a href="http://rake.rubyforge.org/classes/Rake/Task.html">Rake::Task</a> 物件。</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3546/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>自定 YAML Config 設定檔</title>
		<link>http://ihower.tw/blog/archives/3515</link>
		<comments>http://ihower.tw/blog/archives/3515#comments</comments>
		<pubDate>Wed, 30 Dec 2009 14:31:08 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3515</guid>
		<description><![CDATA[從 RailsTips: Config So Simple Your Mama Could Use It 這篇看到一個非常簡單漂亮的用法，因為還蠻常
在 Rails 裡面用到的，特此一記：

可以將如下的 YAML 檔放在 config 目錄下，這裡用了一招 &#038;DEFAULTS 可以複製相同的部分：


DEFAULTS: &#038;DEFAULTS
  email: no-reply@harmonyapp.com
  email_signature: &#124;
    Regards,
    The Harmony Team

development:
  domain: harmonyapp.local
  ]]></description>
			<content:encoded><![CDATA[<p>從 <a href="http://railstips.org/2009/11/10/app-configuration-so-simple-your-mama-could-use-it">RailsTips: Config So Simple Your Mama Could Use It</a> 這篇看到一個非常簡單漂亮的用法，因為還蠻常<br />
在 Rails 裡面用到的，特此一記：<br />
<span id="more-3515"></span><br />
可以將如下的 YAML 檔放在 config 目錄下，這裡用了一招 &#038;DEFAULTS 可以複製相同的部分：</p>
<pre>
<code>
DEFAULTS: &#038;DEFAULTS
  email: no-reply@harmonyapp.com
  email_signature: |
    Regards,
    The Harmony Team

development:
  domain: harmonyapp.local
  <<: *DEFAULTS

test:
  domain: harmonyapp.com
  <<: *DEFAULTS

production:
  domain: harmonyapp.com
  <<: *DEFAULTS
</code>
</pre>
<p>然後將以下這個 Module 檔放到 lib 目錄下 (或是 config/initializers 下也可以)：</p>
<pre>
<code>
# /lib/harmony.rb
module Harmony
  # Allows accessing config variables from harmony.yml like so:
  # Harmony[:domain] => harmonyapp.com
  def self.[](key)
    unless @config
      raw_config = File.read(RAILS_ROOT + "/config/harmony.yml")
      @config = YAML.load(raw_config)[RAILS_ENV].symbolize_keys
    end
    @config[key]
  end

  def self.[]=(key, value)
    @config[key.to_sym] = value
  end
end
</code>
</pre>
<p>如此便可以讀到 Harmony[:domain] 了，依據不同 Rails 環境。</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3515/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Moneta: 提供  key/value stores 的統一介面</title>
		<link>http://ihower.tw/blog/archives/3420</link>
		<comments>http://ihower.tw/blog/archives/3420#comments</comments>
		<pubDate>Mon, 21 Dec 2009 10:00:50 +0000</pubDate>
		<dc:creator>ihower</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://ihower.tw/blog/?p=3420</guid>
		<description><![CDATA[今天我想特別介紹這一套 Ruby library: Moneta
它提供了 key-value stores 標準共通的使用介面，讓你可以用相同的程式，但是可以輕易轉換底層實際使用的儲存庫，包括：

Basic File Store
BerkeleyDB
CouchDB
DataMapper
File store for xattr
In-memory store
Memcache store
Redis
S3
SDBM
Tokyo
Xattrs in a file system

它的用法其實跟 Hash API 差不多，非常容易使用。我認為最實際的用途是用在撰寫快取程式了。
因為不同環境可以輕易切換 store 的這個好處，我在 local 的 development 環境中，可以使用 In-memory store 或 File Store (前者重開 server 快取資料就會消失，後者則會留著)，不需要多裝東西就可以寫快取。更重要的是，團隊中其他人也不需要費心設定 (叫每個人都去裝 Memcached 也太辛苦了)。而在 production 正式環境中，則可以輕易設定成使用 Memcached。
我自己也用了 Moneta 介面寫了一個小程式 Headcache，提供了 get_and_set 功能：

data = Handcache.get_and_set("data-123", :expires_in => 60 ) do
   [...]]]></description>
			<content:encoded><![CDATA[<p>今天我想特別介紹這一套 Ruby library: <a href="http://github.com/wycats/moneta/">Moneta</a></p>
<p>它提供了 key-value stores 標準共通的使用介面，讓你可以用相同的程式，但是可以輕易轉換底層實際使用的儲存庫，包括：</p>
<ul>
<li>Basic File Store</li>
<li>BerkeleyDB</li>
<li>CouchDB</li>
<li>DataMapper</li>
<li>File store for xattr</li>
<li>In-memory store</li>
<li>Memcache store</li>
<li>Redis</li>
<li>S3</li>
<li>SDBM</li>
<li>Tokyo</li>
<li>Xattrs in a file system</li>
</ul>
<p>它的用法其實跟 Hash API 差不多，非常容易使用。我認為最實際的用途是用在撰寫快取程式了。</p>
<p>因為不同環境可以輕易切換 store 的這個好處，我在 local 的 development 環境中，可以使用 In-memory store 或 File Store (前者重開 server 快取資料就會消失，後者則會留著)，不需要多裝東西就可以寫快取。更重要的是，團隊中其他人也不需要費心設定 (叫每個人都去裝 Memcached 也太辛苦了)。而在 production 正式環境中，則可以輕易設定成使用 <a href="http://memcached.org/">Memcached</a>。</p>
<p>我自己也用了 Moneta 介面寫了一個小程式 <a href="http://github.com/ihower/handcache">Headcache</a>，提供了 get_and_set 功能：</p>
<pre><code>
data = Handcache.get_and_set("data-123", :expires_in => 60 ) do
                "cached-foobar"
            end
</code></pre>
<p>如果快取存在，就回傳快取資料；如果不存在，就執行 code block，並將最後的運算值回傳並快取起來。</p>
<p>如果是在 View 中搭配 partial 使用也非常簡單：</p>
<pre><code>
&lt;%= Handcache.get_and_set( dom_id(@post), :expires_in => 60 ) do
               render :partial => "post"
           end %>
</code></pre>
<p>設定的方法則可以是：</p>
<pre><code>
# config/environments/development.rb
begin
  # for developer has tokyo cabinet
  Handcache = Moneta::Tyrant.new( :host => 'localhost', :port => 1978 )
rescue
  # for developer has not tokyo cabinet
  Handcache = Moneta::BasicFile.new( :path => "tmp" )
end
</code></pre>
<p>關於快取這件事情的學問，可以參考我之前的 <a href="http://ihower.tw/blog/archives/1768">Memcached</a> 文章：一是如何清除過期的快取資料(expire)，二是注意快取 Key 的命名。</p>
]]></content:encoded>
			<wfw:commentRss>http://ihower.tw/blog/archives/3420/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
