Archive for 二月, 2007

[ActiveRecord]Dynamic attribute-based finders

說明:(節錄至ActiveRecord::Base)
Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL.

用法:

可以簡單利用 find_by_xxx or find_all_by_xxx 來取得資料(xxx => column name)
ex: Person.find_by_user_name(user_name)

也可使用複數的條件(and/or)來取得資料
ex: Person.find_by_user_name_and_password(user_name, password)

最最最好用的就是這個功能,先判斷資料是否存在,若存在回傳此筆資料,若不存在 create 這筆資料
ex:
# No 'Summer' tag exists
Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
# Now the 'Summer' tag does exist
Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")

或是不想直接 create 只是先初始化一個新的物件的話
ex:
# No 'Winter' tag exists
winter = Tag.find_or_initialize_by_name("Winter")
winter.new_record? # true

這些finders實在是方便,故特別記一筆以免忘記~

留言數(1)

[DRB]Distributed Ruby Objects Simple Sample

Distributed Ruby Objects (以下簡稱 drb),是 Ruby Standard Library 中用來做到類似 RPC (Remote procedure call) 的函式庫,以下紀錄最基本的 Server 端和 Client 端的 sample。

Server:

require ‘drb’

class TimeServer

def get_current_time
Time.now
end

def stop_server
DRb.stop_service
end

end

uri = ‘druby://localhost:7788′
front_object = TimeServer.new

DRb.start_service(uri, front_object)

# Wait for the drb server thread to finish before exiting.
DRb.thread.join

這樣一來最簡單的 Server 端就OK了,只要執行這段 Ruby code,Client端就可以用 druby://localhost:7788 來叫用服務。

Client:

require ‘drb’

server_uri = “druby://localhost:7788″

timeserver = DRbObject.new_with_uri(server_uri)

#call remote object method ‘get_current_time’
puts timeserver.get_current_time

#stop remote service
timeserver.stop_server

就這麼簡單,不過方便歸方便,安全的問題也要特別注意

若想深入了解的人可以參考以下連結:

Intro to DRb
drb: Ruby Standard Library Documentation

張貼留言

如何在寫一般 Ruby Code 時使用 Rails 的 ActiveSupport

就只要改一行:

require “rubygems”
require “active_support”

就這麼簡單,害我找半天,本以為要像使用 ActiveRecord 般

require “rubygems”
require_gem “activerecord”

依樣畫葫蘆的結果完全沒反應

require “rubygems”
require_gem “activesupport”

怎麼會這樣勒?????
在Google中也沒找到相關資料,我記得require_gem “activerecord” 之後除了ActiveRecord外還可直接使用ActiveSupport,但若只想使用ActiveSupport的功能把整個ActiveRecord都require進來實在太肥,索性直接進 ActiveRecord 的原始碼裡面看到底是怎麼弄的,結果改一行就解決~~

YA~~ 以後可以直接使用 1.days.ago 或是 Time.now.tomorrow 這類簡單的表示法啦~~~

Rails萬歲~~~ OpenSource 萬歲~~~~~

留言 (2)