Ruby 添加按钮到视图

<%= button_to "Empty cart", :action => :empty_cart %>

Ruby 从一种方法重定向到另一种方法

redirect_to :action => :index

Ruby 适用于TextDrive的Capistrano食谱

## Set these vars up

set :application, "your_appname"                     # The name of the app
set :user, "your_username"                           # Your Textdrive username
set :domain, 'your_servername.textdrive.com'         # Your domain
set :path, "/users/home/#{user}"                     # The path to root of your site
set :port, YOUR_PORT                                 # Your port from Textdrive
set :apps_directory, "railsapps"                     # The directory where you store your rails apps


## Don't have to worry about anything below here

set :repository, "http://url_for.yoursvnrepos.com/svn/#{application}/trunk"
set :svn_username, Proc.new { "your_svn_username --password your_svn_password" }
    
set :deploy_to, "#{path}/#{apps_directory}/#{application}" 

role :web, domain
role :app, domain
role :db,  domain, :primary => true

# Space saving by Visi http://blogs.law.harvard.edu/vgondi/about
set :keep_releases, 3
set :checkout, "export"

task :cold_deploy do
  transaction do
    update_code
    symlink
  end
  
  run "chmod 755 #{deploy_to}/current/script/spawn" 
  run "#{deploy_to}/current/script/spawn"
  restart  
end

task :restart do
  run "#{deploy_to}/current/script/process/reaper -a reload"
end

task :after_deploy do
  #run "cp #{path}/etc/#{application}.yml #{path}/sites/#{application}/current/config/database.yml"

  #setup links to directories in the shared directory
  delete "#{current_path}/public/photos", :recursive => true
  run "ln -nfs #{shared_path}/photos #{current_path}/public/photos" 
end

desc <<-DESC
Removes unused releases from the releases directory. By default, the last 5
releases are retained, but this can be configured with the 'keep_releases'
variable. This will use sudo to do the delete by default, but you can specify
that run should be used by setting the :use_sudo variable to false.
DESC
task :cleanup do
  count = (self[:keep_releases] || 5).to_i
  if count >= releases.length
    logger.important "no old releases to clean up"
  else
    logger.info "keeping #{count} of #{releases.length} deployed releases"
    directories = (releases - releases.last(count)).map { |release|
      File.join(releases_path, release) }.join(" ")

    delete "#{directories}", :recursive => true
  end
end

task :after_setup, :roles=>[:web, :app, :db] do
  
end

Ruby 使用Ruby和rb-appscript而不是Applescript发送Apple Mail

require "appscript"
include Appscript

def send_email(subject, content, *addresses)
  mail = app('Mail')

  msg = mail.outgoing_messages.end.make(:new => :outgoing_message)

  # mail.set(msg.visible, :to => true)  # by default, 
  mail.set(msg.subject, :to => subject)
  mail.set(msg.content, :to => content)
  # mail.set(msg.sender, :to => "sender@domain.com")  # otherwise default email address used

  addresses.each do |addr|
    msg.to_recipients.end.make(:new => :to_recipient, :with_properties => {:address => addr})
  end

  msg.send_  
end

# send_email("subject goes here", "Hello Cruel World!", "email@address.com") # => true

Ruby 搜索方法in irb

#drop this in .irbrc
class Object
  def search_methods(string)
    search_results = ["--","CLASS METHODS","--"]
    search_results << self.methods.find_all{ |i| i.match(/#{string}/) }.sort 
    search_results << ["--", "INSTANCE METHODS","--"]
    search_results << self.instance_methods.find_all{ |i| i.match(/#{string}/) }.sort
    return y(search_results)
  end
end

# now just call #Object.search_methods "your_search" in irb to find a method

Ruby rails中查找方法的快捷方式

class <<ActiveRecord::Base
  alias_method :[], :find
end

Ruby Ruby Twitter示例

require 'twitter'

def test_twitter(username, password)
	conn = Twitter::Connection.new(username, password)
	conn.status.update("Is happy to see beautiful Ruby code :)")
end

Ruby Ruby Twitter CLI

#!/usr/bin/env ruby

require 'twitter'
require 'optparse'

# UI Application

$options = {}

class App
	def initialize(args)
		begin
			parse_options(args)
		rescue ArgumentError, OptionParser::ParseError => msg
			$stderr.print "Error: #{msg}\n"
			exit
		end
	end

	def parse_options(args)
		commands = [:update]

		OptionParser.new do |opts|
			opts.banner = "Usage: twitter [options]"

			opts.on("-c", "--command COMMAND", commands) do |v|
				$options[:command] = v
			end

			opts.on("-m", "--message MESSAGE") do |v|
				$options[:message] = v
			end

			opts.on("-u", "--username USER") do |v|
				$options[:username] = v
			end

			opts.on("-p", "--password PASSWORD") do |v|
				$options[:password] = v
			end

			opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
				$options[:verbose] = v
			end

			opts.on_tail("-h", "--help", "Show this message") do
				puts opts
				exit
			end
		end.parse!(args)

		case $options[:command]
		when :update
			raise ArgumentError, "Update needs a message" if not $options[:message]
		end
	end

	def run()
		case $options[:command]
		when :update
			print "update: %s\n" % [$options[:message]]
			conn = Twitter::Connection.new($options[:username], $options[:password])
			conn.status.update($options[:message])
		end
	end
end

app = App.new(ARGV)
app.run()

Ruby 在控制器或模型中使用帮助程序

# create a new file inside lib/ and call it helpers.rb
# paste the following:

def help
  Helper.instance
end

class Helper
  include Singleton
  # look inside ActionView::Helpers to include any other helpers that you might need
  include ActionView::Helpers::DateHelper
  include ActionView::Helpers::TextHelper
end

# then in any model or controller:
require 'lib/helpers'

# to use:
# help.name_of_helper
# EX: help.pluralize 10, "person"

Ruby 验证者对象

# Encapsulates some object and executes expressions
# in the context of that object tracking the result 
# of the evaluation. As soon as an expression is 
# false, the verification fails.
#
#   verification = Verifier.new('Marcel') do
#     try { size == 6 } # Passes
#     try { size == 5 } # Fails
#     try { raise }     # Doesn't get here
#   end
#
#   verification.verify
#   => false
class Verifier
  class FailedVerification < Exception
  end
  
  class << self
    def verify(object, &block)
      new(object, &block).verify
    end
  end
  
  attr_reader :object, :results, :block
  def initialize(object, &block)
    @object   = object
    @results  = []
    @verified = false
    @block    = block
  end
  
  def verified?
    @verified && results.all?
  end
  
  def verify
    instance_eval(&block)
    @verified = true
  rescue FailedVerification
    false
  end
  
  def try(&block)
    results << object.instance_exec(&block)
    raise FailedVerification if results.last == false
  end
end