對抗垃圾信!請您點這裡:

我的E-mail:
我的Skype:My status

2008年4月17日

Yahoo-LifeType-API (Yahoo!奇摩生活+ Ruby API)

今天剛看到生活+釋出API(其實早就釋出了,API網址:http://tw.developer.yahoo.com/lifestyle_api.html)後,就開始把NetBeans打開來寫程式了XD
現在RubyForge的專案還沒開,倒是GoogleCode的已經開了(網址:http://code.google.com/p/yahoo-lifetype-api/)
程式是BSD授權,忘記怎樣包裝Gem檔,等到哪天想起來再包XD
程式使用範例(列出生活+的分類):

#!/usr/bin/env ruby
APPID = "NhYX9XjV34FPxdq7zD8T7wwc4QGI5VWu_48NHh03zbPYUfPpcWrpZzhcVDKFQsH9dQ--"
require 'lifetype'
require 'rexml/document'
include REXML

puts "獲取生活+類別中... 請稍後"
doc = Document.new(LifeType::Class.new(APPID).listClasses)
puts "獲取類別結束"
puts "類別總數: " + doc.get_elements("//rsp/ClassList")[0].attribute("count").to_s
puts "列出類別中... 請稍後"
doc.elements.each("//rsp/ClassList/Class") do |ele|
puts "ID: #{ele.attributes["id"]} -- #{ele.get_elements("Title")[0].text}"
end
puts "列出類別結束"
很簡單的就可以使用了,還有doc喔!
有Bug可以丟到GoogleCode的Issues或者丟到我信箱內
謝謝^^


2007年9月13日

偵測DNS是否還活著.. 用Ruby

有鑒於某台主機的DNS常常掛掉.. 所以就寫了這個小程式..

while true
  `ps aux | grep named`.split("\n").each{|line|
    user, pid, cpu, mem, vsz, rss, tty, stat, start, time, *command = line.split("\s")
    flag = true if command[0] == "/usr/sbin/named"
    `/etc/init.d/named start` unless flag
  }
  sleep 300
end


2007年9月10日

線上Ruby Regular Expression Editor

Ruby/Rails寫到一半.. 忽然需要用到RegExp來驗證某個東西(Ex: E-mail),卻臨時找不到工具可以測試自己寫的RegExp是否正確該怎辦?
沒關係!這邊有個網站:http://www.rubular.com/
這個網站可以讓您線上測試RegExp是否正確唷:)
可以試試看!

資料來源:China on Rails http://chinaonrails.com/topic/view/723/1.html

2007年7月30日

WxWidgets初體驗

最近無聊想寫點小程式.. 可是不想用Visual Basic寫,用Ruby + GUI Toolkit寫
可是該選哪套GUI Toolkit? 說真的.. GTK+好難用喔ˊˋ.. Qt完完全全不想用
WindowsAPI? 那我乾脆用VB就好了=..=
選來選去看來看去.. 乾脆就看了godfat的建議,去玩wxWidgets
wxWidgets在Ruby上的binding叫做WxRuby,我們先來做準備吧。
首先,我們要安裝wxWidgets跟WxRuby
連線到http://www.wxwidgets.org/下載wxWidgets
接著打開命令提示字元,輸入gem i wxruby -y
一切搞定後,就可以開始先來寫個"哈囉握的"
開啟irb,輸入以下程式碼

require 'rubygems'
require 'wx'
include Wx # => 我比較懶XD

class HelloWorld <> on_init override
helloframe = Frame.new(nil, -1, "HelloWorld")
StaticText.new(helloframe, -1, "Wa ha ha")
helloframe.show
end
end

HelloWorld.new.main_loop

在wxWidgets中,每個視窗都是一個Frame,而StaticText則是Label(在VB中就叫做Label,SWT我不知道XD)
Okok.. 可以動對不對? 不能動那就.. (( 當作沒看到

繼續...
或許各位會認為很奇怪,為什麼要自己慢慢寫.. 不要用視覺化的開發工具呢?
現在來跟各位介紹,在GTK中有所謂的Glade,那在wxWidgets呢?當然有wxGlade!
如果不喜歡wxGlade,這邊也有列表:[網址太長請點我]
在wxWidgets中,支援一種叫做XRC(XML Resource)的格式檔案,很多視覺化工具,如wxGlade都支援輸出這種檔案。
這種檔案的好處是不管是哪種開發工具或者程式語言,都可以藉由這個XRC檔案來產生一樣的介面。
各位可以到http://wxglade.sourceforge.net/下載wxGlade,安裝後就可以開始拖拉了。
弄好一個介面後,我們選擇產生XRC檔案。
接著在同個目錄下,新增一個.rb檔案。
假設我們有一個Frame與一個Button
Frame: MainFrame
Button: btnButton
程式碼如下

require 'rubygems'
require 'wx'
include Wx

class MainFrame < btn =" find_window_by_id(xrcid('btnButton'))" xml =" XmlResource.get" xrc_file =" File.join(File.dirname(__FILE__)," main =" MainFrame.new">
OK,大致上就這樣囉..

2007年6月29日

Rails中實做下拉式選單

太久沒有寫文章了.. 最近接到一個案子.. 剛好讓我重溫Select的使用方法..
嗯.. 結果卡在multiple,不知道是我太想睡還是怎樣.. 居然傻了..
跑去#rubyonrails問,一位名為carpet_the_walls的網友給了我他寫的文章,網址是:
http://shiningthrough.co.uk/Select+helper+methods+in+Ruby+on+Rails
在此先謝謝carpet_the_walls (Thank you, carpet_the_walls)

來做個Memo.. 不然又忘記了..
在Rails中真的有一堆Select helper可以用.. 不只carpet_the_walls混淆,連我也模糊不清!
常見的有三個..
select, select_tag, collection_select(其餘的什麼select_date那些不談)
我們先來看看一個基本的下拉式選單骨架

<select name="selection">
  <option value="1">Opt1</option>
  <option value="2">Opt2</option>
</select>
在一個下拉式選單中,有一些是必備的資訊,像是"name"、"value"與"text"三個,在回傳資訊給Server時,"name"將是接收資訊用的,而"value"會傳回被選的值,而"text"則是使用者會看到的字,依上面的例子來講,Opt1、Opt2這兩個就是屬於"text"

開始講講那三種Select helper

select:
  select(object, method, choices, options = {}, html_options = {})
  在ActionView::Helpers::FormOptionsHelper中定義

  • object是一個實體化變數,這裡很明顯的就是要擺上model物件嘛!
  • method則是object的一個屬性,也是資料表中的對應欄位
  • choices就是要被選的選項,可以是陣列或者是雜湊(Hash)
  • options與html_options則是一些選項
在這邊來舉個例子吧
<%= select("project", "teacher_id", @teachers.collect{|t| [t.name, t.id]}, { :include_blank => false }) %>
<%= select("project", "student_id", {"CFC" => '1', "EF" => '2'}) %>
第一個例子中,@teachers在Controller是這樣的
@teachers = Teacher.find(:all, :select => 'id, name')

select_tag:
  select_tag(name, option_tags = nil, options = {})
  在ActionView::Helpers::FormTagHelper中定義

如果你很喜歡手動打option的話.. 那用select_tag準沒錯啦!
在select_tag中,name將會是params所接收值所用的鍵
直接看範例
<%= select_tag 'user', "<option>CFC</option>" %>
這時在Controller中將會用params[:user]來接收傳過來的值
但是select_tag也可以搭配options_for_select或者options_from_collection_for_select一起使用.. 來看一個範例吧
<%= select_tag('sid[]', options_from_collection_for_select(@students, 'id', 'name'), :multiple => true)%>
因為加上了:multiple,所以可以接受多值選擇,這時在Controller接收到的sid將會是一個陣列,這也是我所卡住的地方.. (( 真丟臉

collection_select:
  collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
  在ActionView::Helpers::FormOptionsHelper中定義

如果資料來源是從資料庫來的話,可以使用這個來做下拉式選單。
這個Object不用我說,就是你的model
method呢?當然就是欄位啦
其實嚴格說起來,這只是select+options_from_collection_for_select的組合啦!
範例:
<%= collection_select(:payment, :id, @payments, :id, :name, options ={:prompt => "-Select a continent"}, :class =>"payment") %>

再次謝謝原作者carpet_the_walls:)

2007年6月16日

Ruby library -- SMS

這個Library搭配http://www.twsms.com才可以使用喔!
有任何問題可以直接回這篇文章,或者寫信問我,我信箱是Gmail的,帳號跟我的這個部落格帳號一樣

我先說用法好了:

require 'twsms'
sms = TWSMS.new(username, password) # 帳號密碼
sms.sendSMS(mobile, message) # mobile: 目標手機號碼  message: 要傳的訊息
原始碼:
=begin
  == Information ==
  === Copyright: Apache 2.0
  === Author: CFC < zusocfc@gmail.com >
  === Prog. Name: TWSMS lib
  === Version: 0.1
  == Introduction ==
    TWSMS(Taiwan SMS)
    TWSMS is a SMS sender, it must use with http://www.twsms.com.
    There has no any library for the SMS system in Taiwan. So, I just coded this and release this version.
    This version just support for sending SMS.
  == Featured ==
   
  == Using TWSMS ==
    It just support for standalone class now.
    require it before you use.
  === Using TWSMS by standalone class
    require 'twsms'
    sms = TWSMS.new('username', 'password')
    sms.sendSMS('09xxxxxxxx', 'Hi, there! TWSMS library is so easy to use!')
    sms.sendSMS('09xxxxxxxx', 'Send SMS with options',
        :popup => 1,
        :type => "now",
        :mo => "Y")
=end

%w|uri cgi net/http|.each{|r| require r}

class TWSMS
  def initialize(username, password)
    @uname, @upwd = username, password
    @options = {
      :type => "now", # Sending type: now, vld
      :popup => "",
      :mo => "Y".upcase,
      :vldtime => "86400",
      :modate => "",
      :dlvtime => "",
      :wapurl => "",
      :encoding => "big5"
    }
   
    @errors = {
      -1.to_s.to_sym => "Send failed",
      -2.to_s.to_sym => "Username or password is invalid",
      -3.to_s.to_sym => "Popup tag error",
      -4.to_s.to_sym => "Mo tag error",
      -5.to_s.to_sym => "Encoding tag error",
      -6.to_s.to_sym => "Mobile tag error",
      -7.to_s.to_sym => "Message tag error",
      -8.to_s.to_sym => "vldtime tag error",
      -9.to_s.to_sym => "dlvtime tag error",
      -10.to_s.to_sym => "You have no point",
      -11.to_s.to_sym => "Your account has been blocked",
      -12.to_s.to_sym => "Type tag error",
      -13.to_s.to_sym => "You can't send SMS message by dlvtime tag if you use wap push",
      -14.to_s.to_sym => "Source IP has no permission",
      -99.to_s.to_sym => "System error!! Please contact the administrator, thanks!!"
    }
    @args = []
    @url ||= "http://api.twsms.com/send_sms.php?"
    @url += "username=" + @uname
    @url += "&password=" + @upwd
  end
 
  def sendSMS(mobile, message, opt={})
    @options[:mobile], @options[:message] = mobile, message
    @options.merge!(opt).each{|k, v| @args << k.to_s + "=" + CGI::escape(v.to_s)}
    @url += "&" + @args.join("&")
    self.chk_val
    chk_errors(Net::HTTP.get(URI.parse(@url)))
  end
 
  def chk_val
    @options[:dlvtime] = "" unless @options[:type] == "dlv"
    @options[:wapurl] = "" if @options[:type] != ("push" && "upush")
  end
 
  def chk_errors(resp)
    resp = resp.split("=")[1]
    if @errors.has_key?(resp.to_s.to_sym)
      puts "==========", "Error!! Message: ", @errors[resp.to_s.to_sym]
    else
      puts "==========", "Message has been send! Your message id is: " + resp.to_s
    end
  end
 
  protected :chk_val
end
晚點丟到Google Code Hosting上去...

Updated:
TWSMS on Google Code Hosting: http://code.google.com/p/twsms/
SMSender on RubyForge: http://rubyforge.org/projects/smsender/

2007年6月12日

find_by_randomize -- 讓ActiveRecord可以亂數取資料

請在model內加入:

def self.find_by_randomize
  ids = self.find(:all, :select => [id])
  self.find(ids[rand(ids.size)]["id"].to_i)
end
這樣一來,就可以取亂數選取資料了!

請參考這篇:為你的 Active Record 做出多采多姿的 find

當然囉.. thegiive那個就是我修改的範本:P