Ruby 在IE中预览

#!/usr/bin/env ruby -w
require 'win32ole'
require 'timeout'
require ENV['TM_SUPPORT_PATH'] + "/lib/exit_codes.rb"

filename = ENV['TM_FILEPATH'].delete '\\' 
url = "file:///" + %x[cygpath -m "#{filename}"].chomp.capitalize

begin
  Timeout::timeout(5) {
    ie = WIN32OLE.new('InternetExplorer.Application')
    ie.Navigate("#{url}")
    sleep('.2'.to_f) while ie.ReadyState != 4
    ie.Visible = 'true'
  }
rescue Timeout::Error
  puts "Unable connect to #{url} in a reasonable time"
  TextMate.exit_show_tool_tip
end

Ruby 验证模型中的URL

validates_format_of :company_url, :with => /((http|https):\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?)/

Ruby 找人的年龄

def age
  ((Time.now - birthday)/(60*60*24)/365.2422).to_i
end

Ruby 经常发现干扰

# Always be on the lookout for duplicated code. If you find yourself doing 
# asset.incomings.find(:all, :limit => 10) in multiple places, then perhaps you need to 
# pull that into a method of its own. Given the use of the magic number "10", it might
# not be a bad idea to do so anyway.

class Asset < ActiveRecord::Base
  has_many :incomings do
    def recent(count=10)
      find(:all, :limit => count)
    end
  end
end

# Then, you just have to do @asset.incomings.recent to get the first 10 items.

Ruby YAML配置文件示例

#!/usr/bin/ruby -w
require 'yaml'

config = {"pass" => "mybigsecret123", "dir"=>"/cygdrive/c/tmp/", "user"=>"gtcaz", "url"=>"http://snipplr.com"}
p config.to_yaml
open('/cygdrive/c/tmp/config.yml', 'w') {|f| YAML.dump(config, f)}
open('/cygdrive/c/tmp/config.yml') {|f| puts f.read}
conf2 = open('/cygdrive/c/tmp/config.yml') {|f| YAML.load(f) }
conf2.each{ |k, v| puts "#{k} => #{v}" }

Ruby 测试变量是否为空(零)

if session[:counter].nil?
  # code here
end

Ruby 在e / TextMate中检查新的twitters

#!/usr/bin/env ruby

require 'rubygems'
require 'twitter'
require 'net/http'
require 'fileutils'
require ENV['TM_SUPPORT_PATH'] + "/lib/exit_codes.rb"

COCOA_DIALOG = ENV['TM_SUPPORT_PATH'] + "/bin/CocoaDialog"
CACHEDIR = ENV['HOME'] + '/Library/Caches/TwitterMonitor'
FileUtils.mkdir_p CACHEDIR unless File.exist?(CACHEDIR)

template = <<EOF
# .twitter
# 
# Please fill in fields like this:
#
#  email: bla@bla.com (username also works)
#  password: secret
#
email: 
password: 
EOF


# ensure config file for twitter gem exists
begin
  config = YAML::load open(ENV['HOME'] + "/.twitter")
rescue
  open(ENV["HOME"] + '/.twitter','w').write(template)
  config = YAML::load open(ENV['HOME'] + "/.twitter")
end

# make sure there's actually account information in there
if config == false or config.nil? or config['email'].nil? or config['password'].nil?
  res = %x{"#{COCOA_DIALOG}" ok-msgbox --no-newline --float \
  --text "Please edit ~/.twitter to include your twitter email and password" \
  --informative-text "Press OK to edit your ~/.twitter file in a new tab."}
  TextMate.exit_show_tool_tip("Cancelled!") if res == "2"
  `cygstart "txmt://open?url=file://#{ENV['HOME']}/.twitter"`
end

# attempt to retrieve statuses from friend timeline
begin
  statuses = Twitter::Base.new(config['email'], config['password']).timeline
rescue
  success = false
end

