Ruby 简单验证检查器

  def check_authentication
    unless session[:admin]
      session[:intended_action] = action_name
      session[:intended_controller] = controller_name
      redirect_to :action => "signin"
    end
  end

Ruby 自动完成菜单

#!/usr/bin/env ruby

SUPPORT  = ENV['TM_SUPPORT_PATH']
DIALOG   = SUPPORT + '/bin/CocoaDialog.exe'
selected_word = ENV['TM_CURRENT_WORD']
x = "--xpos #{ENV['TM_CARET_XPOS']} "
y = "--ypos #{ENV['TM_CARET_YPOS']} "

if selected_word != nil
  menu      = []
  all_words = STDIN.read.split(/\b/)
  all_words.each do |word|
    if word != selected_word
      if word.index(selected_word) == 0
        menu << word + " "
      end
    end
  end

  menu.uniq!
  if menu.length < 1
    abort
  elsif menu.length == 1
    print menu[0].sub(selected_word, '').strip
  else
    selected = %x`"#{DIALOG}" menu --items #{menu} #{x} #{y}`.to_i - 1
    print menu[selected].sub(selected_word, '').strip
  end
end

Ruby 使用Rails TZInfo的国家时区

countries = Country.find(:all)
for country in countries  
    begin
      tzc = TZInfo::Country.get(country.code.upcase)
    rescue 
      puts "can't find TZInfo for #{country.code.upcase}"
      next
    end
    puts tzc.name
    for zone in tzc.zone_names
      puts country.code.upcase
      puts zone
      CountryTimeZone.create(:parent_id => country.id, :name => zone)
    end
end

Ruby Ruby:解析美味的RSS源

require 'rss'
require 'open-uri'

open('http://del.icio.us/rss/chrisaiv') do |http|
response = http.read
result = RSS::Parser.parse(response, false)
items = result.items

items.each do |item|
  puts "Title:" + item.title + "\n" + item.link + " \n" + item.description + "\n"
end

end

Ruby 如何在Ruby中遍历数组

#A. Create an array
names = %w[chris sandy josie billy suzie]

#B. Find the length of the array and iterate through it 
names.length.times do |i|
  puts i.to_s + " " + names[i]
end

Ruby 为您的笔记本电脑获取OSX Leopard电池统计数据

#!/usr/bin/env ruby -wKU
res = Array.new
res = %x(/usr/sbin/ioreg -p IODeviceTree -n "battery" -w 0).grep(/Battery/)[0].match(/\{(.*)\}/)[1].split(',')
stats = Hash.new

res.each do |d| 
  key, val = d.split("=")
  key.downcase!.delete!(" ")
  if key =~ /\"(.*)\"/
    key = $1
  end
  stats[:"#{key}"] = val
end

puts
puts "-------------------------------"
puts "         Battery Stats"
puts "-------------------------------"
puts
stats.each { |k, v| puts "#{k} => #{v}" }
percentOfOriginal = (stats[:capacity].to_f / stats[:absolutemaxcapacity].to_f) * 100
puts "Battery capacity is currently #{sprintf("%.2f", percentOfOriginal)}% of original."

Ruby TextMate包搜索和粘贴代码

#!/usr/bin/env ruby -wKU
# Copyright 2008 Hirotsugu Asari

require "xmlrpc/client"
require 'cgi'

CMD = [ ENV['TM_SUPPORT_PATH'] +
'/bin/CocoaDialog.app/Contents/MacOS/CocoaDialog' ]

srv = XMLRPC::Client.new2("http://snipplr.com/xml-rpc.php")


