Category: Ruby
Find in ruby
May 26th, 2011Find in ruby
Ruby has a module find which implement function as commnad "find".
Find.prune is used to stop recursive visit in following directory.
require 'find'
total_size = 0
Find.find(ENV["HOME"]) do |path|
if FileTest.directory?(path)
if File.basename(path)[0] == ?.
Find.prune # Don't look any further into this directory.
else
next
end
else
total_size += FileTest.size(path)
end
end
Cooperating with module such like File, using method like basename, extname, or Module FileTest, user can easy to implement find like functions.
Walk a directory/Recursively in Wikipedia
Wikipedia has a great page about work a directory recursively.
Ruby Html Parser
October 23rd, 2010Rake document
October 22nd, 2010ActiveRecord without Rails
June 14th, 2010Link: http://blog.aizatto.com/2007/05/21/activerecord-without-rails/
The basic idea is to using following method to connect database.
require "active_record"
ActiveRecord::Base.establish_connection(params)
The params must be a hash or object.
Based on this method, user can use yaml to load configure just like rails do:
dbconfig = YAML::load(File.open('database.yml'))
ActiveRecord::Base.establish_connection(dbconfig)
SQLite sample
development: adapter: sqlite3 database: db/development.db pool: 5 timeout: 5000
Migration
ActiveRecord::Migrator.up('db/migrate')
class CreateLogTables < ActiveRecord::Migration
def self.up
create_table :accounts do |t|
t.integer :account_id
end
end
end
Using ActiveRecord
class Account < ActiveRecord::Base
has_many :sessions
end
class Session < ActiveRecord::Base
belongs_to :user
has_many :actions
end
class Action < ActiveRecord::Base
belongs_to :session
end
Logger
ActiveRecord::Base.logger = Logger.new(File.open('log/database.log', 'a'))
ActiveRecord::Base.colorize_logging = false
Accerlerator Net::HTTP download performance
June 10th, 2010Link: http://www.ruby-forum.com/topic/73148
Here is a very useful document about net::http performance. It introduces a idea that small buffer used in rbuf_fill causes interior performance of net/http. And he also introduce a workaround. The general idea is override the default behavior. Here are code:
class OverrideInternetMessageIO < Net::InternetMessageIO
def rbuf_fill
timeout(@read_timeout) {
@rbuf << @socket.sysread(65536)
}
end
end
class NewHTTP < Net::HTTP
def NewHTTP.socket_type
OverrideInternetMessageIO
end
end