編輯ADO.rb,找到connect方法,在
handle.Open(dbname)
和
handle.BeginTrans()
之間加上
handle.CommandTimeout = 0
編輯ADO.rb,找到connect方法,在
handle.Open(dbname)
和
handle.BeginTrans()
之間加上
handle.CommandTimeout = 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
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。
加到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
命令:
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) |
./configure -qt-zlib -qt-gif -qt-libpng -qt-libmng -qt-libjpeg -no-framework -fast -no-exceptions -no-stl -no-debug; make; sudo make install
./configure --enable-mac --with-qt-dir=/usr/local/Trolltech/Qt-4.2.3; make; sudo make install
cd /opt/local/lib/ruby/site_ruby/1.8/i686-darwin8.9.1; sudo mv qtruby4.so qtruby4.bundle
require 'Qt' a = Qt::Application.new(ARGV) hello = Qt::PushButton.new('Hello World!', nil) hello.resize(150, 50) hello.show() a.exec()
gem i rails -y --no-ri --no-rdoc
gem i activerecord-jdbc -y --no-ri --no-rdoc
gem i rails -y --no-ri --no-rdoc
gem i activerecord-jdbc -y --no-ri --no-rdoc
jruby script/plugin install svn://rubyforge.org/var/svn/jruby-extras/trunk/rails-integration/plugins/war
jruby script/server
rake war:shared:create
jruby server.rb
將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檔也能測試。
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
CRUD | HTTP | SQL | Action |
---|---|---|---|
Create | POST | INSERT | create |
Read | GET | SELECT | show |
Update | PUT | UPDATE | update |
Delete | DELETE | DELETE | destroy |
在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
記得要加上述參數,不然編出來的檔案不會動。
FreeBSD和OS X使用者可以下載wretch.rb,使用前需先安裝Ruby和mechanize;Windows使用者可以下載wretch.exe,下載後直接執行,不需要安裝其它程式。若在FreeBSD或OS X執行,被下載的相片會被儲存在「帳號/相簿編號_相簿名稱」目錄,在Windows則是儲存在「帳號/相簿編號」目錄。使用方法:
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
#!/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
# 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
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:
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
執行
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 => "不是數字" }
JavaEye是用Ruby on Rails建構的網站,其站長提供了一些運作資料。Ruby VM的效能一向不被看好,不過照這數據來看,每天頂多一、兩萬page view的網站可以放心的用Ruby on Rails建置,而且不需要用上特殊的技巧,連Ruby on Rails內建的動態頁面cache功能都用不到。