目前分類:ruby (24)

瀏覽方式: 標題列表 簡短摘要

編輯ADO.rb,找到connect方法,在

handle.Open(dbname)

handle.BeginTrans()

之間加上

handle.CommandTimeout = 0

Forth 發表在 痞客邦 留言(0) 人氣()

  • rails
  • mongrel
  • mongrel_cluster
  • acts_as_cached
  • acts_as_ferret
  • capistrano
  • fcgi
  • gettext
  • sqlite3-ruby
  • mechanize
  • ruby-net-ldap
  • ruby-openid
  • sendfile
  • log4r
  • rspec
  • ZenTest

Forth 發表在 痞客邦 留言(0) 人氣()

受害者有Oracle、SQLServer、Sybase,以後要記得用gem安裝,不要出錯傻傻查半天。

gem install activerecord-oracle-adapter
gem install activerecord-sqlserver-adapter
gem install activerecord-sybase-adapter

其它可以安裝的adapter:

gem install activerecord-firebird-adapter
gem install activerecord-frontbase-adapter
gem install activerecord-openbase-adapter

Forth 發表在 痞客邦 留言(0) 人氣()

http://svn.techno-weenie.net/projects/plugins/有很多好用的plugin,可以在rails專案中執行

script/plugin source http://svn.techno-weenie.net/projects/plugins/

把repository加入來源清單。之後用

script/plugin list

可以顯示所有repository中的plugin。


Forth 發表在 痞客邦 留言(0) 人氣()

加到application.rb:

module ActiveSupport #:nodoc:
 module CoreExtensions #:nodoc:
   module Hash #:nodoc:
     module Conversions
       unless method_defined? :old_to_xml
         alias_method :old_to_xml, :to_xml
         def to_xml(options = {})
           options.merge!(:dasherize => false)
           old_to_xml(options)
         end
       end
     end
   end
   module Array #:nodoc:
     module Conversions
       unless method_defined? :old_to_xml
         alias_method :old_to_xml, :to_xml
         def to_xml(options = {})
           options.merge!(:dasherize => false)
           old_to_xml(options)
         end
       end
     end
   end
 end
end
module ActiveRecord #:nodoc:
 module XmlSerialization
   unless method_defined? :old_to_xml
     alias_method :old_to_xml, :to_xml
     def to_xml(options = {})
       options.merge!(:dasherize => false)
       old_to_xml(options)
     end
   end
 end
end

Forth 發表在 痞客邦 留言(0) 人氣()

命令:

ruby script/generate scaffold_resource Product

routes.rb:

ActionController::Routing::Routes.draw do |map|
  map.resources :products
end
Action Method URL Helper
index GET /products products_url
create POST /products products_url
new GET /products/new new_product_url
show GET /products/1 product_url(:id => 1)
update PUT /products/1 product_url(:id => 1)
edit GET /products/1/edit edit_product_url(:id => 1)
destroy DELETE /products/1 product_url(:id => 1)

Forth 發表在 痞客邦 留言(0) 人氣()

  1. 下載Qt/Mac
  2. 下載QtRuby
  3. 安裝Qt:
    ./configure -qt-zlib -qt-gif -qt-libpng -qt-libmng -qt-libjpeg -no-framework -fast -no-exceptions -no-stl -no-debug; make; sudo make install
  4. 安裝QtRuby:
    ./configure --enable-mac --with-qt-dir=/usr/local/Trolltech/Qt-4.2.3; make; sudo make install
  5. cd /opt/local/lib/ruby/site_ruby/1.8/i686-darwin8.9.1; sudo mv qtruby4.so qtruby4.bundle
  6. 用irb測試:
    require 'Qt'
    a = Qt::Application.new(ARGV)
    hello = Qt::PushButton.new('Hello World!', nil)
    hello.resize(150, 50)
    hello.show()
    a.exec()

Forth 發表在 痞客邦 留言(0) 人氣()

