Ruby 将SVN导入Dreamhost

# ssh to dreamhost account
svn import /home/USER/path/to/source file:///home/USER/path/to/repository --message="Importing Project"

Ruby Ruby数独求解器

#!/usr/bin/ruby

10.times do
  s = 0
  1.upto(9) do |x|
    1.upto(9) do |y|
      1.upto(9) do |z|
        if x + y + z == 15 && x != y && x != z && y != z
          1.upto(9) do |a|
            1.upto(9) do |b|
              1.upto(9) do |c|
                if( ( a + b + c == 15) && ( ( a != b ) && ( a != c ) && ( b != c ) ) )
                  1.upto(9) do |i|
                    1.upto(9) do |o|
                      1.upto(9) do |p|
                        if( ( i + o + p == 15 ) && ( ( i != o ) && ( i != p ) && ( o != p ) ) ) 
                          if( ( x + a + i == 15 ) && ( ( x != a ) && ( x != i ) && ( a != i ) ) )
                            if( ( y + b + o == 15 ) && ( ( y != b ) && ( y != o ) && ( b != o ) ) )
                              if( ( z + c + p == 15 ) && ( ( z != c ) && ( z != p ) && ( c != p ) ) )
                                if( ( x != b ) && ( x != c ) && ( x != o ) && ( x != p ) )
                                  if( ( y != a ) && ( y != i ) && ( y != c ) && ( y != p ) )
                                    if( ( z != b ) && ( z != a ) && ( z != o ) && ( z != i ) )
                                      s += 1
                                      $stdout.print "Solution ##{s}:\n"
                                      $stdout.print "#{x} #{y} #{z}\n"
                                      $stdout.print "#{a} #{b} #{c}\n"
                                      $stdout.print "#{i} #{o} #{p}\n\n"
                                    end
                                  end
                                end
                              end
                            end
                          end
                        end
                      end
                    end
                  end
                end
              end
            end
          end
        end
      end
    end
  end
end

Ruby rss2模板

xml.instruct!

xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
  xml.channel do

    xml.title       "Feed Name"
    xml.link        url_for :only_path => false, :controller => 'posts'
    xml.pubDate     CGI.rfc1123_date @posts.first.updated_at if @posts.any?
    xml.description "Feed Description"

    @posts.each do |posts|
      xml.item do
        xml.title       post.name
        xml.link        url_for :only_path => false, :controller => 'posts', :action => 'show', :id => post.id
        xml.description post.body
        xml.pubDate     CGI.rfc1123_date post.updated_at
        xml.guid        url_for :only_path => false, :controller => 'posts', :action => 'show', :id => post.id
        xml.author      "#{post.author.email} (#{post.author.name})"
      end
    end

  end
end

Ruby 在Link_to中显示图像

<%= link_to image_tag("search.gif", :border=>0), :action => 'show', :id => user %>

Ruby 101使用Ruby中的Time

#Find out the Current Time
t = Time.now

#Find out the Month, Day, or Year individually
puts t.mon.to_s + "/" + t.day.to_s + "/" + t.year.to_s

#Find out the UTC
puts t.utc

###########################
#User Formatted Characters
###########################
#the String For Time function allows you to mix text with data
puts t.strftime("The Document print data is %m/%d/%Y")

#Another way to Display the Month Day, Year
puts t.strftime("%b %d, %Y")

Ruby Facebook聊天

require 'mechanize'
require 'json'
require 'ostruct'
require 'pp'

