Ruby 从Ruby轻松上传到Amazon S3的文件

#!/usr/bin/env ruby

require 'rubygems'
require 'aws/s3'

local_file = ARGV[0]
bucket = ARGV[1]
mime_type = ARGV[2] || "application/octet-stream"

AWS::S3::Base.establish_connection!(
 :access_key_id => 'REPLACE_ME',
 :secret_access_key => 'REPLACE_ME'
)

base_name = File.basename(local_file)

puts "Uploading #{local_file} as '#{base_name}' to '#{bucket}'"

AWS::S3::S3Object.store(
 base_name,
 File.open(local_file),
 bucket,
 :content_type => mime_type 
)

puts "Uploaded!"

Ruby wxCocoaDialog进度条示例

#!/usr/bin/env ruby

cocoadialog = "#{ENV['TM_SUPPORT_PATH']}/bin/CocoaDialog"
 
IO.popen("'#{cocoadialog}' progressbar --title 'Updating...'",'w') do |pbar|
  (1..100).each do |percent|
    pbar.puts "#{percent} #{percent}% Complete\n"
    sleep(1) if percent % 10 == 0 and percent < 100
  end
end

Ruby 超级简单的Speller v3

#!/usr/bin/env ruby -w
# By Geoff Cheshire <gcheshire@gmail.com>
require ENV['TM_SUPPORT_PATH'] + "/lib/exit_codes.rb"
COCOA_DIALOG = "#{ENV['TM_SUPPORT_PATH']}/bin/CocoaDialog"
selection = STDIN.read
IO.popen("aspell -a", 'w+') do |aspell|
  aspell.puts(selection)
  aspell.close_write
  aspell.each do |check|
    if check =~ /^\&/
      data, raw_suggestions = check.split(":")
      signal, original, count, offset = data.split
      suggestions = ""
      raw_suggestions.split(', ').each { |s| suggestions += "\"#{s.chomp}\" " }
      choice=%x("#{COCOA_DIALOG}" dropdown \
          --title "Misspelled Word" \
          --text "There are #{count} suggestions for '#{original}':" \
          --string-output \
          --items #{suggestions} \
          --button1 "Replace" --button2 "Skip" --button3 "Add to dictionary") # No room for a "Cancel" button
        button, replacement = choice.split(" ", 2)
        replacement.chomp!
        case button
          when "Replace"
            selection.gsub!(/#{original}/, replacement) # Replace done globally; all instances of original replaced
          when "Add"
            `echo -e "*#{original}\n#" | aspell -a`
            `"#{COCOA_DIALOG}" ok-msgbox \
              --text "Added '#{original}' to your personal dictionary." \
              --no-cancel --timeout 2`
        end
    end
  end
end
print selection

Ruby Ruby env shebang有警告

#!/usr/bin/env ruby
BEGIN {$VERBOSE = true}

Ruby 从e / TextMate发布到Twitter

#!/usr/bin/env ruby
require 'net/http'
require 'uri'
require ENV['TM_SUPPORT_PATH'] + "/lib/exit_codes.rb"

TW_USER = 'yourusername'
TW_PASS = 'yourpassword'
TW_URL  = 'http://twitter.com/statuses/update.xml'
MAX_LEN = 140

message = STDIN.read.chomp
if message.length > MAX_LEN
  puts "Sorry, your message was #{message.length} characters long; the limit is #{MAX_LEN}."
  TextMate.exit_show_tool_tip
elsif message.empty?
  puts "No message text selected!"
  TextMate.exit_show_tool_tip
end

begin
  url = URI.parse(TW_URL)
  req = Net::HTTP::Post.new(url.path)
  req.basic_auth TW_USER, TW_PASS
  req.set_form_data({'status' => message})
  begin
    res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
    case res
      when Net::HTTPSuccess, Net::HTTPRedirection
        if res.body.empty?
          puts "Twitter is not responding properly"
          TextMate.exit_show_tool_tip
        else
          puts 'Twitter update succeeded'
          TextMate.exit_show_tool_tip
        end
      else
        puts 'Twitter update failed for an unknown reason'
        # res.error!
        TextMate.exit_show_tool_tip
      end
  rescue
    puts $!
    #puts "Twitter update failed - check username/password"
    TextMate.exit_show_tool_tip
  end
rescue SocketError
  puts "Twitter is currently unavailable"
  TextMate.exit_show_tool_tip
end

Ruby Ruby REST

require 'net/https'

module REST
	class Connection
		def initialize(base_url, args = {})
			@base_url = base_url
			@username = args[:username]
			@password = args[:password]
		end

		def request_get(resource, args = nil)
			request(resource, "get", args)
		end

		def request_post(resource, args = nil)
			request(resource, "post", args)
		end

		def request(resource, method = "get", args = nil)
			url = URI.join(@base_url, resource)

			if args
				# TODO: What about keys without value?
				url.query = args.map { |k,v| "%s=%s" % [URI.encode(k), URI.encode(v)] }.join("&")
			end

			case method
			when "get"
				req = Net::HTTP::Get.new(url.request_uri)
			when "post"
				req = Net::HTTP::Post.new(url.request_uri)
			end

			if @username and @password
				req.basic_auth(@username, @password)
			end

			http = Net::HTTP.new(url.host, url.port)
			http.use_ssl = (url.port == 443)

			res = http.start() { |conn| conn.request(req) }
			res.body
		end
	end
end

Ruby Ruby Twitter

require 'rest'

module Twitter
	URL = "http://twitter.com/"

	class Connection
		def initialize(username, password)
			@conn = REST::Connection.new(URL, :username => username, :password => password)
			@status = Status.new(@conn)
		end

		attr_reader :status
	end

	class Status
		def initialize(conn)
			@conn = conn
		end

		def update(message)
			res = @conn.request_post("statuses/update.xml", :status => message)
		end
	end
end

Ruby 阵列#to_csv

require 'CSV'

class Array
  def to_csv
    str=''
    CSV::Writer.generate(str) do |csv|
      self.each do |r|
        csv << r
      end
    end
    str
  end
end

Ruby XML-RPC(远程过程调用)

#Example 1: Find a State in a Specific Sort Order
#A. Import the XMLPRC Library (Thanx Michael Nuemann)
require 'xmlrpc/client'
#B. You have to define the web address that will run the RPC against
server = XMLRPC::Client.new2('http://betty.userland.com/RPC2')
puts server.call('examples.getStateName', 1)

#Example 2: Find product information based on a UPC number
#C. You have to define the web address that will run the RPC against
server = XMLRPC::Client.new2('http://dev.upcdatabase.com/rpc')
#D. lookupUPC is a method, the number is a product UPC
@item = server.call('lookupUPC', '720642442524')
#E. Store the result in an array
p @item
puts "Description :: " + @item["description"]
puts "Type        :: " + @item["size"]

Ruby Ruby中线程的简单示例

def func1
  i = 0
  while i <= 5
    puts "func1 at: #{Time.now}"
    sleep(2)
    i = i + 1
  end
end
def func2
  i = 0
  while i <= 5
    puts "func2 at: #{Time.now}"
    sleep(1)
    i = i + 1
  end
end

puts "Start at: #{Time.now}"
t1 = Thread.new{func1()}
t2 = Thread.new{func2()}
t1.join
t2.join
puts "End at: #{Time.now}"