所需軟體
安裝Ruby
  1. 下載Ruby
  2. 解壓縮至ruby目錄
  3. 切換工作目錄至ruby/bin
  4. 安裝Rails
    gem i rails -y --no-ri --no-rdoc
  5. 安裝JDBC adapter
    gem i activerecord-jdbc -y --no-ri --no-rdoc
安裝JRuby
  1. 下載JRuby
  2. 解壓縮至jruby目錄
  3. 設定環鏡變數JRUBY_HOME,指向jruby目錄
  4. 將jruby/bin目錄加入PATH
  5. 安裝Rails
    gem i rails -y --no-ri --no-rdoc
  6. 安裝JDBC adapter
    gem i activerecord-jdbc -y --no-ri --no-rdoc
  7. 將ruby/bin/rails.cmd複製到jruby/bin目錄
  8. 將ruby/bin/rake.bat複製到jruby/bin目錄
  9. 編輯jruby/bin/rake.bat,將ruby執行檔路徑改成完整路徑,指向ruby/bin/ruby
建立rails專案
  1. 執行rails demo,建立測試專案
  2. 切換工作目錄至demo
  3. 安裝整合plugin
    jruby script/plugin install svn://rubyforge.org/var/svn/jruby-extras/trunk/rails-integration/plugins/war
  4. 啟動伺服器
    jruby script/server
  5. 用瀏覽器開啟http://localhost:3000/
啟動Jetty 6
  1. 下載Jetty 6
  2. 取出壓縮檔裡,lib目錄中的三個jar檔:jetty-*.jar、jetty-util-*.jar、servlet-api-*.jar
  3. 將上述三個jar檔加入CLASSPATH
  4. 切換工作目錄至rails專案
  5. 建立demo.war檔
    rake war:shared:create
  6. 刪除war檔中的WEB-INF\lib\jruby-complete-*.jar,因為會和jruby本身打架
  7. 將文末的程式碼存成server.rb
  8. 啟動伺服器
    jruby server.rb
  9. 用瀏覽器開啟http://localhost:3000/

將war檔佈署至一般的web container,不使用server.rb啟動時,不需刪除war檔中的WEB-INF\lib\jruby-complete-*.jar。開發 時,可以將war檔中的WEB-INF目錄放到rails專案目錄中,再將server.rb中的

WebAppContext.new(contexts, "demo.war", "/")

改成

WebAppContext.new(contexts, ".", "/")

如此,不用建立war檔也能測試。

server.rb
require 'java'

include_class 'org.mortbay.jetty.Server'
include_class 'org.mortbay.jetty.handler.ContextHandlerCollection'
include_class 'org.mortbay.jetty.webapp.WebAppContext'

server = Server.new(3000)
contexts = ContextHandlerCollection.new

WebAppContext.new(contexts, "demo.war", "/")

server.setHandler(contexts)
server.start
server.join

Forth 發表在 痞客邦 留言(0) 人氣()

CRUD HTTP SQL Action
Create POST INSERT create
Read GET SELECT show
Update PUT UPDATE update
Delete DELETE DELETE destroy

Forth 發表在 痞客邦 留言(0) 人氣()

在rails專案目錄中執行

ruby script/plugin install http://themidnightcoders.net:8089/svn/weborb

就會把WebORB安裝到vendor目錄。安裝程式會在config目錄中會建立WEB-INF/flex目錄,存放設定檔, 此外,還會安裝一個weborb_controller.rb到app/controller目錄,public目錄中會多一個examples目錄, 內有可以使用的範例。執行

ruby script/server

啟動伺服器後,可以用瀏覽器測試:

http://localhost:3000/examples/main.html
http://localhost:3000/examples/example.html

WebORB所附的範例中,提供了example.mxml,可以試著改一改亂玩一下,再用mxmlc編譯:

mxmlc --compiler.services ../../config/WEB-INF/flex/services-config.xml -compiler.context-root ../../config/WEB-INF/flex example.mxml