if ENV['SNIPPLR_KEY'].nil?
  args = [
    'ok-msgbox', '--no-cancel', '--title "Snipplr"',
    '--text "Environment variable SNIPPLR_KEY missing."', '2>/dev/null'
  ]
  %x{ #{ (CMD + args).join(" ") } }
  exit
end


# get tags from user
args = [
  'standard-inputbox', '--title "Get Snippet from Snipplr"',
  '--informative-text "Enter tags to search for"', '--string-output',
  '2>/dev/null'
]

user_response_for_tags = %x{#{(CMD + args).join(" ")}}.split("\n")
if user_response_for_tags[0] == 'Cancel'
  exit
end

# grab snippets from server
matches = []
begin
  matches = srv.call('snippet.list',ENV['SNIPPLR_KEY'],user_response_for_tags[1],'date')
rescue
  args = [
    'ok-msgbox', '--no-cancel', '--title "Snipplr"',
    "--text 'No matching snippet found.'", '2>/dev/null'
  ]
  %x{ #{ (CMD + args).join(" ") } }
  exit
end

## XML-RPC call may return multiple instances of identical item, so trim
## the hash to our needs
snippet_title = {}
matches.each do |h|
  if !snippet_title.has_key?(h['id'])
    snippet_title[h['id']] = h['title']
  end
end

item_string = '' # for CocoaDialog option
snippet_title.each_value do |s|
  item_string += %Q{ '#{s}' }
end

args = [
  'standard-dropdown', '--title "Snipplr"', '--text "Select Snippet"',
  '--exit-onchange', '--string-output', '--items ' + item_string,
  '2>/dev/null'
]

user_choice_for_snippet = %x{#{(CMD + args).join(" ")}}.split("\n")
if user_choice_for_snippet[0] == 'Cancel'
  exit
end

begin
  puts CGI.unescapeHTML(srv.call('snippet.get',snippet_title.index(user_choice_for_snippet[1]))["source"])
rescue
  args = [
    'ok-msgbox', '--no-cancel', '--title "Snipplr"',
    "--text 'No matching snippet found.'", '2>/dev/null'
  ]
  %x{ #{ (CMD + args).join(" ") } }
end

Ruby Snipplr API ruby​​库

module SnipplrAPI
  require 'xmlrpc/client'
  
  API_URL = "http://snipplr.com/xml-rpc.php"
  class Snipplr
    attr_accessor :api_key    
    
    def initialize(key)
      @api_key = key
      @server = XMLRPC::Client::new2(SnipplrAPI::API_URL)
    end
    
    def list(tags="", sort="", limit="")
      cmd = "snippet.list"
      result = @server.call(cmd, @api_key, tags, sort, limit)
    end
    
    def get(snippet_id)
      cmd = "snippet.get"
      result = @server.call(cmd, snippet_id)
    end
    
    def post(title,code,tags="",language="")
      cmd = "snippet.post"
      result = @server.call(cmd, @api_key, title, code, tags, language)
    end
    
    def delete(snippet_id)
      cmd = "snippet.delete"
      result = @server.call(cmd, @api_key, snippet_id)
    end
    
    def checkkey(api_key)
      cmd = "user.checkkey"
      result = @server.call(cmd, api_key)
    end
    
    def languages()
      cmd = "languages.list"
      result = @server.call(cmd)
    end
    
  end
end

# =========================================
# Testing: Do not include in class file 
# =========================================
require 'pp' #used to Pretty Print results not required to use above module

# Replace YOUR_API_KEY below with your assigned API key
# can be found at snipplr.com at http://snipplr.com/settings/
# at the bottom of the page.

key = "YOUR_API_KEY"
snipplr = SnipplrAPI::Snipplr.new(key)

# list your snippets
pp snippets.list

# list only snippets tagged with php or xml
#pp snipplr.list("PHP")

Ruby 通过传入Zipcode从Google地理编码服务中检索城市,州和邮政信息

require 'net/http'
require 'uri'
require "rexml/document"

# Retrieves US Location data based on a passed in Zipcode. Uses
# Google Maps geocoding service to retrieve a Hash of city, state, and zip
# For more info on the service see: http://code.google.com/apis/maps/documentation/geocoding/
# 
# example:
#   puts get_location_data(97030).inspect
# outputs:
#   {:state=>"OR", :zip=>"97030", :city=>"Gresham"}

def get_location_data(zip)
  url = "http://maps.google.com/maps/geo"
  uri = URI.parse(url)
  
  req = Net::HTTP::Get.new(uri.path + "?output=xml&q=#{zip}")
  res = Net::HTTP.start(uri.host, uri.port) do |http|
    http.request(req)
  end
  
  data = res.body
  result = {}
  address = ""
  
  doc = REXML::Document.new data
    
  doc.elements.each('//Placemark[1]/address') do |element|
    address = element.text
  end
  
  if address
    parts = address.split(/[,\s*]/)
    result[:city] = parts[0]
    result[:state] = parts[2]
    result[:zip] = parts[3]
  end
  
  result  
end

Ruby 约会人性化

  def entry_date_humanize( t ) # t:TimeDiff
    sec = t.to_i
    if( sec < 60 ) then
      return sec.to_s + \"s\"
    elsif( sec < (60*60)) then
      return (sec/60).to_s + \"m\"
    elsif( sec < (24*60*60)) then
      return (sec/60/60).to_s + \"h\"
    else
      return (sec/24/60/60).to_s + \"d\"
    end
  end