ruby 不推荐使用rspec stub

不推荐使用rspec stub

rspec_deprecated.rb
class Foo
  def repeat
    2.times { repeated }
  end

  def repeated; end
end

describe Foo do
  let(:foo) { stub method1:"hello" }

  context "stub" do
    it "is deprecated to use double" do
      expect(foo.method1).to eq "hello"
    end
  end

  context "stub!" do
    let(:foo) { Foo.new }

    it "is deprecated" do
      foo.stub! bar:"bar"
      expect(foo.bar).to eq "bar"
    end
  end

  context "any_number_of_times" do
    it "is deprecated" do
      Foo.any_instance.should_receive(:repeated).any_number_of_times
      Foo.new.repeat
    end
  end
end

ruby 不推荐使用rspec stub

不推荐使用rspec stub

rspec_deprecated.rb
class Foo
  def repeat
    2.times { repeated }
  end

  def repeated; end
end

describe Foo do
  let(:foo) { stub method1:"hello" }

  context "stub" do
    it "is deprecated to use double" do
      expect(foo.method1).to eq "hello"
    end
  end

  context "stub!" do
    let(:foo) { Foo.new }

    it "is deprecated" do
      foo.stub! bar:"bar"
      expect(foo.bar).to eq "bar"
    end
  end

  context "any_number_of_times" do
    it "is deprecated" do
      Foo.any_instance.should_receive(:repeated).any_number_of_times
      Foo.new.repeat
    end
  end
end

ruby 获得国家的时区

获得国家的时区

time_zone_for_country.rb
c = TZInfo::Country.get('US')
zones = c.zone_identifiers

ruby 格式化时间从秒到字符串HH:MM:SS,反之亦然

格式化时间从秒到字符串HH:MM:SS,反之亦然

seconds_converter.rb
# format time from seconds to string HH:MM:SS and vice versa
# idea from http://stackoverflow.com/questions/2378171/convert-durations-in-ruby-hhmmss-sss-to-milliseconds-and-vice-versa

def seconds_to_string(time_in_seconds)
  Time.at(time_in_seconds).utc.strftime("%H:%M:%S")
end

def string_to_seconds(time)
  # [second, minute, hour] in seconds
  intervals = [1, 60, 3600]
  time.split(':').map{|time| time.to_i * intervals.pop}.inject(&:+)
end

puts seconds_to_string(82) # => 00:01:22
puts string_to_seconds("00:01:22") # => 82

ruby paged_scope.rb

paged_scope.rb
module ActiveSupport
  module PagedScope
    def self.extended(base)
      base.scope :paginated, lambda { |page,per_page|
        page ||= 0
        per_page ||= 25

        base.limit( per_page.to_i ).offset( per_page.to_i * page.to_i )
      }
    end
  end
end

class User < ActiveRecord::Base
  extend ActiveSupport::PagedScope
end

>> User.paginated(1,25).count
=> 25

ruby 通过使用Ggl的地理编码Web服务获取给定地址的地图位置

通过使用Ggl的地理编码Web服务获取给定地址的地图位置

get_locations.rb
require 'open-uri'
require 'json'
require 'ostruct'

def get_lat_lon( address, times = 0 )
  url = "http://maps.google.com/maps/api/geocode/json?address=#{URI.escape(address)}&sensor=false"
  #puts "Requesting: #{url}"
	page = open(url).readlines.to_s
	document = JSON.parse( page )
	results = document["results"]
  o = nil
  if results && results.size > 0
    o = []
    results.each do |a|
      o << OpenStruct.new(a)
    end
    if o.size > 1 && times == 0
      puts "Found #{o.size} addresses!"
      puts "Requesting again address #{o[0].formatted_address}..."
      o = get_lat_lon(o[0].formatted_address, 1)
    end
  end
  o
end

w = File.open('out.csv', 'a+')
f = File.open('LibInfo1.csv').readlines.collect{|i| i.strip}
f.each_with_index do |x, i|
	next if i == 0
	parts = x.split(';')
	p "Getting address for :#{parts[0]}"
	address = [parts[1], parts[2]].join(' ')
	o = get_lat_lon( address )
	if o && o.size > 0
	  puts "Found #{o.size} addresses!"
    puts "LAT:#{o[0].geometry["location"]["lat"].to_f}"
    puts "LON:#{o[0].geometry["location"]["lng"].to_f}"
    parts << o[0].geometry["location"]["lat"]
    parts << o[0].geometry["location"]["lng"]
    parts = parts.join(';')
	  sleep 1
  end
  w.write("#{parts}\n")