isEven = true
bgStyle = ""
statuses.select do |status|
  # ensure messages are suitable for display
  next if status.text.nil? || status.user.name.nil?
  status.text.gsub!(/"/, "'")
  #p status
  
  # try to find the most likely icon for this user
  icon = Dir.glob("#{CACHEDIR}/#{status.user.screen_name}.{gif,jpeg,jpg,png}").first
  
  # download and cache icons if nonexistant or over a month old
  unless icon and File.mtime(icon) > Time.now - 2629743.83
    image = Net::HTTP.get(URI.parse(status.user.profile_image_url))
    icon = CACHEDIR + "/" + status.user.screen_name + "." + status.user.profile_image_url.match(/\.(\w+)\?/)[1]
    icf = open(icon, "w")
    icf.write(image)
    icf.close
  end
  winicon = `cygpath -w #{icon}` # need to leave this out for TextMate.
  (isEven = !isEven) ? bgStyle = "background-color:#EEEEFF;" : bgStyle = ""
  puts "<p style='font-family:Helvetica,Arial,sans-serif; #{bgStyle}'><img src='file://#{winicon}' style='float:left' />#{status.user.name} (#{status.user.screen_name}):<br />#{status.text}</p>"
end

Ruby Ruby del.icio.us

require 'rest'
require 'rexml/document'

module Diu
	URL = "https://api.del.icio.us/v1/"

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

		attr_reader :posts
	end

	class Posts
		class Post
			def initialize(xml_item)
				@href = xml_item.attributes["href"]
				@time = xml_item.attributes["time"]
				@hash = xml_item.attributes["hash"]
				@tag = xml_item.attributes["tag"]
				@description = xml_item.attributes["description"]
				@extended = xml_item.attributes["extended"]
			end

			attr_reader :href, :time, :hash, :tag, :description, :extended
		end

		def initialize(conn)
			@conn = conn
		end

		def find(method, args = nil)
			resource = "posts/%s" % [method]
			request = @conn.request_get(resource, args)

			posts = Array.new
			doc = REXML::Document.new(request)
			doc.elements.each("//post") do |xml_post|
				posts << Post.new(xml_post)
			end
			posts
		end
	end
end

Ruby Ruby del.icio.us示例

require 'diu'

class Exporter
	def to_html(object)
		case object
		when Diu::Posts::Post
			str = ""
			str << "<p><a href=\"%s\">%s</a></p>\n" % [object.href, object.description]
			str << "<p>%s</p>\n" % [object.extended] if object.extended
			if object.tag
				if @tag_link
					tags = object.tag.split(" ")
					tag_str = tags.map {|tag| "<a href=\"#{@tag_link}#{tag}\">#{tag}</a>"}.join("\n")
				else
					tag_str = object.tag
				end
				str << "<p>(tags: %s)</p>\n" % [tag_str]
			end
		when Array
			"<ul>\n%s</ul>\n" % [object.map { |p| "<li>\n%s</li>\n" % [to_html(p)]}.join]
		end
	end

	attr_writer :tag_link
end

def test_diu(username, password)
	conn = Diu::Connection.new(username, password)
	res = conn.posts.find("recent", "tag" => "to-blog")
	exp = Exporter.new()
	exp.tag_link = "http://del.icio.us/#{username}/"
	print exp.to_html(res)
end

Ruby iPhone on Rails

class ApplicationController < ActionController::Base
  exempt_from_layout('iphone_html.erb')
  
  before_filter :check_iphone
  
  protected
  def iphone?
    request.user_agent.include?('iPhone')
  end
  
  def check_iphone
    if iphone?
      request.parameters[:format] = 'iphone_html'
    end
  end
end

class DashboardController < ApplicationController
  def index
    @top_movies = Movie.top_movies
    @movie = @top_movies.first
    
    respond_to do |format|
      format.html # index.html.erb
      format.iphone_html #index.iphone_html.erb
    end
  end
end