記得要加上述參數,不然編出來的檔案不會動。

Forth 發表在 痞客邦 留言(0) 人氣()

FreeBSD和OS X使用者可以下載wretch.rb,使用前需先安裝Ruby和mechanize;Windows使用者可以下載wretch.exe,下載後直接執行,不需要安裝其它程式。若在FreeBSD或OS X執行,被下載的相片會被儲存在「帳號/相簿編號_相簿名稱」目錄,在Windows則是儲存在「帳號/相簿編號」目錄。使用方法:

  • 備份所有相簿: wretch 帳號 -a
  • 備份指定相簿: wretch 帳號 相簿編號
  • 備份多本相簿: wretch 帳號 相簿編號1 相簿編號2 相簿編號3 相簿編號N
  • 備份有密碼的相簿: wretch -p 密碼 帳號 相簿編號

Forth 發表在 痞客邦 留言(0) 人氣()

  1. 下載並安裝MacPorts。
  2. 開一個terminal。
  3. 把/opt/local/bin和/opt/local/sbin加入PATH。
  4. 執行sudo port selfupdate。
  5. 執行sudo port install ruby。
  6. 執行sudo port install rb-rubygems。
  7. 執行sudo gem install rails -y。
  8. 執行sudo gem install mongrel -y。

Forth 發表在 痞客邦 留言(0) 人氣()

require 'uuid'

module ActiveRecord
  module UseUuid #:nodoc:

    def self.append_features(base)
      super
      base.extend(ClassMethods)
    end

    module ClassMethods
      def use_uuid(options = {})
        class_eval do
          set_primary_key options[:column] if options[:column]

          def after_initialize
            self.id ||= UUID.getUUID
          end
        end
      end
    end
  end
end

ActiveRecord::Base.class_eval do
  include ActiveRecord::UseUuid
end

Forth 發表在 痞客邦 留言(0) 人氣()

#!/usr/local/bin/ruby
require "dbi"

require "parsedate"

db_plog_dsn = "dbi:Mysql:plogdb:localhost"
db_wp_dsn = "dbi:Mysql:wptest:localhost"
db_username = ARGV[0]
db_password = ARGV[1]

Category = Struct.new(:id, :name, :description)
Post = Struct.new(:id, :category, :title, :content, :createDateTime, :modifyDateTime, :status)

wp_cats = Hash.new(nil)
wp_posts = Hash.new(nil)
plog_cats = Hash.new(nil)
plog_posts = Hash.new(nil)

wp_conn = DBI.connect(db_wp_dsn, db_username, db_password)
plog_conn = DBI.connect(db_plog_dsn, db_username, db_password)

# initialize wp_cats
wp_conn.select_all("SELECT * FROM wp_categories") do |row|
  wp_cats[row["cat_name"]] = Category.new(row["cat_ID"], row["cat_name"], row["category_description"])
end

# initialize plog_cats
plog_conn.select_all("SELECT * FROM plog_articles_categories") do |row|
  plog_cats[row["name"]] = Category.new(row["id"], row["name"], row["description"])
end

# initialize wp_posts
wp_conn.select_all("SELECT wp_posts.ID id, wp_categories.cat_name catetory, wp_posts.post_date create_date_time, wp_posts.post_modified modify_date_time, wp_posts.post_title title, wp_posts.post_content content, wp_posts.post_status status FROM wp_post2cat JOIN wp_categories ON wp_post2cat.category_id=wp_categories.cat_ID JOIN wp_posts ON wp_post2cat.post_id=wp_posts.ID") do |row|
  wp_posts[row["title"]] = Post.new(
    row["id"], row["category"], row["title"],
    row["content"], row["create_date_time"],
    row["modify_date_time"], row["status"])
end