end

#o = get_lat_lon( modified_address )
#puts "Found #{o.size} addresses!"
#puts "LAT:#{o[0].geometry["location"]["lat"].to_f}"
#puts "LON:#{o[0].geometry["location"]["lng"].to_f}"

ruby Capistrano样本

Capistrano样本

deploy.rb
def prompt_with_default(var, default)
        set(var) do
                Capistrano::CLI.password_prompt "#{var} [#{default}] : "
        end
        set var, default if eval("#{var.to_s}.empty?")
end

namespace :misc do
        desc "Remove problematic packages"
        task :remove do
                sudo "apt-get remove grub-pc"
                sudo "apt-get -y autoremove"
        end
        desc "Update apt-get sources"
        task :update do
          sudo "apt-get update"
        end

        desc "Upgrade packages"
        task :upgrade do
          sudo "apt-get -y upgrade"
        end

        desc "Install Development Tools"
        task :install_dev do
          sudo "apt-get install build-essential -y"
        end

        desc "Install Git"
        task :install_git do
          sudo "apt-get install git-core git-svn -y"
        end
end

namespace :mysql do
    desc "Install Mysql-server"
    task :install do
      begin
        # Ask user for a password to configure for external access
        prompt_with_default(:mysql_admin_password, "DeFaUlTPwd")
        # Create a temo text file on destination with the user creation, flush and users select (just as debug)
        put %Q{
                GRANT ALL PRIVILEGES ON *.* TO "root"@"%" IDENTIFIED BY "#{mysql_admin_password}";
                FLUSH PRIVILEGES;
                select CONCAT(User,"@",Host) as User, Password from user;
        }, "/tmp/mysql-install-external-password.tmp"
        # Silent install Mysql Server
        sudo "DEBIAN_FRONTEND=noninteractive apt-get -qq -y install mysql-server"
        # Comment bind line to listen on all interfaces
        sudo "sed -i 's/^bind-address/#bind-address/g' /etc/mysql/my.cnf"
        # Import the previously uploaded sql script
        sudo "mysql -Dmysql < /tmp/mysql-install-external-password.tmp"
        # Restart MySQL to apply changes
        sudo "service mysql restart"
      rescue
        raise
      ensure
        # Delete temp file
        sudo "rm /tmp/mysql-install-external-password.tmp"
      end
    end
end

desc "First time server tune"
task :first do
        misc.remove
        misc.update
        misc.upgrade
        misc.install_dev
        misc.install_git
        mysql.install
end

ruby capybara_wait_until.rb

capybara_wait_until.rb
# add this file capybara_wait_until.rb to your /test directory

module Capybara
  class Session
    ##
    #
    # Retry executing the block until a truthy result is returned or the timeout time is exceeded
    #
    # @param [Integer] timeout   The amount of seconds to retry executing the given block
    #
    # this method was removed in Capybara v2 so adding it back if not already defined
    #
    unless defined?(wait_until)
      def wait_until(timeout = Capybara.default_wait_time)
        Capybara.send(:timeout, timeout, driver) { yield }
      end
    end
  end
end

# Use it this way in /test/integration_test_helper.rb:

require 'capybara_wait_until'
module ActionController
  class IntegrationTest
    def wait_for_ajax_to_complete
      # pass timeout in seconds if you need to override default_wait_time
      page.wait_until { page.evaluate_script('jQuery.active === 0') }
    end
  end
end

ruby PCAPファイルを読み込んで,分ごとのTCP / IPパケット数を出力する。

PCAPファイルを読み込んで,分ごとのTCP / IPパケット数を出力する。

ipcount.rb
#!/bin/env ruby

require 'pcap'

count = Hash.new

cap = Pcap::Capture.open_offline(ARGV.shift || 'traffic.cap')
cap.setfilter("ip")
cap.dispatch{|pkt|
   if pkt.ip? and pkt.tcp?
     key = (pkt.time.to_i/60)*60
# p key
     count[key] = 0 if count[key] == nil
     count[key] = count[key] + 1
# p count[key]
   end
}

count.each{|key,value|
   print "#{Time.at(key).to_s}: #{value}\n"
}

ruby gistfile1.rb

gistfile1.rb
def gravatar_url(email,options = {})
	require 'digest/md5'
	hash = Digest::MD5.hexdigest(email)
	url = "http://www.gravatar.com/avatar/#{hash}"
	options.each do |option|
		option == options.first ? url+="?" : url+="&"
		key = option[0].to_s
		value = option[1].to_s
		url+=key + "=" + value
	end
	url
end