class FacebookChat
  def initialize(email, pass); @email, @pass = email, pass; end

  def login
    @agent = WWW::Mechanize.new
    @agent.user_agent_alias = 'Windows IE 7'
    f = @agent.get("http://facebook.com/login.php").forms.first
    f.fields.name("email").value = @email
    f.fields.name("pass").value = @pass
    f.submit
    body = @agent.get("http://www.facebook.com/home.php").body

    # parse info out of facebook home page
    @uid = %r{<a href=".+?/profile.php\?id=(\d+)" class="profile_nav_link">Profile</a>}.match(body)[1].to_i
    @channel = %r{"channel(\d+)"}.match(body)[1]
    @post_form_id = %r{<input type="hidden" id="post_form_id" name="post_form_id" value="([^"]+)}.match(body)[1]
  end

  def wait_for_messages
    determine_initial_seq_number  unless @seq

    begin
      json = parse_json @agent.get(get_message_url(@seq)).body
    end  while json["t"] == "continue"   # no messages yet, keep waiting
    @seq += 1

    json["ms"].select{|m| m['type'] == 'msg'}.map do |msg|
      info = msg.delete 'msg'
      msg['text'] = info['text']
      msg['time'] = Time.at(info['time']/1000)
      OpenStruct.new msg
    end.reject {|msg| msg.from == @uid }  # get rid of messages from us
  end

  def send_message(uid, text)
    r = @agent.post "http://www.facebook.com/ajax/chat/send.php",
      :msg_text => text,
      :msg_id => rand(999999999),
      :client_time => (Time.now.to_f*1000).to_i,
      :to => uid,
      :post_form_id => @post_form_id
  end

  def buddy_list
    json = parse_json(@agent.post("http://www.facebook.com/ajax/presence/update.php",
                        :buddy_list => 1, :post_form_id => @post_form_id, :user => @uid).body)
    json['payload']['buddy_list']['userInfos'].inject({}) do |hash, (uid, info)|
      hash.merge uid => info['name']
    end
  end

  private

  def determine_initial_seq_number
    # -1 will always be a bad seq number so fb will tell us what the correct one is
    json = parse_json @agent.get(get_message_url(-1)).body
    @seq = json["seq"].to_i
  end

  def get_message_url(seq)
    "http://0.channel#{@channel}.facebook.com/x/0/false/p_#{@uid}=#{seq}"
  end

  # get rid of initial js junk, like 'for(;;);'
  def parse_json(s)
    JSON.parse s.sub(/^[^{]+/, '')
  end
end

if __FILE__ == $0
  fb = FacebookChat.new(ARGV.shift, ARGV.shift)
  fb.login

  puts "Buddy List:"
  pp fb.buddy_list

  Thread.abort_on_exception = true
  Thread.new do
    puts usage = "Enter message as <facebook_id> <message> (eg: 124423 hey man wassup?) or type 'buddy' for buddy list"
    loop do
      case gets.strip
      when 'buddy' then pp fb.buddy_list
      when /^(\d+) (.+)$/
        uid, text = $1.to_i, $2
        fb.send_message(uid, text)
      else
        puts usage
      end
    end
  end

  # message receiving loop
  loop do
    fb.wait_for_messages.each do |msg|
      puts "[#{msg.time.strftime('%H:%M')}] #{msg.from_name} (#{msg.from}): #{msg.text}"
    end
  end
end

Ruby 工厂女孩的例子

#### spec_factory.rb
require 'factory_girl'
 
Factory.sequence :login do |n|
  "bob#{n}" 
end
 
Factory.sequence :email do |n|
  "person#{n}@example.com" 
end
 
Factory.sequence :subdomain do |n|
  "joe#{n}" 
end
 
Factory.sequence :checksum do |n|
  n
end
 
Factory.define :user do |u|
  u.login { |l| l.login = Factory.next(:login) }
  u.password "tester1"
  u.password_confirmation "tester1"
  u.email { |e| e.email = Factory.next(:email) }
end
 
Factory.define :blog do |b|
  b.title "Joe's Blog"
  b.subdomain { |s| s.subdomain = Factory.next(:subdomain) }
  b.association :owner, :factory => :user
  b.association :design
end
 
Factory.define :post do |p|
  p.title "First post!"
  p.body "Woot, my blog is sexy!"
  p.association :blog
  p.association :creator, :factory => :user
end
 
 
# post_spec.rb
 
describe Post do
  before(:each) do
    user = Factory(:user)
    blog = Factory(:blog, :owner => user)
    
    @post = Factory(:post, :creator => user, :blog => blog)
  end
  
  describe "validations" do
 
    it "should be valid" do
      @post.should be_valid
    end
  end
end

Ruby 测试所需的属性

def test_required_attributes
    required_atts = [:first_name, :last_name, :credentials, :title1, 
                     :department, :organization, :street, :city, :state, :zip, 
                     :phone, :email]
    required_atts.each do |att|
      r = create_registrant(att => nil)
      assert r.errors.on(att)
    end
  end
  
  private
  
  def create_registrant(options = {})
    Registrant.create({:meeting_id => 1, 
                       :first_name => \"John\", 
                       :middle_name => \"Q\", 
                       :last_name => \"Doe\", 
                       :credentials => \"PhD\", 
                       :title1 => \"Doc\", 
                       :title2 => \"\", 
                       :title3 => \"\", 
                       :department => \"Cardiology\", 
                       :organization => \"DUHS\", 
                       :street => \"12 Erwin Road\", 
                       :city => \"Durham\", 
                       :state => \"NC\", 
                       :zip => \"27707\", 
                       :phone => \"919-490-1000\", 
                       :fax => \"919-490-1001\", 
                       :email => \"johnqdoe@example.com\"}.merge(options))
  end

Ruby 从TextMate运行RSpec for Rails

#######
#Command : 

RUBYLIB="$TM_BUNDLE_SUPPORT/lib:$RUBYLIB" 
"${TM_RUBY:=ruby}" -- "${TM_BUNDLE_SUPPORT}/bin/spec_helper.rb"


#######
#Your.bundle/Support/bin/spec_helper.rb :   require 'cgi'

#try and remove unnecessary '..'s from paths.
#Eg collapse 'config/../app/controllers/../../public' to 'public'.  Hopefully.
def rationalize_path(path)        
  components = path.split("/")
  real_components = []
  components.each do |c|
    if (c == "..") && (real_components.size > 0) && (real_components.last != "..")
      real_components.pop
    else
      real_components.push c
    end
  end
  
  File.join(real_components)
end
  


Dir.chdir(ENV['TM_PROJECT_DIRECTORY'])

output = `rake spec 2>&1`
output = CGI.escapeHTML(output)

#rationalize paths (strip out unnecessary '..'s etc)
output.gsub! /(\.\/|\/)[^:\n&]+\.[^:\n]+/ do |m|
 rationalize_path(m)
end

#Find local file names and make them into proper links
#It ignores any paths that don't start with './'.
# (This is a feature, IMO - too many links otherwise)
output.gsub! /\.(\/[^:&]+):([\d]+)/ do |m|
  path = Dir.pwd + $1
  "<a href=\"txmt://open?url=file://#{path}&line=#{$2}\">#{m}</a>"
end


#Remove unnecessary repitition of the project path.
#Need to keep it in if it's preceeded by '/' - this would indicate it's part of a link url.
output.gsub! /([^\/])#{Dir.pwd}\// do |m|
  $1+'./'
end


#Find the result lines (x specification(s), y failure(s)) and color them
output.gsub! /^[\d]+ specifications?, [\d]+ failures?/ do |m|
  "<span class='result'>#{m}</span>"
end



output.gsub!("\n", "<br/>")

puts <<END
<html>
<head>
  <title>rspec results</title>
  <style type='text/css'>
	body {font-size:0.8em}
	.result {font-weight:bold;}
  </style>
</head>
<body>
<h1>rspec</h1>
#{output}
</body>
</html>
END

Ruby 无表模型

class ${1:name_of_model} < ActiveRecord::Base
      def self.columns() @columns ||= []; end
      def self.column(name, sql_type = nil, default = nil, null = true)
      columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
      end
      
      #insert the names of the form fields here
      column :name, :string
      column :city, :string
      column :state, :string
      column :phone, :string
      column :email_address, :string
  
      #standard validations will go here
      validates_presence_of :name, :email_address
end