# initialize plog_posts
plog_conn.select_all("SELECT plog_articles.id id, plog_articles_categories.name category, plog_articles.`date` create_date_time, plog_articles.modification_date modify_date_time, plog_articles_text.normalized_topic title, plog_articles_text.`text` content, plog_articles.status status FROM plog_article_categories_link JOIN plog_articles_categories ON plog_article_categories_link.category_id=plog_articles_categories.id JOIN plog_articles ON plog_article_categories_link.article_id=plog_articles.id JOIN plog_articles_text ON plog_article_categories_link.article_id=plog_articles_text.article_id") do |row|
  plog_posts[row["title"]] = Post.new(
    row["id"], row["category"], row["title"],
    row["content"].gsub(/\[@more@\]/, ''),
    row["create_date_time"],
    row["modify_date_time"], row["status"])
end

# create category
plog_cats.each_key do |key|
  if false == wp_cats.has_key?(key)
    puts "Create category \"#{key}\""

    plog_cat = plog_cats[key]
    wp_conn.prepare("INSERT INTO wp_categories (cat_name, category_nicename, category_description) VALUES (?, ?, ?)") do |pstmt|
      pstmt.execute(plog_cat.name, plog_cat.name, plog_cat.description)
    end
    # put created category into hash
    id = wp_conn.select_one("SELECT last_insert_id()")
    wp_cat = Category.new(id, plog_cat.name, plog_cat.description)
    wp_cats[wp_cat.name] = wp_cat
  end
end

# create post
(plog_posts.keys - wp_posts.keys).each do |post_title|
  plog_post = plog_posts[post_title]
  puts "Import #{plog_post.title}"
  createGmtDateTime = Time.local(*ParseDate.parsedate(plog_post.createDateTime)).gmtime.strftime("%Y-%m-%d %H:%M:%S")
  modifyDateTime = plog_post.modifyDateTime
  if modifyDateTime == "0000-00-00 00:00:00"
    modifyDateTime = plog_post.createDateTime
  end
  modifyGmtDateTime = plog_post.modifyDateTime
  if modifyGmtDateTime == "0000-00-00 00:00:00"

    modifyGmtDateTime = createGmtDateTime 
  else
    modifyGmtDateTime = Time.local(*ParseDate.parsedate(modifyGmtDateTime)).gmtime.strftime("%Y-%m-%d %H:%M:%S")
  end
  status = plog_post.status
  if status  == 1
    status = "publish"
  else
    status = "draft"
  end
  wp_conn.prepare("INSERT INTO wp_posts (post_author, post_date, post_date_gmt, post_content, post_title, post_status, post_modified, post_modified_gmt) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") do |pstmt|
    pstmt.execute(1, plog_post.createDateTime, createGmtDateTime, plog_post.content, plog_post.title, status, modifyDateTime, modifyGmtDateTime)
  end
  post_id = wp_conn.select_one("SELECT last_insert_id()")
  wp_conn.prepare("INSERT INTO wp_post2cat (post_id, category_id) VALUES (?, ?)") do |pstmt|
    pstmt.execute(post_id, wp_cats[plog_post.category].id)
  end
end

wp_conn.disconnect
plog_conn.disconnect

Forth 發表在 痞客邦 留言(0) 人氣()

# Using the algorithm from Hibernate to generate UUID

require 'socket'
require 'thread'

class UUID
  @@instance = nil
  @@mutex = Mutex.new

  def initialize
    @IP = 0
    ipStr = IPSocket.getaddress(Socket.gethostname)
    ipStr.split('.').collect {|a| a.to_i}.pack('C*').each_byte {|a| @IP = (@IP << 8) - 128 + a}
    @counter = -1
    @JVM = (currentTimeMillis >> 8) & 0xffffffff
  end

  def currentTimeMillis
    (Time.new.to_f * 1000).to_i
  end

  def getJVM
    @JVM
  end

  def getCount
    @@mutex.synchronize do
      @counter = (@counter + 1) % 32768
    end
  end

  def getIP
    @IP
  end

  def getHiTime
    currentTimeMillis >> 32
  end

  def getLoTime
    currentTimeMillis & 0xffffffff
  end

  def generate
    sprintf(’%08x-%08x-%04x-%08x-%04x’, getIP, getJVM, getHiTime, getLoTime, getCount)
  end

  def UUID.getInstance
    @@mutex.synchronize do
      @@instance = new unless @@instance
    end
    @@instance
  end

  def UUID.getUUID
    getInstance.generate
  end
