ruby business_hours.rb

business_hours_test.rb
require "test/unit"
require File.dirname(__FILE__) + '/business_hours'

class BusinessHoursTest < Test::Unit::TestCase
  def setup
    @hours = BusinessHours.new("8:00 AM", "5:00 PM")
  end
  
  def test_within_working_hours
    assert_equal Time.parse("Dec 21, 2009 3:05 PM"), @hours.calculate_deadline(5*60, "Dec 21, 2009 3:00 PM")
  end
  
  def test_start_at_opening_time
    assert_equal Time.parse("Dec 21, 2009 8:05 AM"), @hours.calculate_deadline(5*60, "Dec 21, 2009 7:27 AM")
  end
  
  def test_start_next_day_when_after_closing_time
    assert_equal Time.parse("Dec 21, 2009 8:05 AM"), @hours.calculate_deadline(5*60, "Dec 20, 2009 6:37 PM")
  end
  
  def test_carry_over_remaining_time_onto_next_day
    assert_equal Time.parse("Dec 22, 2009 8:02 AM"), @hours.calculate_deadline(5*60, "Dec 21, 2009 4:57 PM")
  end
  
  def test_skip_full_day
    assert_equal Time.parse("Dec 23, 2009 8:57 AM"), @hours.calculate_deadline(10*60*60, "Dec 21, 2009 4:57 PM")
  end
  
  def test_skip_current_day_before_opening
    assert_equal Time.parse("Dec 22, 2009 9:00 AM"), @hours.calculate_deadline(10*60*60, "Dec 21, 2009 7:57 AM")
  end
  
  def test_update_week_day_hours
    @hours.update :mon, "8:00 AM", "3:00 PM"
    @hours.update :tue, "9:00 AM", "5:00 PM"
    assert_equal Time.parse("Dec 22, 2009 9:02 AM"), @hours.calculate_deadline(5*60, "Dec 21, 2009 2:57 PM")
  end
  
  def test_skip_closed_days
    @hours.closed :sat, :sun
    assert_equal Time.parse("Dec 21, 2009 8:02 AM"), @hours.calculate_deadline(5*60, "Dec 18, 2009 4:57 PM")
  end
  
  def test_change_hours_for_specific_dates
    @hours.update "Dec 24, 2009", "8:00 AM", "3:00 PM"
    @hours.closed :sat, :sun, "Dec 25, 2009"
    assert_equal Time.parse("Dec 28, 2009 8:02 AM"), @hours.calculate_deadline(5*60, "Dec 24, 2009 2:57 PM")
    assert_equal Time.parse("Dec 17, 2009 3:02 PM"), @hours.calculate_deadline(5*60, "Dec 17, 2009 2:57 PM")
  end
  
  def test_start_on_closed_days
    @hours.closed :tue, "Dec 25, 2009"
    assert_equal Time.parse("Dec 23, 2009 8:05 AM"), @hours.calculate_deadline(5*60, "Dec 22, 2009 4:57 PM")
    assert_equal Time.parse("Dec 26, 2009 8:05 AM"), @hours.calculate_deadline(5*60, "Dec 25, 2009 4:57 PM")
  end
end
business_hours.rb
require "time"
require "date"

class Date
  def to_time
    Time.local(year, month, day)
  end
end

class Time
  def to_date
    Date.new(year, month, day)
  end
end

class BusinessHours
  def initialize(opening, closing)
    @schedule = { :default => [opening, closing] }
  end
  
  def update(day, opening, closing)
    key = day.kind_of?(Symbol) ? Date.parse(day.to_s).wday : Date.parse(day)
    @schedule[key] = [opening, closing]
  end
  
  def closed(*days)
    days.each { |day| update(day, "0:00", "0:00") }
  end
  
  def calculate_deadline(interval, start_time)
    Deadline.new(@schedule, interval, Time.parse(start_time)).calculate
  end
  
  class Deadline
    def initialize(*args)
      @schedule, @remaining, @current_time = *args
    end
    
    def calculate
      increment_day while after_today?
      current_or_opening_time + @remaining
    end
    
    private
    
    def after_today?
      current_or_opening_time + @remaining > closing_time
    end
    
    def increment_day
      @remaining -= closing_time - current_or_opening_time if @current_time < closing_time
      @current_time = @current_time.to_date.next.to_time
    end
    
    def current_or_opening_time
      [@current_time, opening_time].max
    end
    
    def opening_time
      Time.parse(current_hours.first, @current_time)
    end
    
    def closing_time
      Time.parse(current_hours.last, @current_time)
    end
    
    def current_hours
      @schedule[@current_time.to_date] || @schedule[@current_time.wday] || @schedule[:default]
    end
  end
