Ruby Mediawiki输出

#!/usr/bin/ruby -w

require "mysql"

def grab(dbh, title)
	dbh.query("select old_text from text where old_id=(select rev_text_id from revision where rev_id=(select page_latest from page where page_title='#{title}'));")
end

def all(dbh)
	dbh.query("select page_title,old_text from page,revision,text where rev_id = page_latest and old_id = rev_text_id;")
end

begin
	dbh = Mysql.real_connect("localhost", "wikiuser", ARG[0], "wikidb")
	@title = "Main_Page"
rescue Mysql::Error => e
	puts "Error code: #{e.errno}"
		puts "Error message: #{e.error}"
		puts "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
ensure
	# r = grab(dbh, @title)
	r = all(dbh)
	r.each do |row|
		File.open("/data/shared/backup/wiki/#{row[0]}", "w") do |f|
			f.write(row[1])
		end
	end
	dbh.close if dbh
end

Ruby Ruby命令行选项解析器

require 'optparse'

app = Hash.new

options = OptionParser.new do |opts|
  opts.on("-o", "--option [ARG]", "Option description") do |opt|
    app['option'] = opt
  end
end

begin
  options.parse!(ARGV)
rescue OptionParser::ParseError => e
  puts e
end

Ruby 阅读YAML文件

require 'yaml'
settings = YAML::load_file('filename.yaml')

Ruby 使用TextMate的tm_dialog命令显示警告框

SUPPORT = ENV['TM_SUPPORT_PATH']
DIALOG = ENV['DIALOG']

require SUPPORT + '/lib/escape'
require SUPPORT + '/lib/osx/plist'

title = "My Alert"
message = "This is my alert Box"
buttons = ['OK', 'Close']

params = {
    'alertStyle' => 'informational', 
    'messageTitle' => title, 
    'informativeText' => message, 
    'buttonTitles' => buttons
}

opts = params.to_plist

puts `#{e_sh(DIALOG)} -ep #{e_sh(opts)}`

Ruby base64 enocde / decode

def decode_base64( text )
	text.unpack( "m" )[0]
end

def encode_base64( bin )
	[ bin ].pack( "m" ).gsub( /\s/, "" )
end



text = "The quick brown fox jumps over the lazy dog"

p encode_base64( text )
# => VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZw==
p decode_base64( encode_base64( text ) )
# => The quick brown fox jumps over the lazy dog

Ruby 从shell发布到Twitter

#!/usr/bin/env ruby
#Usage:
# ruby tweet.rb username:password "status message"

def tweet (arguments)
  user, twit = arguments
  response = `curl -s -u #{user} -d status="#{twit}" http://twitter.com/statuses/update.xml | grep truncated`
  unless (response =~ /truncated>false</)
  	 puts "fail: Tweet failed.  Check your user name and password."
  end
end

if (ARGV[1].length > 140)
  overlimit = ARGV[1].length - 140
  offendingSubstring = ARGV[1][140, ARGV[1].length-1]
  puts %Q{FAIL: #{overlimit} characters over the 140-character limit:}
  puts %Q{\t"...#{offendingSubstring}"}
elsif (ARGV.length != 2) ||
   (ARGV[1] == "")
  puts %Q{usage: ruby tweet.rb <username> "This will be tweeted to Twitter."}
else
  tweet(ARGV)
end

Ruby 将RubyGems更新到最新版本(如何升级gem命令)

sudo gem update --system



# OLD WAY, for historical purposes

sudo gem install rubygems-update --no-rdoc --no-ri
sudo update_rubygems

Ruby TextMate Ruby Snippet检索

#!/usr/bin/ruby
$: << ENV['TM_SUPPORT_PATH'] + '/lib'

require "cgi"
require "ui"
require "xmlrpc/client"

unless ENV['SNIPPLR_KEY']
  TextMate::UI.alert(:critical, "Snipplr error", "Please first set your 'SNIPPLR_KEY' in Preferences > Advanced > Shell Variables.")
  exit
end

TextMate::UI.request_string(:title => "Get Snippet from Snipplr",
                            :prompt => "Enter tags to search for:",
                            :button1 => "Search") do |tag|

  begin
    server = XMLRPC::Client.new2("http://snipplr.com/xml-rpc.php")
    snippet_list = server.call('snippet.list', ENV['SNIPPLR_KEY'], tag)
  rescue
    # fall through
  end

  unless snippet_list and snippet_list.length > 0
    TextMate::UI.alert(:warning, "Snipplr result", "No snippets for '#{tag}' found.")
  else
    items = {}
    snippet_list.each { |r| items[r['title']] = r['id'] }

    TextMate::UI.request_item(:items => items.keys.sort,
                              :title => "Snipplr result",
                              :prompt => "Choose",
                              :string => "Select which snippet to paste") do |item|
      begin
        snippet = server.call('snippet.get', items[item])
        puts CGI.unescapeHTML(snippet['source'])
      rescue
        TextMate::UI.alert(:critical, "Snipplr error", "Could not retrieve '#{item}'.")
      end
    end
  end
end

Ruby 使用MANP在mac os 10.5上安装mysql gem

sudo gem install mysql -- --with-mysql-config=/Applications/MAMP/Library/bin/mysql_config

Ruby 在ruby中获取站点

#!/usr/local/bin/ruby
require 'rubygems'
require 'curl-multi'


curl = Curl::Multi.new


on_success = lambda do |body|
  puts body
end

on_failure = lambda do |ex|
  puts 'Failure.'
  puts ex
end


curl.get('http://www.wp.pl', on_success, on_failure)
curl.select([],[]) while curl.size > 0;