end

Forth 發表在 痞客邦 留言(0) 人氣()


Forth 發表在 痞客邦 留言(0) 人氣()

Mongrel Cluster是一支小程式,用來簡化運行多個Mongrel時的設定、啟動及停止。安裝Mongrel Cluster:

gem install mongrel_cluster -y

因為我有數支rails程式,所以把Mongrel Cluster設定檔集中管理,儲存在/home/forth/etc/mongrel目錄中,另外,寫了一支小程式偷懶,不用每次都敲那麼長的命令,只要定義rails程式的名字、起始連接埠、行程數、目錄:

site :myapp, 8000, 4, '/home/www/myapp'

再執行簡單的命令就能控制rails程式:

railsd config_cluster # 產生設定檔供Mongrel Cluster使用
railsd start_cluster # 透過Mongrel Cluster啟動rails程式
railsd stop_cluster # 停止rails程式

Mongrel Cluster提供了一支開機啟動程式:

/usr/local/lib/ruby/gems/1.8/gems/mongrel_cluster-0.2.0/resources/mongrel_cluster

把它複製到/usr/local/etc/rc.d目錄,再修改內容,將CONF_DIR設成/home/forth/etc/mongrel,之後就會在開機時啟動所有rails程式。 偷懶小程式railsd:

Forth 發表在 痞客邦 留言(0) 人氣()

安裝Ruby-GetText-Package

gem install gettext

設定: 建立lib/tasks/gettext.rake:

desc "Update pot/po files." 
task :updatepo do
  require 'gettext/utils'
# Windows需要下一行
#  ENV["MSGMERGE_PATH"] = 'rmsgmerge.cmd'
  GetText.update_pofiles("myapp", Dir.glob("{app,lib,bin}/**/*.{rb,rhtml}"), "myapp 1.0.0")
end

desc "Create mo-files." 
task :makemo do
  require 'gettext/utils'
  GetText.create_mofiles(true, "po", "locale")
end

在config/environment.rb加入:

$KCODE = 'u'
require 'jcode'
require 'gettext/rails'

在app/controller/application.rb加入init_gettext:

class ApplicationController < ActionController::Base
  init_gettext "myapp" 
end

執行

Forth 發表在 痞客邦 留言(0) 人氣()

ActiveRecord的欄位驗證訊息是英文,要改成其它語言,可以覆寫ActiveRecord:: Errors.default_error_messages定義的訊息,如此,就不需要在每個用到validates_*_of的地方加上: message參數。直接在environment.rb加入:

ActiveRecord::Errors.default_error_messages = {
  :inclusion => "不是選項之一",
  :exclusion => "已被保留",
  :invalid => "是無效的",
  :confirmation => "與確認值不符",
  :accepted  => "必需被接受",
  :empty => "不能是空的",
  :blank => "不能是空白",
  :too_long => "太長(最多%d個字)",
  :too_short => "太短(至少%d個字)",
  :wrong_length => "長度不對(必須%d個字)",
  :taken => "已被使用",
  :not_a_number => "不是數字" 
}

Forth 發表在 痞客邦 留言(0) 人氣()

JavaEye是用Ruby on Rails建構的網站,其站長提供了一些運作資料。Ruby VM的效能一向不被看好,不過照這數據來看,每天頂多一、兩萬page view的網站可以放心的用Ruby on Rails建置,而且不需要用上特殊的技巧,連Ruby on Rails內建的動態頁面cache功能都用不到。


Forth 發表在 痞客邦 留言(0) 人氣()

1 2