end

ruby 更改Rails 3.2.13和4.0如何在JSONMonkey修补程序ActiveSupport中编码unicode以恢复to_json unicode字符编码。

更改Rails 3.2.13和4.0如何在JSONMonkey修补程序ActiveSupport中编码unicode以恢复to_json unicode字符编码。如果你可以控制to_json调用,有一种更好的方法,使用JSON.generate(object,:ascii_only => true)。阅读更多@ http://omegadelta.net/2013/04/28/changes-to-how-rails-3-2-13-and-4-0-encodes-unicode-in-json/

json_escape.rb
# http://omegadelta.net/2013/04/28/changes-to-how-rails-3-2-13-and-4-0-encodes-unicode-in-json/
# http://stackoverflow.com/questions/14823971/json-encoding-decoding-with-unicode-in-rails
# https://gist.github.com/WilliamDenniss/5475630
# thanks: @ William Denniss

module ActiveSupport
  module JSON
    module Encoding
      class << self

      # from https://github.com/rails/rails/blob/v3.2.12/activesupport/lib/active_support/json/encoding.rb#L121
      def escape(string)
        if string.respond_to?(:force_encoding)
          string = string.encode(::Encoding::UTF_8, :undef => :replace).force_encoding(::Encoding::BINARY)
        end
        json = string.
          gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
          gsub(/([\xC0-\xDF][\x80-\xBF]|
                 [\xE0-\xEF][\x80-\xBF]{2}|
                 [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
          s.unpack("U*").pack("n*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&')
        }

        ## alternate encoding from https://github.com/rails/rails/issues/3727
        #json = string.
        #  gsub(escape_regex) { |s| ESCAPED_CHARS[s] }.
        #  gsub(/([\xC0-\xDF][\x80-\xBF]|
        #         [\xE0-\xEF][\x80-\xBF]{2}|
        #         [\xF0-\xF7][\x80-\xBF]{3})+/nx) { |s|
        #  s.unpack("U*").pack("N*").unpack("H*")[0].gsub(/.{4}/n, '\\\\u\&')
        #}

        json = %("#{json}")
        json.force_encoding(::Encoding::UTF_8) if json.respond_to?(:force_encoding)
        json
        end
      end
    end
  end
end

ruby memstats.rb

memstats.rb
#!/usr/bin/env ruby

#------------------------------------------------------------------------------
# Aggregate Print useful information from /proc/[pid]/smaps
#
# pss  - Roughly the amount of memory that is "really" being used by the pid
# swap - Amount of swap this process is currently using
#
# Reference:
#  http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt#361
#
# Example:
#   # ./memstats.rb 4386
#   Process:             4386
#   Command Line:        /usr/bin/mongod -f /etc/mongo/mongod.conf
#   Memory Summary:
#     private_clean             107,132 kB
#     private_dirty           2,020,676 kB
#     pss                     2,127,860 kB
#     rss                     2,128,536 kB
#     shared_clean                  728 kB
#     shared_dirty                    0 kB
#     size                  149,281,668 kB
#     swap                    1,719,792 kB
#------------------------------------------------------------------------------

class Mapping
  FIELDS = %w[ size rss shared_clean shared_dirty private_clean private_dirty swap pss ]
  attr_reader :address_start
  attr_reader :address_end
  attr_reader :perms
  attr_reader :offset
  attr_reader :device_major
  attr_reader :device_minor
  attr_reader :inode
  attr_reader :region

  attr_accessor :size
  attr_accessor :rss
  attr_accessor :shared_clean
  attr_accessor :shared_dirty
  attr_accessor :private_dirty
  attr_accessor :private_clean
  attr_accessor :swap
  attr_accessor :pss

  def initialize( lines )

    FIELDS.each do |field|
      self.send("#{field}=", 0)
    end

    parse_first_line( lines.shift )
    lines.each do |l|
      parse_field_line(l)
    end
  end

  def parse_first_line( line )
    parts = line.strip.split
    @address_start, @address_end = parts[0].split("-")
    @perms = parts[1]
    @offset = parts[2]
    @device_major, @device_minor = parts[3].split(":")
    @inode = parts[4]
    @region = parts[5] || "anonymous"
  end

  def parse_field_line( line )
    parts = line.strip.split
    field = parts[0].downcase.sub(':','')
    value = Float(parts[1]).to_i
    self.send( "#{field}=", value ) if respond_to? "#{field}="
  end
end

def consume_mapping( map_lines, totals )
  m = Mapping.new( map_lines )

  Mapping::FIELDS.each do |field|
    totals[field] += m.send( field )
  end
  return m
end

abort 'usage: memstats [pid]' unless ARGV.first
pid = ARGV.shift.to_i
totals = Hash.new(0)
mappings = []

File.open( "/proc/#{pid}/smaps" ) do |smaps|

  map_lines = []

  loop do
    break if smaps.eof?
    line = smaps.readline.strip
    case line
    when /\w+:\s+/
      map_lines << line
    when /[0-9a-f]+:[0-9a-f]+\s+/
      if map_lines.size > 0 then
        mappings << consume_mapping( map_lines, totals )
      end
      map_lines.clear
      map_lines << line
    else
      break
    end
  end
end

# http://rubyforge.org/snippet/download.php?type=snippet&id=511
def format_number( n )
  n.to_s.gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2')
end

def get_commandline( pid )
  commandline = IO.read( "/proc/#{pid}/cmdline" ).split("\0")
  if commandline.first =~ /java$/ then
    loop { break if commandline.shift == "-jar" }
    return "[java] #{commandline.shift}"
  end
  return commandline.join(' ')
end


puts "#{"Process:".ljust(20)} #{pid}"
puts "#{"Command Line:".ljust(20)} #{get_commandline(pid)}"
puts "Memory Summary:"
totals.keys.sort.each do |k|
  puts "  #{k.ljust(20)} #{format_number( totals[k] ).rjust(12)} kB"
end

ruby 回应?红宝石战士改写

回应?红宝石战士改写

ruby_warrior_respond_to.rb
class Player

  def init(warrior)
    @warrior = warrior
    @low_side ||= 10
    @current_direction ||= :forward
    @backsteps ||= 0
    @skip ||= false
    @turn_count ||= 0
    @health ||= 20
    @surrounded ||= false
    unless @warrior.respond_to? :pivot!
      class << @warrior
        def pivot!
          change_direction
        end
      end
    end
    unless @warrior.respond_to? :look
      class << @warrior
        def look(direction)
          []
        end
      end
    end
  end
  
  def play_turn(warrior)
    init(warrior)
    sit_rep
    surrounded?
    do_stuff! unless @skip
    @skip = false
  end
  
  def sit_rep
    if @turn_count < 1
      front = ranged_enemy? change_direction
      back = ranged_enemy? change_direction
      skip_actions!
      @surrounded = front && back
      @warrior.pivot! if @surrounded
      @turn_count += 1
    end
    hit_wall?
  end
  
  def ranged_enemy?(direction)
    @warrior.look(@current_direction).detect{|space| space.enemy?}
  end
  
  def surrounded?
    if @surrounded && @warrior.feel.stairs?
      @warrior.pivot!
      #change_direction
      skip_actions!
      @low_side = 20
      @surrounded = false
    end
  end
  
  def skip_actions!
    @skip = true
  end
  
  def change_direction
    if @current_direction == :forward
      @current_direction = :backward
      :backward
    elsif @current_direction == :backward
      @current_direction = :forward
      :forward
    end
  end
  
  def do_stuff!
    if @warrior.health < @low_side && @warrior.feel(@current_direction).empty?
      @warrior.rest!
      @low_side = 20
    elsif @warrior.feel(@current_direction).enemy?
      @warrior.attack!(@current_direction)
    elsif @warrior.feel(@current_direction).captive?
      @warrior.rescue!(@current_direction)
    elsif @warrior.look(@current_direction).detect{|item| item.captive?}
      @warrior.walk!
    elsif @warrior.look(@current_direction)[2].enemy?
      @warrior.shoot!
    else
      @warrior.walk!(@current_direction)
      @low_side = 10
      @backsteps = 0
    end
      @health = @warrior.health
  end
  
  def backstep
    change_direction
    @warrior.walk!(@current_direction)
    change_direction
    @backsteps += 1
  end
  
  def hit_wall?
    if @warrior.feel(@current_direction).wall?
      @warrior.pivot!
      skip_actions!
    end
  end
end
  

ruby 通过排除路径文件中定义的路由来检查是否在列出的路由中定义了传入的URL的约束。

通过排除路径文件中定义的路由来检查是否在列出的路由中定义了传入的URL的约束。

old_routes_constraint.rb
class OldRoutesConstraint
  def self.matches?(request)
    # TO-DO: add a check to make sure this code block runs only if no other url matches.
    path = {}
    begin
      _routes = Bangthetable::Application.routes
      _routes.disable_clear_and_finalize = true
      _routes.clear!
      _routes.draw do
        # here you can add any route you want
        # and there will only be routes that are listed below in routes.
        get "/documents/show/:id", :to => "sessions#new"
      end
      ActiveSupport.on_load(:action_controller) { _routes.finalize! }
      path = (Rails.application.routes.recognize_path(request.env["PATH_INFO"], :method => request.env["REQUEST_METHOD"].to_sym) rescue {}) || {}
    ensure
      _routes.disable_clear_and_finalize = false
      Bangthetable::Application.routes_reloader.paths.each{ |path| load(path) }
      # this is where we are reloading the original v2 routes.
      # do not remove this piece of code. Coz from next requests, app will fail.
    end
    Bangthetable::Application.routes_reloader.paths.each{ |path| load(path) }

    return path.has_key?(:controller)
  end
end

ruby 的Watir-广泛,得到元素为基础,对孩子,element.rb

watir-broadly-get-element-based-on-child-element.rb
target_parent = browser.divs( class: 'card' ).find { |div| div.div( class: 'title', text: 'AAAA' ).exists? }
target_element = target_parent.div( class: 'title', text: 'AAAA' )

ruby flavor.rb

flavor.rb
#!/usr/bin/ruby
# Convert a Markdown README to HTML with Github Flavored Markdown
# Github and Pygments styles are included in the output
#
# Requirements: json gem (`gem install json`)
#
# Input: STDIN or filename
# Output: STDOUT 
# Arguments: "-c" to copy to clipboard (or "| pbcopy"), or "> filename.html" to output to a file
# cat README.md | flavor > README.html

require 'rubygems'
require 'json'
require 'net/https'

clipboard_output = false
if ARGV[0] == "-c"
	clipboard_output = true
	ARGV.shift
end

input = ''
if ARGV.length > 0
	if File.exists?(File.expand_path(ARGV[0]))
		input = File.new(File.expand_path(ARGV[0])).read
	else
		puts "File not found: #{ARGV[0]}"
	end
else
	if STDIN.stat.size > 0
		input = STDIN.read
	else
		puts "No input specified"
	end
end

exit if input == ''

def e_sh(str)
	str.to_s.gsub(/(?=[^a-zA-Z0-9_.\/\-\x7F-\xFF\n])/, '\\').gsub(/\n/, "'\n'").sub(/^$/, "''")
end

output = {}
output['text'] = input
output['mode'] = 'gfm'

url = URI.parse("https://api.github.com/markdown")
request = Net::HTTP::Post.new("#{url.path}")
request.body = output.to_json
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
response = http.start {|http| http.request(request) }

if response.code == "200"
	html=<<ENDOUTPUT
<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
	<style>
	html,body{color:black}*{margin:0;padding:0}body{font:13.34px helvetica,arial,freesans,clean,sans-serif;-webkit-font-smoothing:subpixel-antialiased;line-height:1.4;padding:3px;background:#fff;border-radius:3px;-moz-border-radius:3px;-webkit-border-radius:3px}p{margin:1em 0}a{color:#4183c4;text-decoration:none}#wrapper{background-color:#fff;padding:30px;font-size:14px;line-height:1.6;width:900px;margin:15px auto;}@media screen{#wrapper{box-shadow:0 0 0 1px #cacaca,0 0 0 4px #eee}}#wrapper>*:first-child{margin-top:0!important}#wrapper>*:last-child{margin-bottom:0!important}h1,h2,h3,h4,h5,h6{margin:20px 0 10px;padding:0;font-weight:bold;-webkit-font-smoothing:subpixel-antialiased;cursor:text}h1{font-size:28px;color:#000}h2{font-size:24px;border-bottom:1px solid #ccc;color:#000}h3{font-size:18px;color:#333}h4{font-size:16px;color:#333}h5{font-size:14px;color:#333}h6{color:#777;font-size:14px}p,blockquote,ul,ol,dl,table,pre{margin:15px 0}ul,ol{padding-left:30px}hr{background:transparent url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAECAYAAACtBE5DAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6OENDRjNBN0E2NTZBMTFFMEI3QjRBODM4NzJDMjlGNDgiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6OENDRjNBN0I2NTZBMTFFMEI3QjRBODM4NzJDMjlGNDgiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo4Q0NGM0E3ODY1NkExMUUwQjdCNEE4Mzg3MkMyOUY0OCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo4Q0NGM0E3OTY1NkExMUUwQjdCNEE4Mzg3MkMyOUY0OCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PqqezsUAAAAfSURBVHjaYmRABcYwBiM2QSA4y4hNEKYDQxAEAAIMAHNGAzhkPOlYAAAAAElFTkSuQmCC) repeat-x 0 0;border:0 none;color:#ccc;height:4px;padding:0}#wrapper>h2:first-child,#wrapper>h1:first-child,#wrapper>h1:first-child+h2,#wrapper>h3:first-child,#wrapper>h4:first-child,#wrapper>h5:first-child,#wrapper>h6:first-child{margin-top:0;padding-top:0}a:first-child h1,a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6{margin-top:0;padding-top:0}h1+p,h2+p,h3+p,h4+p,h5+p,h6+p{margin-top:0}ul li>:first-child,ol li>:first-child{margin-top:0}dl{padding:0}dl dt{font-size:14px;font-weight:bold;font-style:italic;padding:0;margin:15px 0 5px}dl dt:first-child{padding:0}dl dt>:first-child{margin-top:0}dl dt>:last-child{margin-bottom:0}dl dd{margin:0 0 15px;padding:0 15px}dl dd>:first-child{margin-top:0}dl dd>:last-child{margin-bottom:0}blockquote{border-left:4px solid #DDD;padding:0 15px;color:#777}blockquote>:first-child{margin-top:0}blockquote>:last-child{margin-bottom:0}table{border-collapse:collapse;border-spacing:0;font-size:100%;font:inherit}table th{font-weight:bold}table th,table td{border:1px solid #ccc;padding:6px 13px}table tr{border-top:1px solid #ccc;background-color:#fff}table tr:nth-child(2n){background-color:#f8f8f8}img{max-width:100%}code,tt{margin:0 2px;padding:0 5px;white-space:nowrap;border:1px solid #eaeaea;background-color:#f8f8f8;border-radius:3px}pre>code{margin:0;padding:0;white-space:pre;border:0;background:transparent}.highlight pre,pre{background-color:#f8f8f8;border:1px solid #ccc;font-size:13px;line-height:19px;overflow:auto;padding:6px 10px;border-radius:3px}pre code,pre tt{background-color:transparent;border:0}.poetry pre{font-family:Georgia,Garamond,serif!important;font-style:italic;font-size:110%!important;line-height:1.6em;display:block;margin-left:1em}.poetry pre code{font-family:Georgia,Garamond,serif!important;word-break:break-all;word-break:break-word;-webkit-hyphens:auto;-moz-hyphens:auto;hyphens:auto;white-space:pre-wrap}sup,sub,a.footnote{font-size:1.4ex;height:0;line-height:1;vertical-align:super;position:relative}sub{vertical-align:sub;top:-1px}@media print{body{background:#fff}img,pre,blockquote,table,figure{page-break-inside:avoid}#wrapper{background:#fff;border:0}code{background-color:#fff;color:#444!important;padding:0 .2em;border:1px solid #dedede}pre code{background-color:#fff!important;overflow:visible}pre{background:#fff}}@media screen{body.inverted,.inverted #wrapper,.inverted hr .inverted p,.inverted td,.inverted li,.inverted h1,.inverted h2,.inverted h3,.inverted h4,.inverted h5,.inverted h6,.inverted th,.inverted .math,.inverted caption,.inverted dd,.inverted dt,.inverted blockquote{color:#eee!important;border-color:#555}.inverted td,.inverted th{background:#333}.inverted pre,.inverted code,.inverted tt{background:#444!important}.inverted h2{border-color:#555}.inverted hr{border-color:#777;border-width:1px!important}::selection{background:rgba(157,193,200,.5)}h1::selection{background-color:rgba(45,156,208,.3)}h2::selection{background-color:rgba(90,182,224,.3)}h3::selection,h4::selection,h5::selection,h6::selection,li::selection,ol::selection{background-color:rgba(133,201,232,.3)}code::selection{background-color:rgba(0,0,0,.7);color:#eee}code span::selection{background-color:rgba(0,0,0,.7)!important;color:#eee!important}a::selection{background-color:rgba(255,230,102,.2)}.inverted a::selection{background-color:rgba(255,230,102,.6)}td::selection,th::selection,caption::selection{background-color:rgba(180,237,95,.5)}.inverted{background:#0b2531}.inverted #wrapper,.inverted{background:rgba(37,42,42,1)}.inverted a{color:rgba(172,209,213,1)}}.highlight .c{color:#998;font-style:italic}.highlight .err{color:#a61717;background-color:#e3d2d2}.highlight .k{font-weight:bold}.highlight .o{font-weight:bold}.highlight .cm{color:#998;font-style:italic}.highlight .cp{color:#999;font-weight:bold}.highlight .c1{color:#998;font-style:italic}.highlight .cs{color:#999;font-weight:bold;font-style:italic}.highlight .gd{color:#000;background-color:#fdd}.highlight .gd .x{color:#000;background-color:#faa}.highlight .ge{font-style:italic}.highlight .gr{color:#a00}.highlight .gh{color:#999}.highlight .gi{color:#000;background-color:#dfd}.highlight .gi .x{color:#000;background-color:#afa}.highlight .go{color:#888}.highlight .gp{color:#555}.highlight .gs{font-weight:bold}.highlight .gu{color:#800080;font-weight:bold}.highlight .gt{color:#a00}.highlight .kc{font-weight:bold}.highlight .kd{font-weight:bold}.highlight .kn{font-weight:bold}.highlight .kp{font-weight:bold}.highlight .kr{font-weight:bold}.highlight .kt{color:#458;font-weight:bold}.highlight .m{color:#099}.highlight .s{color:#d14}.highlight .na{color:#008080}.highlight .nb{color:#0086b3}.highlight .nc{color:#458;font-weight:bold}.highlight .no{color:#008080}.highlight .ni{color:#800080}.highlight .ne{color:#900;font-weight:bold}.highlight .nf{color:#900;font-weight:bold}.highlight .nn{color:#555}.highlight .nt{color:#000080}.highlight .nv{color:#008080}.highlight .ow{font-weight:bold}.highlight .w{color:#bbb}.highlight .mf{color:#099}.highlight .mh{color:#099}.highlight .mi{color:#099}.highlight .mo{color:#099}.highlight .sb{color:#d14}.highlight .sc{color:#d14}.highlight .sd{color:#d14}.highlight .s2{color:#d14}.highlight .se{color:#d14}.highlight .sh{color:#d14}.highlight .si{color:#d14}.highlight .sx{color:#d14}.highlight .sr{color:#009926}.highlight .s1{color:#d14}.highlight .ss{color:#990073}.highlight .bp{color:#999}.highlight .vc{color:#008080}.highlight .vg{color:#008080}.highlight .vi{color:#008080}.highlight .il{color:#099}.highlight .gc{color:#999;background-color:#eaf2f5}.type-csharp .highlight .k{color:#00F}.type-csharp .highlight .kt{color:#00F}.type-csharp .highlight .nf{color:#000;font-weight:normal}.type-csharp .highlight .nc{color:#2b91af}.type-csharp .highlight .nn{color:#000}.type-csharp .highlight .s{color:#a31515}.type-csharp .highlight .sc{color:#a31515}
	</style>
</head>
<body>
<div id="wrapper">
#{response.body}
</div>
</body>
</html>
ENDOUTPUT
	if clipboard_output
		%x{echo #{html}|pbcopy}
		puts "Result in clipboard"
	else
		puts html
	end
else
	puts "Error #{response.code}"
end

ruby 测试

测试

test.rb
require "gem"
require_relative "hello"

string = "base16"
symbol = :base16
fixnum = 0
float  = 0.00
array  = Array.new
array  = ['chris', 85]
hash   = {"test" => "test"}
regexp = /[abc]/

# This is a comment

class Person

  attr_accessor :name

  def initialize(attributes)
    @name = attributes[:name]
  end

  def self.greet
    "hello"
  end
end

person1 = Person.new(:name => "Chris")

print Person::greet, " ", person1.name, "\n"
puts "another #{Person::greet} #{person1.name}"

ruby Поисксистемврецепте

Поисксистемврецепте

gistfile1.rb
# Находим апи ордер

Twiket::Network.search(system: 'api:order')

# Находим все апи кроме stats

Twiket::Network.search(system: 'api:* AND NOT api:stats')

# Из кода выше ты можешь увидить, что search может использовать простейший solr синтакс, из операций поддерживаются
# (), OR, AND, NOT 

ruby twiket搜索海岸墙

twiket搜索海岸墙

gistfile1.rb
# Кусок роли api.rb

    "zone_hosts" => {
      "api" =>  {search: 'twiket', system: 'api:*'},
      "webf" => {search: 'twiket', system: 'webfront:*'},
    }