diff --git a/vendor/bundle/ruby/2.0.0/bin/dotenv b/vendor/bundle/ruby/2.0.0/bin/dotenv deleted file mode 100755 index df8972c..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/dotenv +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'dotenv' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'dotenv', version -load Gem.bin_path('dotenv', 'dotenv', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/foreman b/vendor/bundle/ruby/2.0.0/bin/foreman deleted file mode 100755 index d063a4e..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/foreman +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'foreman' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'foreman', version -load Gem.bin_path('foreman', 'foreman', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/htmldiff b/vendor/bundle/ruby/2.0.0/bin/htmldiff deleted file mode 100755 index bdabb37..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/htmldiff +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/sh -'exec' "ruby" '-x' "$0" "$@" -#!/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -# -# This file was generated by RubyGems. -# -# The application 'diff-lcs' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'diff-lcs', version -load Gem.bin_path('diff-lcs', 'htmldiff', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/ldiff b/vendor/bundle/ruby/2.0.0/bin/ldiff deleted file mode 100755 index 28eeb45..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/ldiff +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/sh -'exec' "ruby" '-x' "$0" "$@" -#!/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -# -# This file was generated by RubyGems. -# -# The application 'diff-lcs' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'diff-lcs', version -load Gem.bin_path('diff-lcs', 'ldiff', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/rackup b/vendor/bundle/ruby/2.0.0/bin/rackup deleted file mode 100755 index 416d30a..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/rackup +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'rack' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'rack', version -load Gem.bin_path('rack', 'rackup', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/rspec b/vendor/bundle/ruby/2.0.0/bin/rspec deleted file mode 100755 index 1df29e9..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/rspec +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'rspec-core' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'rspec-core', version -load Gem.bin_path('rspec-core', 'rspec', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/thor b/vendor/bundle/ruby/2.0.0/bin/thor deleted file mode 100755 index 2533f7b..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/thor +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'thor' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'thor', version -load Gem.bin_path('thor', 'thor', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/tilt b/vendor/bundle/ruby/2.0.0/bin/tilt deleted file mode 100755 index cba5196..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/tilt +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'tilt' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'tilt', version -load Gem.bin_path('tilt', 'tilt', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/unicorn b/vendor/bundle/ruby/2.0.0/bin/unicorn deleted file mode 100755 index 5669e5e..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/unicorn +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'unicorn' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'unicorn', version -load Gem.bin_path('unicorn', 'unicorn', version) diff --git a/vendor/bundle/ruby/2.0.0/bin/unicorn_rails b/vendor/bundle/ruby/2.0.0/bin/unicorn_rails deleted file mode 100755 index 7d19340..0000000 --- a/vendor/bundle/ruby/2.0.0/bin/unicorn_rails +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env ruby -# -# This file was generated by RubyGems. -# -# The application 'unicorn' is installed as part of a gem, and -# this file is here to facilitate running it. -# - -require 'rubygems' - -version = ">= 0" - -if ARGV.first - str = ARGV.first - str = str.dup.force_encoding("BINARY") if str.respond_to? :force_encoding - if str =~ /\A_(.*)_\z/ and Gem::Version.correct?($1) then - version = $1 - ARGV.shift - end -end - -gem 'unicorn', version -load Gem.bin_path('unicorn', 'unicorn_rails', version) diff --git a/vendor/bundle/ruby/2.0.0/build_info/diff-lcs-1.2.5.info b/vendor/bundle/ruby/2.0.0/build_info/diff-lcs-1.2.5.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/diff-lcs-1.2.5.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/dotenv-0.11.1.info b/vendor/bundle/ruby/2.0.0/build_info/dotenv-0.11.1.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/dotenv-0.11.1.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/dotenv-deployment-0.0.2.info b/vendor/bundle/ruby/2.0.0/build_info/dotenv-deployment-0.0.2.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/dotenv-deployment-0.0.2.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/foreman-0.74.0.info b/vendor/bundle/ruby/2.0.0/build_info/foreman-0.74.0.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/foreman-0.74.0.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/kgio-2.9.2.info b/vendor/bundle/ruby/2.0.0/build_info/kgio-2.9.2.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/kgio-2.9.2.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/rack-1.5.2.info b/vendor/bundle/ruby/2.0.0/build_info/rack-1.5.2.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/rack-1.5.2.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/rack-protection-1.5.3.info b/vendor/bundle/ruby/2.0.0/build_info/rack-protection-1.5.3.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/rack-protection-1.5.3.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/raindrops-0.13.0.info b/vendor/bundle/ruby/2.0.0/build_info/raindrops-0.13.0.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/raindrops-0.13.0.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/rspec-3.0.0.info b/vendor/bundle/ruby/2.0.0/build_info/rspec-3.0.0.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/rspec-3.0.0.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/rspec-core-3.0.3.info b/vendor/bundle/ruby/2.0.0/build_info/rspec-core-3.0.3.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/rspec-core-3.0.3.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/rspec-expectations-3.0.3.info b/vendor/bundle/ruby/2.0.0/build_info/rspec-expectations-3.0.3.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/rspec-expectations-3.0.3.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/rspec-mocks-3.0.3.info b/vendor/bundle/ruby/2.0.0/build_info/rspec-mocks-3.0.3.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/rspec-mocks-3.0.3.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/rspec-support-3.0.3.info b/vendor/bundle/ruby/2.0.0/build_info/rspec-support-3.0.3.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/rspec-support-3.0.3.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/sinatra-1.4.5.info b/vendor/bundle/ruby/2.0.0/build_info/sinatra-1.4.5.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/sinatra-1.4.5.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/thor-0.19.1.info b/vendor/bundle/ruby/2.0.0/build_info/thor-0.19.1.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/thor-0.19.1.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/tilt-1.4.1.info b/vendor/bundle/ruby/2.0.0/build_info/tilt-1.4.1.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/tilt-1.4.1.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/build_info/unicorn-4.8.3.info b/vendor/bundle/ruby/2.0.0/build_info/unicorn-4.8.3.info deleted file mode 100644 index 8b13789..0000000 --- a/vendor/bundle/ruby/2.0.0/build_info/unicorn-4.8.3.info +++ /dev/null @@ -1 +0,0 @@ - diff --git a/vendor/bundle/ruby/2.0.0/cache/diff-lcs-1.2.5.gem b/vendor/bundle/ruby/2.0.0/cache/diff-lcs-1.2.5.gem deleted file mode 100644 index e4436cc..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/diff-lcs-1.2.5.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/dotenv-0.11.1.gem b/vendor/bundle/ruby/2.0.0/cache/dotenv-0.11.1.gem deleted file mode 100644 index 41a74fa..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/dotenv-0.11.1.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/dotenv-deployment-0.0.2.gem b/vendor/bundle/ruby/2.0.0/cache/dotenv-deployment-0.0.2.gem deleted file mode 100644 index 30876f9..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/dotenv-deployment-0.0.2.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/foreman-0.74.0.gem b/vendor/bundle/ruby/2.0.0/cache/foreman-0.74.0.gem deleted file mode 100644 index 40c013d..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/foreman-0.74.0.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/kgio-2.9.2.gem b/vendor/bundle/ruby/2.0.0/cache/kgio-2.9.2.gem deleted file mode 100644 index cc45547..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/kgio-2.9.2.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/rack-1.5.2.gem b/vendor/bundle/ruby/2.0.0/cache/rack-1.5.2.gem deleted file mode 100644 index e1f7bfd..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/rack-1.5.2.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/rack-protection-1.5.3.gem b/vendor/bundle/ruby/2.0.0/cache/rack-protection-1.5.3.gem deleted file mode 100644 index 5a00e8e..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/rack-protection-1.5.3.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/raindrops-0.13.0.gem b/vendor/bundle/ruby/2.0.0/cache/raindrops-0.13.0.gem deleted file mode 100644 index 90e0e0d..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/raindrops-0.13.0.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/rspec-3.0.0.gem b/vendor/bundle/ruby/2.0.0/cache/rspec-3.0.0.gem deleted file mode 100644 index 28e57f8..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/rspec-3.0.0.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/rspec-core-3.0.3.gem b/vendor/bundle/ruby/2.0.0/cache/rspec-core-3.0.3.gem deleted file mode 100644 index 5ff86eb..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/rspec-core-3.0.3.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/rspec-expectations-3.0.3.gem b/vendor/bundle/ruby/2.0.0/cache/rspec-expectations-3.0.3.gem deleted file mode 100644 index 8238b74..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/rspec-expectations-3.0.3.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/rspec-mocks-3.0.3.gem b/vendor/bundle/ruby/2.0.0/cache/rspec-mocks-3.0.3.gem deleted file mode 100644 index 4d0dbd9..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/rspec-mocks-3.0.3.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/rspec-support-3.0.3.gem b/vendor/bundle/ruby/2.0.0/cache/rspec-support-3.0.3.gem deleted file mode 100644 index ec13f72..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/rspec-support-3.0.3.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/sinatra-1.4.5.gem b/vendor/bundle/ruby/2.0.0/cache/sinatra-1.4.5.gem deleted file mode 100644 index f8cdfe6..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/sinatra-1.4.5.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/thor-0.19.1.gem b/vendor/bundle/ruby/2.0.0/cache/thor-0.19.1.gem deleted file mode 100644 index 1ca502f..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/thor-0.19.1.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/tilt-1.4.1.gem b/vendor/bundle/ruby/2.0.0/cache/tilt-1.4.1.gem deleted file mode 100644 index 3ad79a9..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/tilt-1.4.1.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/cache/unicorn-4.8.3.gem b/vendor/bundle/ruby/2.0.0/cache/unicorn-4.8.3.gem deleted file mode 100644 index f06e285..0000000 Binary files a/vendor/bundle/ruby/2.0.0/cache/unicorn-4.8.3.gem and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/gem.build_complete b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/gem.build_complete deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/gem_make.out b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/gem_make.out deleted file mode 100644 index bac0708..0000000 --- a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/gem_make.out +++ /dev/null @@ -1,64 +0,0 @@ -/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -r ./siteconf20140814-69107-1n4i7bf.rb extconf.rb -checking for CLOCK_MONOTONIC in time.h... no -checking for CLOCK_MONOTONIC() in time.h... no -checking for clockid_t in time.h... no -checking for clock_gettime() in -lrt... no -checking for t_open() in -lnsl... no -checking for socket() in -lsocket... no -checking for poll() in poll.h... yes -checking for getaddrinfo() in sys/types.h,sys/socket.h,netdb.h... yes -checking for getnameinfo() in sys/types.h,sys/socket.h,netdb.h... yes -checking for struct sockaddr_storage in sys/types.h,sys/socket.h... yes -checking for accept4() in sys/socket.h... no -checking for sys/select.h... yes -checking for writev() in sys/uio.h... yes -checking for ruby/io.h... yes -checking for rb_io_t.fd in ruby.h,ruby/io.h... yes -checking for rb_io_t.mode in ruby.h,ruby/io.h... yes -checking for rb_io_t.pathv in ruby.h,ruby/io.h... yes -checking for struct RFile in ruby.h,ruby/io.h... yes -checking size of struct RFile in ruby.h,ruby/io.h... 24 -checking for struct RObject... yes -checking size of struct RObject... 40 -checking size of int... 4 -checking for rb_io_ascii8bit_binmode()... yes -checking for rb_update_max_fd()... yes -checking for rb_fd_fix_cloexec()... yes -checking for rb_cloexec_open()... yes -checking for ruby/thread.h... yes -checking for rb_thread_call_without_gvl() in ruby/thread.h... yes -checking for rb_thread_blocking_region()... yes -checking for rb_thread_io_blocking_region()... yes -checking for rb_str_set_len()... yes -checking for rb_time_interval()... yes -checking for rb_wait_for_single_fd()... yes -checking for rb_str_subseq()... yes -checking for rb_ary_subseq()... yes -creating Makefile - -make "DESTDIR=" clean - -make "DESTDIR=" -compiling accept.c -compiling autopush.c -compiling connect.c -compiling kgio_ext.c -compiling poll.c -poll.c:89:1: warning: control may reach end of non-void function [-Wreturn-type] -} -^ -1 warning generated. -poll.c:89:1: warning: control may reach end of non-void function [-Wreturn-type] -} -^ -1 warning generated. -compiling read.c -compiling tryopen.c -compiling wait.c -compiling write.c -compiling writev.c -linking shared-object kgio_ext.bundle - -make "DESTDIR=" install -/usr/bin/install -c -m 0755 kgio_ext.bundle ./.gem.20140814-69107-1tgvci4 -installing default kgio_ext libraries diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/kgio_ext.bundle b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/kgio_ext.bundle deleted file mode 100755 index 48342ab..0000000 Binary files a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/kgio_ext.bundle and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/mkmf.log b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/mkmf.log deleted file mode 100644 index 32174a5..0000000 --- a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/kgio-2.9.2/mkmf.log +++ /dev/null @@ -1,1065 +0,0 @@ -have_macro: checking for CLOCK_MONOTONIC in time.h... -------------------- no - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: int main(int argc, char **argv) -4: { -5: return 0; -6: } -/* end */ - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -conftest.c:6:3: error: -# error - ^ -conftest.c:7:1: error: expected identifier or '(' -|:/ === CLOCK_MONOTONIC undefined === /:| -^ -2 errors generated. -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: /*top*/ -5: #ifndef CLOCK_MONOTONIC -6: # error -7: |:/ === CLOCK_MONOTONIC undefined === /:| -8: #endif -/* end */ - --------------------- - -have_func: checking for CLOCK_MONOTONIC() in time.h... -------------------- no - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:7:57: error: use of undeclared identifier 'CLOCK_MONOTONIC' -int t(void) { void ((*volatile p)()); p = (void ((*)()))CLOCK_MONOTONIC; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))CLOCK_MONOTONIC; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:7:15: warning: implicit declaration of function 'CLOCK_MONOTONIC' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { CLOCK_MONOTONIC(); return 0; } - ^ -1 warning generated. -Undefined symbols for architecture x86_64: - "_CLOCK_MONOTONIC", referenced from: - _t in conftest-823ffb.o -ld: symbol(s) not found for architecture x86_64 -conftest.c:7:15: warning: implicit declaration of function 'CLOCK_MONOTONIC' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { CLOCK_MONOTONIC(); return 0; } - ^ -1 warning generated. -clang: error: linker command failed with exit code 1 (use -v to see invocation) -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { CLOCK_MONOTONIC(); return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_type: checking for clockid_t in time.h... -------------------- no - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -conftest.c:6:9: error: unknown type name 'clockid_t'; did you mean 'clock_t'? -typedef clockid_t conftest_type; - ^~~~~~~~~ - clock_t -/usr/include/sys/_types/_clock_t.h:30:33: note: 'clock_t' declared here -typedef __darwin_clock_t clock_t; - ^ -1 error generated. -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: -5: /*top*/ -6: typedef clockid_t conftest_type; -7: int conftestval[sizeof(conftest_type)?1:-1]; -/* end */ - --------------------- - -have_library: checking for clock_gettime() in -lrt... -------------------- no - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lrt -lpthread -ldl -lobjc " -conftest.c:7:57: error: use of undeclared identifier 'clock_gettime' -int t(void) { void ((*volatile p)()); p = (void ((*)()))clock_gettime; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))clock_gettime; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lrt -lpthread -ldl -lobjc " -conftest.c:7:15: warning: implicit declaration of function 'clock_gettime' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { clock_gettime(); return 0; } - ^ -1 warning generated. -ld: library not found for -lrt -conftest.c:7:15: warning: implicit declaration of function 'clock_gettime' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { clock_gettime(); return 0; } - ^ -1 warning generated. -clang: error: linker command failed with exit code 1 (use -v to see invocation) -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { clock_gettime(); return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_library: checking for t_open() in -lnsl... -------------------- no - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lnsl -lpthread -ldl -lobjc " -conftest.c:5:57: error: use of undeclared identifier 't_open' -int t(void) { void ((*volatile p)()); p = (void ((*)()))t_open; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))t_open; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lnsl -lpthread -ldl -lobjc " -conftest.c:5:15: warning: implicit declaration of function 't_open' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { t_open(); return 0; } - ^ -1 warning generated. -ld: library not found for -lnsl -conftest.c:5:15: warning: implicit declaration of function 't_open' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { t_open(); return 0; } - ^ -1 warning generated. -clang: error: linker command failed with exit code 1 (use -v to see invocation) -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { t_open(); return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_library: checking for socket() in -lsocket... -------------------- no - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lsocket -lpthread -ldl -lobjc " -conftest.c:5:57: error: use of undeclared identifier 'socket' -int t(void) { void ((*volatile p)()); p = (void ((*)()))socket; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))socket; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lsocket -lpthread -ldl -lobjc " -conftest.c:5:15: warning: implicit declaration of function 'socket' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { socket(); return 0; } - ^ -1 warning generated. -ld: library not found for -lsocket -conftest.c:5:15: warning: implicit declaration of function 'socket' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { socket(); return 0; } - ^ -1 warning generated. -clang: error: linker command failed with exit code 1 (use -v to see invocation) -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { socket(); return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for poll() in poll.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))poll; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_func: checking for getaddrinfo() in sys/types.h,sys/socket.h,netdb.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: #include - 5: #include - 6: - 7: /*top*/ - 8: extern int t(void); - 9: int t(void) { void ((*volatile p)()); p = (void ((*)()))getaddrinfo; return 0; } -10: int main(int argc, char **argv) -11: { -12: if (argc > 1000000) { -13: printf("%p", &t); -14: } -15: -16: return 0; -17: } -/* end */ - --------------------- - -have_func: checking for getnameinfo() in sys/types.h,sys/socket.h,netdb.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: #include - 5: #include - 6: - 7: /*top*/ - 8: extern int t(void); - 9: int t(void) { void ((*volatile p)()); p = (void ((*)()))getnameinfo; return 0; } -10: int main(int argc, char **argv) -11: { -12: if (argc > 1000000) { -13: printf("%p", &t); -14: } -15: -16: return 0; -17: } -/* end */ - --------------------- - -have_type: checking for struct sockaddr_storage in sys/types.h,sys/socket.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: #include -5: -6: /*top*/ -7: typedef struct sockaddr_storage conftest_type; -8: int conftestval[sizeof(conftest_type)?1:-1]; -/* end */ - --------------------- - -have_func: checking for accept4() in sys/socket.h... -------------------- no - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:7:57: error: use of undeclared identifier 'accept4' -int t(void) { void ((*volatile p)()); p = (void ((*)()))accept4; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))accept4; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:7:15: warning: implicit declaration of function 'accept4' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { accept4(); return 0; } - ^ -1 warning generated. -Undefined symbols for architecture x86_64: - "_accept4", referenced from: - _t in conftest-4adf12.o -ld: symbol(s) not found for architecture x86_64 -conftest.c:7:15: warning: implicit declaration of function 'accept4' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { accept4(); return 0; } - ^ -1 warning generated. -clang: error: linker command failed with exit code 1 (use -v to see invocation) -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { accept4(); return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_header: checking for sys/select.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -/* end */ - --------------------- - -have_func: checking for writev() in sys/uio.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))writev; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_header: checking for ruby/io.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -/* end */ - --------------------- - -have_struct_member: checking for rb_io_t.fd in ruby.h,ruby/io.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: #include - 5: - 6: /*top*/ - 7: int s = (char *)&((rb_io_t*)0)->fd - (char *)0; - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &s); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_struct_member: checking for rb_io_t.mode in ruby.h,ruby/io.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: #include - 5: - 6: /*top*/ - 7: int s = (char *)&((rb_io_t*)0)->mode - (char *)0; - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &s); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_struct_member: checking for rb_io_t.pathv in ruby.h,ruby/io.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: #include - 5: - 6: /*top*/ - 7: int s = (char *)&((rb_io_t*)0)->pathv - (char *)0; - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &s); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_type: checking for struct RFile in ruby.h,ruby/io.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: #include -5: -6: /*top*/ -7: typedef struct RFile conftest_type; -8: int conftestval[sizeof(conftest_type)?1:-1]; -/* end */ - --------------------- - -check_sizeof: checking size of struct RFile in ruby.h,ruby/io.h... -------------------- 24 - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -conftest.c:9:20: error: 'conftest_const' declared as an array with a negative size -int conftest_const[(sizeof((*rbcv_ptr_)) < 0) ? 1 : -1]; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -1 error generated. -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: #include -5: typedef struct RFile rbcv_typedef_; -6: static rbcv_typedef_ *rbcv_ptr_; -7: -8: /*top*/ -9: int conftest_const[(sizeof((*rbcv_ptr_)) < 0) ? 1 : -1]; -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: #include - 5: typedef struct RFile rbcv_typedef_; - 6: static rbcv_typedef_ *rbcv_ptr_; - 7: - 8: #include - 9: /*top*/ -10: typedef unsigned -11: #ifdef PRI_LL_PREFIX -12: #define PRI_CONFTEST_PREFIX PRI_LL_PREFIX -13: LONG_LONG -14: #else -15: #define PRI_CONFTEST_PREFIX "l" -16: long -17: #endif -18: conftest_type; -19: conftest_type conftest_const = (conftest_type)(sizeof((*rbcv_ptr_))); -20: int main() {printf("%"PRI_CONFTEST_PREFIX"u\n", conftest_const); return 0;} -/* end */ - -./conftest | --------------------- - -have_type: checking for struct RObject... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: /*top*/ -4: typedef struct RObject conftest_type; -5: int conftestval[sizeof(conftest_type)?1:-1]; -/* end */ - --------------------- - -check_sizeof: checking size of struct RObject... -------------------- 40 - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -conftest.c:7:20: error: 'conftest_const' declared as an array with a negative size -int conftest_const[(sizeof((*rbcv_ptr_)) < 0) ? 1 : -1]; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -1 error generated. -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: typedef struct RObject rbcv_typedef_; -4: static rbcv_typedef_ *rbcv_ptr_; -5: -6: /*top*/ -7: int conftest_const[(sizeof((*rbcv_ptr_)) < 0) ? 1 : -1]; -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: typedef struct RObject rbcv_typedef_; - 4: static rbcv_typedef_ *rbcv_ptr_; - 5: - 6: #include - 7: /*top*/ - 8: typedef unsigned - 9: #ifdef PRI_LL_PREFIX -10: #define PRI_CONFTEST_PREFIX PRI_LL_PREFIX -11: LONG_LONG -12: #else -13: #define PRI_CONFTEST_PREFIX "l" -14: long -15: #endif -16: conftest_type; -17: conftest_type conftest_const = (conftest_type)(sizeof((*rbcv_ptr_))); -18: int main() {printf("%"PRI_CONFTEST_PREFIX"u\n", conftest_const); return 0;} -/* end */ - -./conftest | --------------------- - -check_sizeof: checking size of int... -------------------- 4 - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -conftest.c:7:20: error: 'conftest_const' declared as an array with a negative size -int conftest_const[(sizeof((*rbcv_ptr_)) < 0) ? 1 : -1]; - ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -1 error generated. -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: typedef int rbcv_typedef_; -4: static rbcv_typedef_ *rbcv_ptr_; -5: -6: /*top*/ -7: int conftest_const[(sizeof((*rbcv_ptr_)) < 0) ? 1 : -1]; -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: typedef int rbcv_typedef_; - 4: static rbcv_typedef_ *rbcv_ptr_; - 5: - 6: #include - 7: /*top*/ - 8: typedef unsigned - 9: #ifdef PRI_LL_PREFIX -10: #define PRI_CONFTEST_PREFIX PRI_LL_PREFIX -11: LONG_LONG -12: #else -13: #define PRI_CONFTEST_PREFIX "l" -14: long -15: #endif -16: conftest_type; -17: conftest_type conftest_const = (conftest_type)(sizeof((*rbcv_ptr_))); -18: int main() {printf("%"PRI_CONFTEST_PREFIX"u\n", conftest_const); return 0;} -/* end */ - -./conftest | --------------------- - -have_func: checking for rb_io_ascii8bit_binmode()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_io_ascii8bit_binmode; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_update_max_fd()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_update_max_fd; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_fd_fix_cloexec()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_fd_fix_cloexec; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_cloexec_open()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_cloexec_open; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_header: checking for ruby/thread.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -/* end */ - --------------------- - -have_func: checking for rb_thread_call_without_gvl() in ruby/thread.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_thread_call_without_gvl; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_func: checking for rb_thread_blocking_region()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_thread_blocking_region; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_thread_io_blocking_region()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:5:57: error: use of undeclared identifier 'rb_thread_io_blocking_region' -int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_thread_io_blocking_region; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_thread_io_blocking_region; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:5:15: warning: implicit declaration of function 'rb_thread_io_blocking_region' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { rb_thread_io_blocking_region(); return 0; } - ^ -1 warning generated. -conftest.c:5:15: warning: implicit declaration of function 'rb_thread_io_blocking_region' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { rb_thread_io_blocking_region(); return 0; } - ^ -1 warning generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { rb_thread_io_blocking_region(); return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_str_set_len()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_str_set_len; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_time_interval()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_time_interval; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_wait_for_single_fd()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:5:57: error: use of undeclared identifier 'rb_wait_for_single_fd' -int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_wait_for_single_fd; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_wait_for_single_fd; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:5:15: warning: implicit declaration of function 'rb_wait_for_single_fd' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { rb_wait_for_single_fd(); return 0; } - ^ -1 warning generated. -conftest.c:5:15: warning: implicit declaration of function 'rb_wait_for_single_fd' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { rb_wait_for_single_fd(); return 0; } - ^ -1 warning generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { rb_wait_for_single_fd(); return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_str_subseq()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_str_subseq; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_ary_subseq()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -DPOSIX_C_SOURCE=1-D_POSIX_C_SOURCE=200112L -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_ary_subseq; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/gem.build_complete b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/gem.build_complete deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/gem_make.out b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/gem_make.out deleted file mode 100644 index ff5966b..0000000 --- a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/gem_make.out +++ /dev/null @@ -1,21 +0,0 @@ -/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -r ./siteconf20140814-69107-1jcc13a.rb extconf.rb -checking for mmap() in sys/mman.h... yes -checking for munmap() in sys/mman.h... yes -checking for mremap() in sys/mman.h... no -checking for getpagesize() in unistd.h... yes -checking for rb_thread_blocking_region()... yes -checking for rb_thread_io_blocking_region()... yes -checking for GCC 4+ atomic builtins... yes -creating Makefile - -make "DESTDIR=" clean - -make "DESTDIR=" -compiling linux_inet_diag.c -compiling linux_tcp_info.c -compiling raindrops.c -linking shared-object raindrops_ext.bundle - -make "DESTDIR=" install -/usr/bin/install -c -m 0755 raindrops_ext.bundle ./.gem.20140814-69107-tuc3mm -installing default raindrops_ext libraries diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/mkmf.log b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/mkmf.log deleted file mode 100644 index d6db7fd..0000000 --- a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/mkmf.log +++ /dev/null @@ -1,238 +0,0 @@ -have_func: checking for mmap() in sys/mman.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: int main(int argc, char **argv) -4: { -5: return 0; -6: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))mmap; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_func: checking for munmap() in sys/mman.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))munmap; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_func: checking for mremap() in sys/mman.h... -------------------- no - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:7:57: error: use of undeclared identifier 'mremap' -int t(void) { void ((*volatile p)()); p = (void ((*)()))mremap; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))mremap; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:7:15: warning: implicit declaration of function 'mremap' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { mremap(); return 0; } - ^ -1 warning generated. -Undefined symbols for architecture x86_64: - "_mremap", referenced from: - _t in conftest-bc982c.o -ld: symbol(s) not found for architecture x86_64 -conftest.c:7:15: warning: implicit declaration of function 'mremap' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { mremap(); return 0; } - ^ -1 warning generated. -clang: error: linker command failed with exit code 1 (use -v to see invocation) -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { mremap(); return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_func: checking for getpagesize() in unistd.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -D_BSD_SOURCE -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))getpagesize; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_func: checking for rb_thread_blocking_region()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -D_BSD_SOURCE -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_thread_blocking_region; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -have_func: checking for rb_thread_io_blocking_region()... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -D_BSD_SOURCE -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:5:57: error: use of undeclared identifier 'rb_thread_io_blocking_region' -int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_thread_io_blocking_region; return 0; } - ^ -1 error generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_thread_io_blocking_region; return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -D_BSD_SOURCE -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -conftest.c:5:15: warning: implicit declaration of function 'rb_thread_io_blocking_region' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { rb_thread_io_blocking_region(); return 0; } - ^ -1 warning generated. -conftest.c:5:15: warning: implicit declaration of function 'rb_thread_io_blocking_region' is invalid in C99 [-Wimplicit-function-declaration] -int t(void) { rb_thread_io_blocking_region(); return 0; } - ^ -1 warning generated. -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: /*top*/ - 4: extern int t(void); - 5: int t(void) { rb_thread_io_blocking_region(); return 0; } - 6: int main(int argc, char **argv) - 7: { - 8: if (argc > 1000000) { - 9: printf("%p", &t); -10: } -11: -12: return 0; -13: } -/* end */ - --------------------- - -checking for GCC 4+ atomic builtins... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -D_GNU_SOURCE -D_BSD_SOURCE -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: int main(int argc, char * const argv[]) { - 4: unsigned long i = 0; - 5: __sync_lock_test_and_set(&i, 0); - 6: __sync_lock_test_and_set(&i, 1); - 7: __sync_bool_compare_and_swap(&i, 0, 1); - 8: __sync_add_and_fetch(&i, argc); - 9: __sync_sub_and_fetch(&i, argc); -10: return 0; -11: } -/* end */ - --------------------- - diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/raindrops_ext.bundle b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/raindrops_ext.bundle deleted file mode 100755 index 014de41..0000000 Binary files a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/raindrops-0.13.0/raindrops_ext.bundle and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/gem.build_complete b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/gem.build_complete deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/gem_make.out b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/gem_make.out deleted file mode 100644 index d9e0e0b..0000000 --- a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/gem_make.out +++ /dev/null @@ -1,18 +0,0 @@ -/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby -r ./siteconf20140814-69107-18tjagu.rb extconf.rb -checking for SIZEOF_OFF_T in ruby.h... yes -checking for SIZEOF_SIZE_T in ruby.h... yes -checking for SIZEOF_LONG in ruby.h... yes -checking for rb_str_set_len() in ruby.h... yes -checking for gmtime_r() in time.h... yes -creating Makefile - -make "DESTDIR=" clean - -make "DESTDIR=" -compiling httpdate.c -compiling unicorn_http.c -linking shared-object unicorn_http.bundle - -make "DESTDIR=" install -/usr/bin/install -c -m 0755 unicorn_http.bundle ./.gem.20140814-69107-q7nwpv -installing default unicorn_http libraries diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/mkmf.log b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/mkmf.log deleted file mode 100644 index cc92df1..0000000 --- a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/mkmf.log +++ /dev/null @@ -1,110 +0,0 @@ -have_macro: checking for SIZEOF_OFF_T in ruby.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: int main(int argc, char **argv) -4: { -5: return 0; -6: } -/* end */ - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: /*top*/ -5: #ifndef SIZEOF_OFF_T -6: # error -7: |:/ === SIZEOF_OFF_T undefined === /:| -8: #endif -/* end */ - --------------------- - -have_macro: checking for SIZEOF_SIZE_T in ruby.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: /*top*/ -5: #ifndef SIZEOF_SIZE_T -6: # error -7: |:/ === SIZEOF_SIZE_T undefined === /:| -8: #endif -/* end */ - --------------------- - -have_macro: checking for SIZEOF_LONG in ruby.h... -------------------- yes - -"xcrun clang -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe -arch x86_64 -arch i386 -c conftest.c" -checked program was: -/* begin */ -1: #include "ruby.h" -2: -3: #include -4: /*top*/ -5: #ifndef SIZEOF_LONG -6: # error -7: |:/ === SIZEOF_LONG undefined === /:| -8: #endif -/* end */ - --------------------- - -have_func: checking for rb_str_set_len() in ruby.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))rb_str_set_len; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - -have_func: checking for gmtime_r() in time.h... -------------------- yes - -"xcrun clang -o conftest -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/universal-darwin13 -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0/ruby/backward -I/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/include/ruby-2.0.0 -I. -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE -D_DARWIN_UNLIMITED_SELECT -D_REENTRANT -g -Os -pipe conftest.c -L. -L/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib -L. -L/usr/local/lib -arch x86_64 -arch i386 -lruby.2.0.0 -lpthread -ldl -lobjc " -checked program was: -/* begin */ - 1: #include "ruby.h" - 2: - 3: #include - 4: - 5: /*top*/ - 6: extern int t(void); - 7: int t(void) { void ((*volatile p)()); p = (void ((*)()))gmtime_r; return 0; } - 8: int main(int argc, char **argv) - 9: { -10: if (argc > 1000000) { -11: printf("%p", &t); -12: } -13: -14: return 0; -15: } -/* end */ - --------------------- - diff --git a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/unicorn_http.bundle b/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/unicorn_http.bundle deleted file mode 100755 index 4d1f914..0000000 Binary files a/vendor/bundle/ruby/2.0.0/extensions/universal-darwin-13/2.0.0/unicorn-4.8.3/unicorn_http.bundle and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.autotest b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.autotest deleted file mode 100644 index 1236395..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.autotest +++ /dev/null @@ -1,3 +0,0 @@ -require 'rubygems' - -# vim: syntax=ruby diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.gemtest b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.gemtest deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.hoerc b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.hoerc deleted file mode 100644 index 0a13543..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.hoerc +++ /dev/null @@ -1,2 +0,0 @@ ---- -exclude: !ruby/regexp /(tmp|swp)$|CVS|TAGS|\.(svn|git|hg|DS_Store|idea)|Gemfile\.lock|research\/|\.gemspec$/ diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.rspec b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.rspec deleted file mode 100644 index 7438fbe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.rspec +++ /dev/null @@ -1,2 +0,0 @@ ---colour ---format documentation diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.travis.yml b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.travis.yml deleted file mode 100644 index 903cddf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/.travis.yml +++ /dev/null @@ -1,22 +0,0 @@ ---- -after_script: -- rake travis:after -t -before_script: -- gem install hoe-travis --no-rdoc --no-ri -- rake travis:before -t -language: ruby -notifications: - email: true -rvm: - - 2.0.0 - - 1.9.3 - - 1.9.2 - - ruby-head - - 1.8.7 - - jruby-19mode - - jruby-head - - jruby-18mode - - rbx-19mode - - rbx-18mode - - ree -script: rake travis diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Contributing.rdoc b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Contributing.rdoc deleted file mode 100644 index a0f37de..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Contributing.rdoc +++ /dev/null @@ -1,64 +0,0 @@ -== Contributing - -I value any contribution to Diff::LCS you can provide: a bug report, a feature -request, or code contributions. - -Code contributions to Diff::LCS are especially welcomeencouraged. -Because Diff::LCS is a complex codebase, there are a few guidelines: - -* Changes will not be accepted without tests. -* The test suite is written with RSpec.‡ -* Match my coding style. -* Use a thoughtfully-named topic branch that contains your change. Rebase your - commits into logical chunks as necessary. -* Use {quality commit messages}[http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html]. -* Do not change the version number; when your patch is accepted and a release - is made, the version will be updated at that point. -* Submit a GitHub pull request with your changes. -* New features require new documentation. - -=== Test Dependencies - -To run the test suite, you will need to install the development dependencies -for Diff::LCS. If you have Bundler, you can accomplish this easily: - - $ bundle install - -Diff::LCS uses Ryan Davis’s excellent {Hoe}[https://github.com/seattlerb/hoe] -to manage the release process, and it adds a number of rake tasks. You will -mostly be interested in: - - $ rake - -which runs the tests the same way that: - - $ rake spec - $ rake test - $ rake travis - -will do. - -=== Workflow - -Here's the most direct way to get your work merged into the project: - -* Fork the project. -* Clone down your fork (+git clone git://github.com//diff-lcs.git+). -* Create a topic branch to contain your change (+git checkout -b my\_awesome\_feature+). -* Hack away, add tests. Not necessarily in that order. -* Make sure everything still passes by running `rake`. -* If necessary, rebase your commits into logical chunks, without errors. -* Push the branch up (+git push origin my\_awesome\_feature+). -* Create a pull request against halostatue/diff-lcs and describe what your - change does and the why you think it should be merged. - -=== Contributors - -* Austin Ziegler created Diff::LCS. - -Thanks to everyone else who has contributed to Diff::LCS: - -* Kenichi Kamiya -* Michael Granger -* Vít Ondruch -* Jon Rowe diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Gemfile b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Gemfile deleted file mode 100644 index 174f15f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Gemfile +++ /dev/null @@ -1,20 +0,0 @@ -# -*- ruby -*- - -# DO NOT EDIT THIS FILE. Instead, edit Rakefile, and run `rake bundler:gemfile`. - -source "https://rubygems.org/" - - -gem "rubyforge", ">=2.0.4", :group => [:development, :test] -gem "rdoc", "~>4.0", :group => [:development, :test] -gem "hoe-bundler", "~>1.2", :group => [:development, :test] -gem "hoe-doofus", "~>1.0", :group => [:development, :test] -gem "hoe-gemspec2", "~>1.1", :group => [:development, :test] -gem "hoe-git", "~>1.5", :group => [:development, :test] -gem "hoe-rubygems", "~>1.0", :group => [:development, :test] -gem "hoe-travis", "~>1.2", :group => [:development, :test] -gem "rake", "~>10.0", :group => [:development, :test] -gem "rspec", "~>2.0", :group => [:development, :test] -gem "hoe", "~>3.7", :group => [:development, :test] - -# vim: syntax=ruby diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/History.rdoc b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/History.rdoc deleted file mode 100644 index 69e5ddc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/History.rdoc +++ /dev/null @@ -1,152 +0,0 @@ -== 1.2.5 / 2013-11-08 - -* Bugs fixed: - * Comparing arrays flattened them too far, especially with Diff::LCS.sdiff. - https://github.com/halostatue/diff-lcs/pull/23 - -== 1.2.4 / 2013-04-20 - -* Bugs fixed: - * A bug was introduced after 1.1.3 when pruning common sequences at the start - of comparison. Paul Kunysch (@pck) fixed this in pull request 18. Thanks! - https://github.com/halostatue/diff-lcs/pull/18 -* The Rubinius (1.9 mode) bug in rubinius/rubinius#2268 has been fixed by the - Rubinius team two days after it was filed. Thanks for fixing this so quickly! - https://github.com/rubinius/rubinius/issues/2268 -* Switching to Raggi's hoe-gemspec2 for gemspec generation. - -== 1.2.3 / 2013-04-11 - -* Bugs Fixed: - * The new encoding detection for diff output generation (added in 1.2.2) - introduced a bug if the left side of the comparison was the empty set. - Originally found in rspec/rspec-expectations#238 and - rspec/rspec-expectations#239. Jon Rowe developed a reasonable heuristic - (left side, right side, empty string literal) to avoid this bug. - https://github.com/rspec/rspec-expectations/pull/238 - https://github.com/rspec/rspec-expectations/pull/239 -* There is a known issue with Rubinius in 1.9 mode reported in - rubinius/rubinius#2268 and demonstrated in the Travis CI builds. For all - other tested platforms, diff-lcs is considered stable. As soon as a suitably - small test-case can be created for the Rubinius team to examine, this will be - added to the Rubinius issue around this. - https://github.com/rubinius/rubinius/issues/2268 - https://travis-ci.org/halostatue/diff-lcs/jobs/6241195 - -== 1.2.2 / 2013-03-30 - -* Bugs Fixed: - * Diff::LCS::Hunk could not properly generate a difference for comparison - sets that are not US-ASCII-compatible because of the use of literal regular - expressions and strings. Jon Rowe (JonRowe) found this in - rspec/rspec-expectations#219 and provided a first pass implementation in - diff-lcs#15. I've reworked it because of test failures in Rubinius when - running in Ruby 1.9 mode. This coerces the added values to the encoding of - the old dataset (as determined by the first piece of the old dataset). - https://github.com/rspec/rspec-expectations/issues/219 - https://github.com/halostatue/diff-lcs/pull/15 -* Adding Travis CI testing for Ruby 2.0. - -== 1.2.1 / 2013-02-09 - -* Bugs Fixed: - * As seen in https://github.com/rspec/rspec-expectations/pull/200, the - release of Diff::LCS 1.2 introduced an unnecessary public API change to - Diff::LCS::Hunk (see the change at - https://github.com/rspec/rspec-expectations/commit/3d6fc82c for details). - The new method name (and behaviour) is more correct, but I should not have - renamed the function or should have at least provided an alias. This - release restores Diff::LCS::Hunk#unshift as an alias to - #merge. Note that the old #unshift behaviour was incorrect and will not be - restored. - -== 1.2.0 / 2013-01-21 -* Minor Enhancements: - * Added special case handling for Diff::LCS.patch so that it handles patches - that are empty or contain no changes. - * Added two new methods (#patch\_me and #unpatch\_me) to the includable - module. -* Bugs Fixed: - * Fixed issue #1 patch direction detection. - https://github.com/halostatue/diff-lcs/issues/1 - * Resolved issue #2 by handling string[string.size, 1] properly (it returns - "" not nil). https://github.com/halostatue/diff-lcs/issues/2 - * Michael Granger (ged) fixed an implementation error in Diff::LCS::Change - and added specs in pull request #8. Thanks! - https://github.com/halostatue/diff-lcs/issues/8 - * Made the code auto-testable. - * Vít Ondruch (voxik) provided the latest version of the GPL2 license file in - pull request #10. Thanks! https://github.com/halostatue/diff-lcs/issues/10 - * Fixed a documentation issue with the includable versions of #patch! and - #unpatch! where they implied that they would replace the original value. - Given that Diff::LCS.patch always returns a copy, the documentation was - incorrect and has been corrected. To provide the behaviour that was - originally documented, two new methods were added to provide this - behaviour. Found by scooter-dangle in issue #12. Thanks! - https://github.com/halostatue/diff-lcs/issues/12 -* Code Style Changes: - * Removed trailing spaces. - * Calling class methods using '.' instead of '::'. - * Vít Ondruch (voxik) removed unnecessary shebangs in pull request #9. - Thanks! https://github.com/halostatue/diff-lcs/issues/9 - * Kenichi Kamiya (kachick) removed some warnings of an unused variable in - lucky pull request #13. https://github.com/halostatue/diff-lcs/issues/13 - Thanks! - * Embarked on a major refactoring to make the files a little more manageable - and understand the code on a deeper level. - * Adding to http://travis-ci.org. - -== 1.1.3 / 2011-08-27 -* Converted to 'hoe' for release. -* Converted tests to RSpec 2. -* Extracted the body of htmldiff into a class available from - diff/lcs/htmldiff. -* Migrated development and issue tracking to GitHub. -* Bugs fixed: - - Eliminated the explicit use of RubyGems in both bin/htmldiff and bin/ldiff. - Resolves issue 4 (https://github.com/halostatue/diff-lcs/issues/4). - - Eliminated Ruby warnings. Resolves issue 3 - (https://github.com/halostatue/diff-lcs/issues/3). - -== 1.1.2 / 2004-10-20 -* Fixed a problem reported by Mauricio Fernandez in htmldiff. - -== 1.1.1 / 2004-09-25 -* Fixed bug #891: - http://rubyforge.org/tracker/?func=detail&atid=407&aid=891&group_id=84 -* Fixed a problem with callback initialisation code (it assumed that all - callbacks passed as classes can be initialised; now, it rescues - NoMethodError in the event of private :new being called). -* Modified the non-initialisable callbacks to have a private #new method. -* Moved ldiff core code to Diff::LCS::Ldiff (diff/lcs/ldiff.rb). - -== 1.1.0 / - -* Eliminated the need for Diff::LCS::Event and removed it. -* Added a contextual diff callback, Diff::LCS::ContextDiffCallback. -* Implemented patching/unpatching for standard Diff callback output formats - with both #diff and #sdiff. -* Extensive documentation changes. - -== 1.0.4 / - -* Fixed a problem with bin/ldiff output, especially for unified format. - Newlines that should have been present weren't. -* Changed the .tar.gz installer to generate Windows batch files if ones do not - exist already. Removed the existing batch files as they didn't work. - -== 1.0.3 / - -* Fixed a problem with #traverse\_sequences where the first difference from the - left sequence might not be appropriately captured. - -== 1.0.2 / - -* Fixed an issue with ldiff not working because actions were changed from - symbols to strings. - -== 1.0.1 / - -* Minor modifications to the gemspec, the README. -* Renamed the diff program to ldiff (as well as the companion batch file) so as - to not collide with the standard diff program. -* Fixed issues with RubyGems. Requires RubyGems > 0.6.1 or >= 0.6.1 with the - latest CVS version. - -== 1.0 / - -* Initial release based mostly on Perl's Algorithm::Diff. diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/License.rdoc b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/License.rdoc deleted file mode 100644 index 63b763d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/License.rdoc +++ /dev/null @@ -1,39 +0,0 @@ -== License - -This software is available under three licenses: the GNU GPL version 2 (or at -your option, a later version), the Perl Artistic license, or the MIT license. -Note that my preference for licensing is the MIT license, but Algorithm::Diff -was dually originally licensed with the Perl Artistic and the GNU GPL ("the -same terms as Perl itself") and given that the Ruby implementation originally -hewed pretty closely to the Perl version, I must maintain the additional -licensing terms. - -* Copyright 2004–2013 Austin Ziegler. -* Adapted from Algorithm::Diff (Perl) by Ned Konz and a Smalltalk version by - Mario I. Wolczko. - -=== MIT License - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -=== Perl Artistic License (version 2) -See the file docs/artistic.txt in the main distribution. - -=== GNU GPL version 2 -See the file docs/COPYING.txt in the main distribution. diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Manifest.txt b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Manifest.txt deleted file mode 100644 index d078734..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Manifest.txt +++ /dev/null @@ -1,38 +0,0 @@ -.autotest -.gemtest -.hoerc -.rspec -.travis.yml -Contributing.rdoc -Gemfile -History.rdoc -License.rdoc -Manifest.txt -README.rdoc -Rakefile -autotest/discover.rb -bin/htmldiff -bin/ldiff -docs/COPYING.txt -docs/artistic.txt -lib/diff-lcs.rb -lib/diff/lcs.rb -lib/diff/lcs/array.rb -lib/diff/lcs/block.rb -lib/diff/lcs/callbacks.rb -lib/diff/lcs/change.rb -lib/diff/lcs/htmldiff.rb -lib/diff/lcs/hunk.rb -lib/diff/lcs/internals.rb -lib/diff/lcs/ldiff.rb -lib/diff/lcs/string.rb -spec/change_spec.rb -spec/diff_spec.rb -spec/hunk_spec.rb -spec/issues_spec.rb -spec/lcs_spec.rb -spec/patch_spec.rb -spec/sdiff_spec.rb -spec/spec_helper.rb -spec/traverse_balanced_spec.rb -spec/traverse_sequences_spec.rb diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/README.rdoc b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/README.rdoc deleted file mode 100644 index fd6964e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/README.rdoc +++ /dev/null @@ -1,85 +0,0 @@ -= Diff::LCS - -home :: http://diff-lcs.rubyforge.org/ -code :: https://github.com/halostatue/diff-lcs -bugs :: https://github.com/halostatue/diff-lcs/issues -rdoc :: http://rubydoc.info/github/halostatue/diff-lcs - -== Description - -Diff::LCS computes the difference between two Enumerable sequences using the -McIlroy-Hunt longest common subsequence (LCS) algorithm. It includes utilities -to create a simple HTML diff output format and a standard diff-like tool. - -This is release 1.2.4, fixing a bug introduced after diff-lcs 1.1.3 that did -not properly prune common sequences at the beginning of a comparison set. -Thanks to Paul Kunysch for fixing this issue. - -Coincident with the release of diff-lcs 1.2.3, we reported an issue with -Rubinius in 1.9 mode -({rubinius/rubinius#2268}[https://github.com/rubinius/rubinius/issues/2268]). -We are happy to report that this issue has been resolved. - -== Synopsis - -Using this module is quite simple. By default, Diff::LCS does not extend -objects with the Diff::LCS interface, but will be called as if it were a -function: - - require 'diff/lcs' - - seq1 = %w(a b c e h j l m n p) - seq2 = %w(b c d e f j k l m r s t) - - lcs = Diff::LCS.LCS(seq1, seq2) - diffs = Diff::LCS.diff(seq1, seq2) - sdiff = Diff::LCS.sdiff(seq1, seq2) - seq = Diff::LCS.traverse_sequences(seq1, seq2, callback_obj) - bal = Diff::LCS.traverse_balanced(seq1, seq2, callback_obj) - seq2 == Diff::LCS.patch!(seq1, diffs) - seq1 == Diff::LCS.unpatch!(seq2, diffs) - seq2 == Diff::LCS.patch!(seq1, sdiff) - seq1 == Diff::LCS.unpatch!(seq2, sdiff) - -Objects can be extended with Diff::LCS: - - seq1.extend(Diff::LCS) - lcs = seq1.lcs(seq2) - diffs = seq1.diff(seq2) - sdiff = seq1.sdiff(seq2) - seq = seq1.traverse_sequences(seq2, callback_obj) - bal = seq1.traverse_balanced(seq2, callback_obj) - seq2 == seq1.patch!(diffs) - seq1 == seq2.unpatch!(diffs) - seq2 == seq1.patch!(sdiff) - seq1 == seq2.unpatch!(sdiff) - -By requiring 'diff/lcs/array' or 'diff/lcs/string', Array or String will be -extended for use this way. - -Note that Diff::LCS requires a sequenced enumerable container, which means that -the order of enumeration is both predictable and consistent for the same set of -data. While it is theoretically possible to generate a diff for an unordered -hash, it will only be meaningful if the enumeration of the hashes is -consistent. In general, this will mean that containers that behave like String -or Array will perform best. - -== History - -Diff::LCS is a port of Perl's Algorithm::Diff that uses the McIlroy-Hunt -longest common subsequence (LCS) algorithm to compute intelligent differences -between two sequenced enumerable containers. The implementation is based on -Mario I. Wolczko's {Smalltalk version 1.2}[ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st] -(1993) and Ned Konz's Perl version -{Algorithm::Diff 1.15}[http://search.cpan.org/~nedkonz/Algorithm-Diff-1.15/]. - -This library is called Diff::LCS because of an early version of Algorithm::Diff -which was restrictively licensed. - -== Continuous Integration Status - -{}[https://travis-ci.org/halostatue/diff-lcs] - -:include: Contributing.rdoc - -:include: License.rdoc diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Rakefile b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Rakefile deleted file mode 100644 index 5186800..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/Rakefile +++ /dev/null @@ -1,41 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'rubygems' -require 'rspec' -require 'hoe' - -Hoe.plugin :bundler -Hoe.plugin :doofus -Hoe.plugin :email -Hoe.plugin :gemspec2 -Hoe.plugin :git -Hoe.plugin :rubyforge -Hoe.plugin :travis - -Hoe.spec 'diff-lcs' do - developer('Austin Ziegler', 'austin@rubyforge.org') - - self.remote_rdoc_dir = '.' - self.rsync_args << ' --exclude=statsvn/' - - self.history_file = 'History.rdoc' - self.readme_file = 'README.rdoc' - self.extra_rdoc_files = FileList["*.rdoc"].to_a - - %w(MIT Perl\ Artistic\ v2 GNU\ GPL\ v2).each { |l| self.license l } - - self.extra_dev_deps << ['hoe-bundler', '~> 1.2'] - self.extra_dev_deps << ['hoe-doofus', '~> 1.0'] - self.extra_dev_deps << ['hoe-gemspec2', '~> 1.1'] - self.extra_dev_deps << ['hoe-git', '~> 1.5'] - self.extra_dev_deps << ['hoe-rubygems', '~> 1.0'] - self.extra_dev_deps << ['hoe-travis', '~> 1.2'] - self.extra_dev_deps << ['rake', '~> 10.0'] - self.extra_dev_deps << ['rspec', '~> 2.0'] -end - -unless Rake::Task.task_defined? :test - task :test => :spec -end - -# vim: syntax=ruby diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/autotest/discover.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/autotest/discover.rb deleted file mode 100644 index cd6892c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/autotest/discover.rb +++ /dev/null @@ -1 +0,0 @@ -Autotest.add_discovery { "rspec2" } diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/bin/htmldiff b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/bin/htmldiff deleted file mode 100755 index 1e4efe7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/bin/htmldiff +++ /dev/null @@ -1,32 +0,0 @@ -#!ruby -w - -require 'diff/lcs' -require 'diff/lcs/htmldiff' - -begin - require 'text/format' -rescue LoadError - Diff::LCS::HTMLDiff.can_expand_tabs = false -end - -if ARGV.size < 2 or ARGV.size > 3 - $stderr.puts "usage: #{File.basename($0)} old new [output.html]" - $stderr.puts " #{File.basename($0)} old new > output.html" - exit 127 -end - -left = IO.read(ARGV[0]).split($/) -right = IO.read(ARGV[1]).split($/) - -options = { :title => "diff #{ARGV[0]} #{ARGV[1]}" } - -htmldiff = Diff::LCS::HTMLDiff.new(left, right, options) - -if ARGV[2] - File.open(ARGV[2], "w") do |f| - htmldiff.options[:output] = f - htmldiff.run - end -else - htmldiff.run -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/bin/ldiff b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/bin/ldiff deleted file mode 100755 index a9b876f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/bin/ldiff +++ /dev/null @@ -1,6 +0,0 @@ -#!ruby -w - -require 'diff/lcs' -require 'diff/lcs/ldiff' - -exit Diff::LCS::Ldiff.run(ARGV) diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/docs/COPYING.txt b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/docs/COPYING.txt deleted file mode 100644 index d159169..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/docs/COPYING.txt +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/docs/artistic.txt b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/docs/artistic.txt deleted file mode 100644 index c04639a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/docs/artistic.txt +++ /dev/null @@ -1,127 +0,0 @@ -The "Artistic License" - - Preamble - -The intent of this document is to state the conditions under which a -Package may be copied, such that the Copyright Holder maintains some -semblance of artistic control over the development of the package, -while giving the users of the package the right to use and distribute -the Package in a more-or-less customary fashion, plus the right to make -reasonable modifications. - -Definitions: - - "Package" refers to the collection of files distributed by the - Copyright Holder, and derivatives of that collection of files - created through textual modification. - - "Standard Version" refers to such a Package if it has not been - modified, or has been modified in accordance with the wishes - of the Copyright Holder as specified below. - - "Copyright Holder" is whoever is named in the copyright or - copyrights for the package. - - "You" is you, if you're thinking about copying or distributing - this Package. - - "Reasonable copying fee" is whatever you can justify on the - basis of media cost, duplication charges, time of people involved, - and so on. (You will not be required to justify it to the - Copyright Holder, but only to the computing community at large - as a market that must bear the fee.) - - "Freely Available" means that no fee is charged for the item - itself, though there may be fees involved in handling the item. - It also means that recipients of the item may redistribute it - under the same conditions they received it. - -1. You may make and give away verbatim copies of the source form of the -Standard Version of this Package without restriction, provided that you -duplicate all of the original copyright notices and associated disclaimers. - -2. You may apply bug fixes, portability fixes and other modifications -derived from the Public Domain or from the Copyright Holder. A Package -modified in such a way shall still be considered the Standard Version. - -3. You may otherwise modify your copy of this Package in any way, provided -that you insert a prominent notice in each changed file stating how and -when you changed that file, and provided that you do at least ONE of the -following: - - a) place your modifications in the Public Domain or otherwise make them - Freely Available, such as by posting said modifications to Usenet or - an equivalent medium, or placing the modifications on a major archive - site such as uunet.uu.net, or by allowing the Copyright Holder to include - your modifications in the Standard Version of the Package. - - b) use the modified Package only within your corporation or organization. - - c) rename any non-standard executables so the names do not conflict - with standard executables, which must also be provided, and provide - a separate manual page for each non-standard executable that clearly - documents how it differs from the Standard Version. - - d) make other distribution arrangements with the Copyright Holder. - -4. You may distribute the programs of this Package in object code or -executable form, provided that you do at least ONE of the following: - - a) distribute a Standard Version of the executables and library files, - together with instructions (in the manual page or equivalent) on where - to get the Standard Version. - - b) accompany the distribution with the machine-readable source of - the Package with your modifications. - - c) give non-standard executables non-standard names, and clearly - document the differences in manual pages (or equivalent), together - with instructions on where to get the Standard Version. - - d) make other distribution arrangements with the Copyright Holder. - -5. You may charge a reasonable copying fee for any distribution of this -Package. You may charge any fee you choose for support of this -Package. You may not charge a fee for this Package itself. However, -you may distribute this Package in aggregate with other (possibly -commercial) programs as part of a larger (possibly commercial) software -distribution provided that you do not advertise this Package as a -product of your own. You may embed this Package's interpreter within -an executable of yours (by linking); this shall be construed as a mere -form of aggregation, provided that the complete Standard Version of the -interpreter is so embedded. - -6. The scripts and library files supplied as input to or produced as -output from the programs of this Package do not automatically fall -under the copyright of this Package, but belong to whoever generated -them, and may be sold commercially, and may be aggregated with this -Package. If such scripts or library files are aggregated with this -Package via the so-called "undump" or "unexec" methods of producing a -binary executable image, then distribution of such an image shall -neither be construed as a distribution of this Package nor shall it -fall under the restrictions of Paragraphs 3 and 4, provided that you do -not represent such an executable image as a Standard Version of this -Package. - -7. C subroutines (or comparably compiled subroutines in other -languages) supplied by you and linked into this Package in order to -emulate subroutines and variables of the language defined by this -Package shall not be considered part of this Package, but are the -equivalent of input as in Paragraph 6, provided these subroutines do -not change the language in any way that would cause it to fail the -regression tests for the language. - -8. Aggregation of this Package with a commercial distribution is always -permitted provided that the use of this Package is embedded; that is, -when no overt attempt is made to make this Package's interfaces visible -to the end user of the commercial distribution. Such use shall not be -construed as a distribution of this Package. - -9. The name of the Copyright Holder may not be used to endorse or promote -products derived from this software without specific prior written permission. - -10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR -IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED -WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. - - The End diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff-lcs.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff-lcs.rb deleted file mode 100644 index 10d6e8a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff-lcs.rb +++ /dev/null @@ -1,3 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'diff/lcs' diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs.rb deleted file mode 100644 index 5559615..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs.rb +++ /dev/null @@ -1,805 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -module Diff; end unless defined? Diff -# = Diff::LCS 1.2.5 -# -# Computes "intelligent" differences between two sequenced Enumerables. This -# is an implementation of the McIlroy-Hunt "diff" algorithm for Enumerable -# objects that include Diffable. -# -# Based on Mario I. Wolczko's Smalltalk version (1.2, 1993) and Ned Konz's -# Perl version (Algorithm::Diff 1.15). -# -# == Synopsis -# require 'diff/lcs' -# -# seq1 = %w(a b c e h j l m n p) -# seq2 = %w(b c d e f j k l m r s t) -# -# lcs = Diff::LCS.lcs(seq1, seq2) -# diffs = Diff::LCS.diff(seq1, seq2) -# sdiff = Diff::LCS.sdiff(seq1, seq2) -# seq = Diff::LCS.traverse_sequences(seq1, seq2, callback_obj) -# bal = Diff::LCS.traverse_balanced(seq1, seq2, callback_obj) -# seq2 == Diff::LCS.patch(seq1, diffs) -# seq2 == Diff::LCS.patch!(seq1, diffs) -# seq1 == Diff::LCS.unpatch(seq2, diffs) -# seq1 == Diff::LCS.unpatch!(seq2, diffs) -# seq2 == Diff::LCS.patch(seq1, sdiff) -# seq2 == Diff::LCS.patch!(seq1, sdiff) -# seq1 == Diff::LCS.unpatch(seq2, sdiff) -# seq1 == Diff::LCS.unpatch!(seq2, sdiff) -# -# Alternatively, objects can be extended with Diff::LCS: -# -# seq1.extend(Diff::LCS) -# lcs = seq1.lcs(seq2) -# diffs = seq1.diff(seq2) -# sdiff = seq1.sdiff(seq2) -# seq = seq1.traverse_sequences(seq2, callback_obj) -# bal = seq1.traverse_balanced(seq2, callback_obj) -# seq2 == seq1.patch(diffs) -# seq2 == seq1.patch!(diffs) -# seq1 == seq2.unpatch(diffs) -# seq1 == seq2.unpatch!(diffs) -# seq2 == seq1.patch(sdiff) -# seq2 == seq1.patch!(sdiff) -# seq1 == seq2.unpatch(sdiff) -# seq1 == seq2.unpatch!(sdiff) -# -# Default extensions are provided for Array and String objects through the -# use of 'diff/lcs/array' and 'diff/lcs/string'. -# -# == Introduction (by Mark-Jason Dominus) -# -# The following text is from the Perl documentation. The only changes -# have been to make the text appear better in Rdoc. -# -# I once read an article written by the authors of +diff+; they said that -# they hard worked very hard on the algorithm until they found the right -# one. -# -# I think what they ended up using (and I hope someone will correct me, -# because I am not very confident about this) was the `longest common -# subsequence' method. In the LCS problem, you have two sequences of items: -# -# a b c d f g h j q z -# a b c d e f g i j k r x y z -# -# and you want to find the longest sequence of items that is present in both -# original sequences in the same order. That is, you want to find a new -# sequence *S* which can be obtained from the first sequence by deleting -# some items, and from the second sequence by deleting other items. You also -# want *S* to be as long as possible. In this case *S* is: -# -# a b c d f g j z -# -# From there it's only a small step to get diff-like output: -# -# e h i k q r x y -# + - + + - + + + -# -# This module solves the LCS problem. It also includes a canned function to -# generate +diff+-like output. -# -# It might seem from the example above that the LCS of two sequences is -# always pretty obvious, but that's not always the case, especially when the -# two sequences have many repeated elements. For example, consider -# -# a x b y c z p d q -# a b c a x b y c z -# -# A naive approach might start by matching up the +a+ and +b+ that appear at -# the beginning of each sequence, like this: -# -# a x b y c z p d q -# a b c a b y c z -# -# This finds the common subsequence +a b c z+. But actually, the LCS is +a x -# b y c z+: -# -# a x b y c z p d q -# a b c a x b y c z -# -# == Author -# This version is by Austin Ziegler . -# -# It is based on the Perl Algorithm::Diff (1.15) by Ned Konz , copyright -# © 2000–2002 and the Smalltalk diff version by Mario I. -# Wolczko, copyright © 1993. Documentation includes work by -# Mark-Jason Dominus. -# -# == Licence -# Copyright © 2004–2013 Austin Ziegler -# This program is free software; you can redistribute it and/or modify it -# under the same terms as Ruby, or alternatively under the Perl Artistic -# licence. -# -# == Credits -# Much of the documentation is taken directly from the Perl Algorithm::Diff -# implementation and was written originally by Mark-Jason Dominus and later -# by Ned Konz. The basic Ruby implementation was re-ported from the -# Smalltalk implementation, available at -# ftp://st.cs.uiuc.edu/pub/Smalltalk/MANCHESTER/manchester/4.0/diff.st -# -# #sdiff and #traverse_balanced were written for the Perl version by Mike -# Schilli . -# -# "The algorithm is described in A Fast Algorithm for Computing Longest -# Common Subsequences, CACM, vol.20, no.5, pp.350-353, May -# 1977, with a few minor improvements to improve the speed." -module Diff::LCS - VERSION = '1.2.5' -end - -require 'diff/lcs/callbacks' -require 'diff/lcs/internals' - -module Diff::LCS - # Returns an Array containing the longest common subsequence(s) between - # +self+ and +other+. See Diff::LCS#LCS. - # - # lcs = seq1.lcs(seq2) - def lcs(other, &block) #:yields self[i] if there are matched subsequences: - Diff::LCS.lcs(self, other, &block) - end - - # Returns the difference set between +self+ and +other+. See - # Diff::LCS#diff. - def diff(other, callbacks = nil, &block) - Diff::LCS.diff(self, other, callbacks, &block) - end - - # Returns the balanced ("side-by-side") difference set between +self+ and - # +other+. See Diff::LCS#sdiff. - def sdiff(other, callbacks = nil, &block) - Diff::LCS.sdiff(self, other, callbacks, &block) - end - - # Traverses the discovered longest common subsequences between +self+ and - # +other+. See Diff::LCS#traverse_sequences. - def traverse_sequences(other, callbacks = nil, &block) - traverse_sequences(self, other, callbacks || - Diff::LCS.YieldingCallbacks, &block) - end - - # Traverses the discovered longest common subsequences between +self+ and - # +other+ using the alternate, balanced algorithm. See - # Diff::LCS#traverse_balanced. - def traverse_balanced(other, callbacks = nil, &block) - traverse_balanced(self, other, callbacks || - Diff::LCS.YieldingCallbacks, &block) - end - - # Attempts to patch +self+ with the provided +patchset+. A new sequence - # based on +self+ and the +patchset+ will be created. See Diff::LCS#patch. - # Attempts to autodiscover the direction of the patch. - def patch(patchset) - Diff::LCS.patch(self, patchset) - end - alias_method :unpatch, :patch - - # Attempts to patch +self+ with the provided +patchset+. A new sequence - # based on +self+ and the +patchset+ will be created. See Diff::LCS#patch. - # Does no patch direction autodiscovery. - def patch!(patchset) - Diff::LCS.patch!(self, patchset) - end - - # Attempts to unpatch +self+ with the provided +patchset+. A new sequence - # based on +self+ and the +patchset+ will be created. See Diff::LCS#unpatch. - # Does no patch direction autodiscovery. - def unpatch!(patchset) - Diff::LCS.unpatch!(self, patchset) - end - - # Attempts to patch +self+ with the provided +patchset+, using #patch!. If - # the sequence this is used on supports #replace, the value of +self+ will - # be replaced. See Diff::LCS#patch. Does no patch direction autodiscovery. - def patch_me(patchset) - if respond_to? :replace - replace(patch!(patchset)) - else - patch!(patchset) - end - end - - # Attempts to unpatch +self+ with the provided +patchset+, using - # #unpatch!. If the sequence this is used on supports #replace, the value - # of +self+ will be replaced. See Diff::LCS#unpatch. Does no patch direction - # autodiscovery. - def unpatch_me(patchset) - if respond_to? :replace - replace(unpatch!(patchset)) - else - unpatch!(patchset) - end - end -end - -class << Diff::LCS - def lcs(seq1, seq2, &block) #:yields seq1[i] for each matched: - matches = Diff::LCS::Internals.lcs(seq1, seq2) - ret = [] - string = seq1.kind_of? String - matches.each_with_index do |e, i| - unless matches[i].nil? - v = string ? seq1[i, 1] : seq1[i] - v = block[v] if block - ret << v - end - end - ret - end - alias_method :LCS, :lcs - - # #diff computes the smallest set of additions and deletions necessary to - # turn the first sequence into the second, and returns a description of - # these changes. - # - # See Diff::LCS::DiffCallbacks for the default behaviour. An alternate - # behaviour may be implemented with Diff::LCS::ContextDiffCallbacks. If a - # Class argument is provided for +callbacks+, #diff will attempt to - # initialise it. If the +callbacks+ object (possibly initialised) responds - # to #finish, it will be called. - def diff(seq1, seq2, callbacks = nil, &block) # :yields diff changes: - diff_traversal(:diff, seq1, seq2, callbacks || Diff::LCS::DiffCallbacks, - &block) - end - - # #sdiff computes all necessary components to show two sequences and their - # minimized differences side by side, just like the Unix utility - # sdiff does: - # - # old < - - # same same - # before | after - # - > new - # - # See Diff::LCS::SDiffCallbacks for the default behaviour. An alternate - # behaviour may be implemented with Diff::LCS::ContextDiffCallbacks. If a - # Class argument is provided for +callbacks+, #diff will attempt to - # initialise it. If the +callbacks+ object (possibly initialised) responds - # to #finish, it will be called. - def sdiff(seq1, seq2, callbacks = nil, &block) #:yields diff changes: - diff_traversal(:sdiff, seq1, seq2, callbacks || Diff::LCS::SDiffCallbacks, - &block) - end - - # #traverse_sequences is the most general facility provided by this - # module; #diff and #lcs are implemented as calls to it. - # - # The arguments to #traverse_sequences are the two sequences to traverse, - # and a callback object, like this: - # - # traverse_sequences(seq1, seq2, Diff::LCS::ContextDiffCallbacks.new) - # - # == Callback Methods - # - # Optional callback methods are emphasized. - # - # callbacks#match:: Called when +a+ and +b+ are pointing to - # common elements in +A+ and +B+. - # callbacks#discard_a:: Called when +a+ is pointing to an - # element not in +B+. - # callbacks#discard_b:: Called when +b+ is pointing to an - # element not in +A+. - # callbacks#finished_a:: Called when +a+ has reached the end of - # sequence +A+. - # callbacks#finished_b:: Called when +b+ has reached the end of - # sequence +B+. - # - # == Algorithm - # - # a---+ - # v - # A = a b c e h j l m n p - # B = b c d e f j k l m r s t - # ^ - # b---+ - # - # If there are two arrows (+a+ and +b+) pointing to elements of sequences - # +A+ and +B+, the arrows will initially point to the first elements of - # their respective sequences. #traverse_sequences will advance the arrows - # through the sequences one element at a time, calling a method on the - # user-specified callback object before each advance. It will advance the - # arrows in such a way that if there are elements A[i] and - # B[j] which are both equal and part of the longest common - # subsequence, there will be some moment during the execution of - # #traverse_sequences when arrow +a+ is pointing to A[i] and - # arrow +b+ is pointing to B[j]. When this happens, - # #traverse_sequences will call callbacks#match and then it will - # advance both arrows. - # - # Otherwise, one of the arrows is pointing to an element of its sequence - # that is not part of the longest common subsequence. #traverse_sequences - # will advance that arrow and will call callbacks#discard_a or - # callbacks#discard_b, depending on which arrow it advanced. If - # both arrows point to elements that are not part of the longest common - # subsequence, then #traverse_sequences will advance one of them and call - # the appropriate callback, but it is not specified which it will call. - # - # The methods for callbacks#match, callbacks#discard_a, - # and callbacks#discard_b are invoked with an event comprising - # the action ("=", "+", or "-", respectively), the indicies +i+ and +j+, - # and the elements A[i] and B[j]. Return values are - # discarded by #traverse_sequences. - # - # === End of Sequences - # - # If arrow +a+ reaches the end of its sequence before arrow +b+ does, - # #traverse_sequence will try to call callbacks#finished_a with - # the last index and element of +A+ (A[-1]) and the current index - # and element of +B+ (B[j]). If callbacks#finished_a - # does not exist, then callbacks#discard_b will be called on each - # element of +B+ until the end of the sequence is reached (the call will - # be done with A[-1] and B[j] for each element). - # - # If +b+ reaches the end of +B+ before +a+ reaches the end of +A+, - # callbacks#finished_b will be called with the current index and - # element of +A+ (A[i]) and the last index and element of +B+ - # (A[-1]). Again, if callbacks#finished_b does not exist - # on the callback object, then callbacks#discard_a will be called - # on each element of +A+ until the end of the sequence is reached - # (A[i] and B[-1]). - # - # There is a chance that one additional callbacks#discard_a or - # callbacks#discard_b will be called after the end of the - # sequence is reached, if +a+ has not yet reached the end of +A+ or +b+ - # has not yet reached the end of +B+. - def traverse_sequences(seq1, seq2, callbacks = Diff::LCS::SequenceCallbacks, &block) #:yields change events: - callbacks ||= Diff::LCS::SequenceCallbacks - matches = Diff::LCS::Internals.lcs(seq1, seq2) - - run_finished_a = run_finished_b = false - string = seq1.kind_of?(String) - - a_size = seq1.size - b_size = seq2.size - ai = bj = 0 - - (0..matches.size).each do |i| - b_line = matches[i] - - ax = string ? seq1[i, 1] : seq1[i] - bx = string ? seq2[bj, 1] : seq2[bj] - - if b_line.nil? - unless ax.nil? or (string and ax.empty?) - event = Diff::LCS::ContextChange.new('-', i, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_a(event) - end - else - loop do - break unless bj < b_line - bx = string ? seq2[bj, 1] : seq2[bj] - event = Diff::LCS::ContextChange.new('+', i, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_b(event) - bj += 1 - end - bx = string ? seq2[bj, 1] : seq2[bj] - event = Diff::LCS::ContextChange.new('=', i, ax, bj, bx) - event = yield event if block_given? - callbacks.match(event) - bj += 1 - end - ai = i - end - ai += 1 - - # The last entry (if any) processed was a match. +ai+ and +bj+ point - # just past the last matching lines in their sequences. - while (ai < a_size) or (bj < b_size) - # last A? - if ai == a_size and bj < b_size - if callbacks.respond_to?(:finished_a) and not run_finished_a - ax = string ? seq1[-1, 1] : seq1[-1] - bx = string ? seq2[bj, 1] : seq2[bj] - event = Diff::LCS::ContextChange.new('>', (a_size - 1), ax, bj, bx) - event = yield event if block_given? - callbacks.finished_a(event) - run_finished_a = true - else - ax = string ? seq1[ai, 1] : seq1[ai] - loop do - bx = string ? seq2[bj, 1] : seq2[bj] - event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_b(event) - bj += 1 - break unless bj < b_size - end - end - end - - # last B? - if bj == b_size and ai < a_size - if callbacks.respond_to?(:finished_b) and not run_finished_b - ax = string ? seq1[ai, 1] : seq1[ai] - bx = string ? seq2[-1, 1] : seq2[-1] - event = Diff::LCS::ContextChange.new('<', ai, ax, (b_size - 1), bx) - event = yield event if block_given? - callbacks.finished_b(event) - run_finished_b = true - else - bx = string ? seq2[bj, 1] : seq2[bj] - loop do - ax = string ? seq1[ai, 1] : seq1[ai] - event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_a(event) - ai += 1 - break unless bj < b_size - end - end - end - - if ai < a_size - ax = string ? seq1[ai, 1] : seq1[ai] - bx = string ? seq2[bj, 1] : seq2[bj] - event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_a(event) - ai += 1 - end - - if bj < b_size - ax = string ? seq1[ai, 1] : seq1[ai] - bx = string ? seq2[bj, 1] : seq2[bj] - event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_b(event) - bj += 1 - end - end - end - - # #traverse_balanced is an alternative to #traverse_sequences. It uses a - # different algorithm to iterate through the entries in the computed - # longest common subsequence. Instead of viewing the changes as insertions - # or deletions from one of the sequences, #traverse_balanced will report - # changes between the sequences. - # - # The arguments to #traverse_balanced are the two sequences to traverse - # and a callback object, like this: - # - # traverse_balanced(seq1, seq2, Diff::LCS::ContextDiffCallbacks.new) - # - # #sdiff is implemented with #traverse_balanced. - # - # == Callback Methods - # - # Optional callback methods are emphasized. - # - # callbacks#match:: Called when +a+ and +b+ are pointing to - # common elements in +A+ and +B+. - # callbacks#discard_a:: Called when +a+ is pointing to an - # element not in +B+. - # callbacks#discard_b:: Called when +b+ is pointing to an - # element not in +A+. - # callbacks#change:: Called when +a+ and +b+ are pointing to - # the same relative position, but - # A[a] and B[b] are not - # the same; a change has - # occurred. - # - # #traverse_balanced might be a bit slower than #traverse_sequences, - # noticable only while processing huge amounts of data. - # - # == Algorithm - # - # a---+ - # v - # A = a b c e h j l m n p - # B = b c d e f j k l m r s t - # ^ - # b---+ - # - # === Matches - # - # If there are two arrows (+a+ and +b+) pointing to elements of sequences - # +A+ and +B+, the arrows will initially point to the first elements of - # their respective sequences. #traverse_sequences will advance the arrows - # through the sequences one element at a time, calling a method on the - # user-specified callback object before each advance. It will advance the - # arrows in such a way that if there are elements A[i] and - # B[j] which are both equal and part of the longest common - # subsequence, there will be some moment during the execution of - # #traverse_sequences when arrow +a+ is pointing to A[i] and - # arrow +b+ is pointing to B[j]. When this happens, - # #traverse_sequences will call callbacks#match and then it will - # advance both arrows. - # - # === Discards - # - # Otherwise, one of the arrows is pointing to an element of its sequence - # that is not part of the longest common subsequence. #traverse_sequences - # will advance that arrow and will call callbacks#discard_a or - # callbacks#discard_b, depending on which arrow it advanced. - # - # === Changes - # - # If both +a+ and +b+ point to elements that are not part of the longest - # common subsequence, then #traverse_sequences will try to call - # callbacks#change and advance both arrows. If - # callbacks#change is not implemented, then - # callbacks#discard_a and callbacks#discard_b will be - # called in turn. - # - # The methods for callbacks#match, callbacks#discard_a, - # callbacks#discard_b, and callbacks#change are invoked - # with an event comprising the action ("=", "+", "-", or "!", - # respectively), the indicies +i+ and +j+, and the elements - # A[i] and B[j]. Return values are discarded by - # #traverse_balanced. - # - # === Context - # Note that +i+ and +j+ may not be the same index position, even if +a+ - # and +b+ are considered to be pointing to matching or changed elements. - def traverse_balanced(seq1, seq2, callbacks = Diff::LCS::BalancedCallbacks) - matches = Diff::LCS::Internals.lcs(seq1, seq2) - a_size = seq1.size - b_size = seq2.size - ai = bj = mb = 0 - ma = -1 - string = seq1.kind_of?(String) - - # Process all the lines in the match vector. - loop do - # Find next match indices +ma+ and +mb+ - loop do - ma += 1 - break unless ma < matches.size and matches[ma].nil? - end - - break if ma >= matches.size # end of matches? - mb = matches[ma] - - # Change(seq2) - while (ai < ma) or (bj < mb) - ax = string ? seq1[ai, 1] : seq1[ai] - bx = string ? seq2[bj, 1] : seq2[bj] - - case [(ai < ma), (bj < mb)] - when [true, true] - if callbacks.respond_to?(:change) - event = Diff::LCS::ContextChange.new('!', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.change(event) - ai += 1 - bj += 1 - else - event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_a(event) - ai += 1 - ax = string ? seq1[ai, 1] : seq1[ai] - event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_b(event) - bj += 1 - end - when [true, false] - event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_a(event) - ai += 1 - when [false, true] - event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_b(event) - bj += 1 - end - end - - # Match - ax = string ? seq1[ai, 1] : seq1[ai] - bx = string ? seq2[bj, 1] : seq2[bj] - event = Diff::LCS::ContextChange.new('=', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.match(event) - ai += 1 - bj += 1 - end - - while (ai < a_size) or (bj < b_size) - ax = string ? seq1[ai, 1] : seq1[ai] - bx = string ? seq2[bj, 1] : seq2[bj] - - case [(ai < a_size), (bj < b_size)] - when [true, true] - if callbacks.respond_to?(:change) - event = Diff::LCS::ContextChange.new('!', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.change(event) - ai += 1 - bj += 1 - else - event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_a(event) - ai += 1 - ax = string ? seq1[ai, 1] : seq1[ai] - event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_b(event) - bj += 1 - end - when [true, false] - event = Diff::LCS::ContextChange.new('-', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_a(event) - ai += 1 - when [false, true] - event = Diff::LCS::ContextChange.new('+', ai, ax, bj, bx) - event = yield event if block_given? - callbacks.discard_b(event) - bj += 1 - end - end - end - - PATCH_MAP = { #:nodoc: - :patch => { '+' => '+', '-' => '-', '!' => '!', '=' => '=' }, - :unpatch => { '+' => '-', '-' => '+', '!' => '!', '=' => '=' } - } - - # Applies a +patchset+ to the sequence +src+ according to the +direction+ - # (:patch or :unpatch), producing a new sequence. - # - # If the +direction+ is not specified, Diff::LCS::patch will attempt to - # discover the direction of the +patchset+. - # - # A +patchset+ can be considered to apply forward (:patch) if the - # following expression is true: - # - # patch(s1, diff(s1, s2)) -> s2 - # - # A +patchset+ can be considered to apply backward (:unpatch) if - # the following expression is true: - # - # patch(s2, diff(s1, s2)) -> s1 - # - # If the +patchset+ contains no changes, the +src+ value will be returned - # as either src.dup or +src+. A +patchset+ can be deemed as - # having no changes if the following predicate returns true: - # - # patchset.empty? or - # patchset.flatten.all? { |change| change.unchanged? } - # - # === Patchsets - # - # A +patchset+ is always an enumerable sequence of changes, hunks of - # changes, or a mix of the two. A hunk of changes is an enumerable - # sequence of changes: - # - # [ # patchset - # # change - # [ # hunk - # # change - # ] - # ] - # - # The +patch+ method accepts patchsets that are enumerable - # sequences containing either Diff::LCS::Change objects (or a subclass) or - # the array representations of those objects. Prior to application, array - # representations of Diff::LCS::Change objects will be reified. - def patch(src, patchset, direction = nil) - # Normalize the patchset. - has_changes, patchset = Diff::LCS::Internals.analyze_patchset(patchset) - - if not has_changes - return src.dup if src.respond_to? :dup - return src - end - - string = src.kind_of?(String) - # Start with a new empty type of the source's class - res = src.class.new - - direction ||= Diff::LCS::Internals.intuit_diff_direction(src, patchset) - - ai = bj = 0 - - patch_map = PATCH_MAP[direction] - - patchset.flatten.each do |change| - # Both Change and ContextChange support #action - action = patch_map[change.action] - - case change - when Diff::LCS::ContextChange - case direction - when :patch - el = change.new_element - op = change.old_position - np = change.new_position - when :unpatch - el = change.old_element - op = change.new_position - np = change.old_position - end - - case action - when '-' # Remove details from the old string - while ai < op - res << (string ? src[ai, 1] : src[ai]) - ai += 1 - bj += 1 - end - ai += 1 - when '+' - while bj < np - res << (string ? src[ai, 1] : src[ai]) - ai += 1 - bj += 1 - end - - res << el - bj += 1 - when '=' - # This only appears in sdiff output with the SDiff callback. - # Therefore, we only need to worry about dealing with a single - # element. - res << el - - ai += 1 - bj += 1 - when '!' - while ai < op - res << (string ? src[ai, 1] : src[ai]) - ai += 1 - bj += 1 - end - - bj += 1 - ai += 1 - - res << el - end - when Diff::LCS::Change - case action - when '-' - while ai < change.position - res << (string ? src[ai, 1] : src[ai]) - ai += 1 - bj += 1 - end - ai += 1 - when '+' - while bj < change.position - res << (string ? src[ai, 1] : src[ai]) - ai += 1 - bj += 1 - end - - bj += 1 - - res << change.element - end - end - end - - while ai < src.size - res << (string ? src[ai, 1] : src[ai]) - ai += 1 - bj += 1 - end - - res - end - - # Given a set of patchset, convert the current version to the prior - # version. Does no auto-discovery. - def unpatch!(src, patchset) - patch(src, patchset, :unpatch) - end - - # Given a set of patchset, convert the current version to the next - # version. Does no auto-discovery. - def patch!(src, patchset) - patch(src, patchset, :patch) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/array.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/array.rb deleted file mode 100644 index 1acd8c9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/array.rb +++ /dev/null @@ -1,7 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'diff/lcs' - -class Array - include Diff::LCS -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/block.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/block.rb deleted file mode 100644 index 8518727..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/block.rb +++ /dev/null @@ -1,37 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -# A block is an operation removing, adding, or changing a group of items. -# Basically, this is just a list of changes, where each change adds or -# deletes a single item. Used by bin/ldiff. -class Diff::LCS::Block - attr_reader :changes, :insert, :remove - - def initialize(chunk) - @changes = [] - @insert = [] - @remove = [] - - chunk.each do |item| - @changes << item - @remove << item if item.deleting? - @insert << item if item.adding? - end - end - - def diff_size - @insert.size - @remove.size - end - - def op - case [@remove.empty?, @insert.empty?] - when [false, false] - '!' - when [false, true] - '-' - when [true, false] - '+' - else # [true, true] - '^' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/callbacks.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/callbacks.rb deleted file mode 100644 index 8eec5fc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/callbacks.rb +++ /dev/null @@ -1,322 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'diff/lcs/change' - -module Diff::LCS - # This callback object implements the default set of callback events, - # which only returns the event itself. Note that #finished_a and - # #finished_b are not implemented -- I haven't yet figured out where they - # would be useful. - # - # Note that this is intended to be called as is, e.g., - # - # Diff::LCS.LCS(seq1, seq2, Diff::LCS::DefaultCallbacks) - class DefaultCallbacks - class << self - # Called when two items match. - def match(event) - event - end - # Called when the old value is discarded in favour of the new value. - def discard_a(event) - event - end - # Called when the new value is discarded in favour of the old value. - def discard_b(event) - event - end - # Called when both the old and new values have changed. - def change(event) - event - end - - private :new - end - end - - # An alias for DefaultCallbacks that is used in - # Diff::LCS#traverse_sequences. - # - # Diff::LCS.LCS(seq1, seq2, Diff::LCS::SequenceCallbacks) - SequenceCallbacks = DefaultCallbacks - - # An alias for DefaultCallbacks that is used in - # Diff::LCS#traverse_balanced. - # - # Diff::LCS.LCS(seq1, seq2, Diff::LCS::BalancedCallbacks) - BalancedCallbacks = DefaultCallbacks - - def self.callbacks_for(callbacks) - callbacks.new rescue callbacks - end -end - -# This will produce a compound array of simple diff change objects. Each -# element in the #diffs array is a +hunk+ or +hunk+ array, where each -# element in each +hunk+ array is a single Change object representing the -# addition or removal of a single element from one of the two tested -# sequences. The +hunk+ provides the full context for the changes. -# -# diffs = Diff::LCS.diff(seq1, seq2) -# # This example shows a simplified array format. -# # [ [ [ '-', 0, 'a' ] ], # 1 -# # [ [ '+', 2, 'd' ] ], # 2 -# # [ [ '-', 4, 'h' ], # 3 -# # [ '+', 4, 'f' ] ], -# # [ [ '+', 6, 'k' ] ], # 4 -# # [ [ '-', 8, 'n' ], # 5 -# # [ '-', 9, 'p' ], -# # [ '+', 9, 'r' ], -# # [ '+', 10, 's' ], -# # [ '+', 11, 't' ] ] ] -# -# There are five hunks here. The first hunk says that the +a+ at position 0 -# of the first sequence should be deleted ('-'). The second hunk -# says that the +d+ at position 2 of the second sequence should be inserted -# ('+'). The third hunk says that the +h+ at position 4 of the -# first sequence should be removed and replaced with the +f+ from position 4 -# of the second sequence. The other two hunks are described similarly. -# -# === Use -# -# This callback object must be initialised and is used by the Diff::LCS#diff -# method. -# -# cbo = Diff::LCS::DiffCallbacks.new -# Diff::LCS.LCS(seq1, seq2, cbo) -# cbo.finish -# -# Note that the call to #finish is absolutely necessary, or the last set of -# changes will not be visible. Alternatively, can be used as: -# -# cbo = Diff::LCS::DiffCallbacks.new { |tcbo| Diff::LCS.LCS(seq1, seq2, tcbo) } -# -# The necessary #finish call will be made. -# -# === Simplified Array Format -# -# The simplified array format used in the example above can be obtained -# with: -# -# require 'pp' -# pp diffs.map { |e| e.map { |f| f.to_a } } -class Diff::LCS::DiffCallbacks - # Returns the difference set collected during the diff process. - attr_reader :diffs - - def initialize # :yields self: - @hunk = [] - @diffs = [] - - if block_given? - begin - yield self - ensure - self.finish - end - end - end - - # Finalizes the diff process. If an unprocessed hunk still exists, then it - # is appended to the diff list. - def finish - finish_hunk - end - - def match(event) - finish_hunk - end - - def discard_a(event) - @hunk << Diff::LCS::Change.new('-', event.old_position, event.old_element) - end - - def discard_b(event) - @hunk << Diff::LCS::Change.new('+', event.new_position, event.new_element) - end - - def finish_hunk - @diffs << @hunk unless @hunk.empty? - @hunk = [] - end - private :finish_hunk -end - -# This will produce a compound array of contextual diff change objects. Each -# element in the #diffs array is a "hunk" array, where each element in each -# "hunk" array is a single change. Each change is a Diff::LCS::ContextChange -# that contains both the old index and new index values for the change. The -# "hunk" provides the full context for the changes. Both old and new objects -# will be presented for changed objects. +nil+ will be substituted for a -# discarded object. -# -# seq1 = %w(a b c e h j l m n p) -# seq2 = %w(b c d e f j k l m r s t) -# -# diffs = Diff::LCS.diff(seq1, seq2, Diff::LCS::ContextDiffCallbacks) -# # This example shows a simplified array format. -# # [ [ [ '-', [ 0, 'a' ], [ 0, nil ] ] ], # 1 -# # [ [ '+', [ 3, nil ], [ 2, 'd' ] ] ], # 2 -# # [ [ '-', [ 4, 'h' ], [ 4, nil ] ], # 3 -# # [ '+', [ 5, nil ], [ 4, 'f' ] ] ], -# # [ [ '+', [ 6, nil ], [ 6, 'k' ] ] ], # 4 -# # [ [ '-', [ 8, 'n' ], [ 9, nil ] ], # 5 -# # [ '+', [ 9, nil ], [ 9, 'r' ] ], -# # [ '-', [ 9, 'p' ], [ 10, nil ] ], -# # [ '+', [ 10, nil ], [ 10, 's' ] ], -# # [ '+', [ 10, nil ], [ 11, 't' ] ] ] ] -# -# The five hunks shown are comprised of individual changes; if there is a -# related set of changes, they are still shown individually. -# -# This callback can also be used with Diff::LCS#sdiff, which will produce -# results like: -# -# diffs = Diff::LCS.sdiff(seq1, seq2, Diff::LCS::ContextCallbacks) -# # This example shows a simplified array format. -# # [ [ [ "-", [ 0, "a" ], [ 0, nil ] ] ], # 1 -# # [ [ "+", [ 3, nil ], [ 2, "d" ] ] ], # 2 -# # [ [ "!", [ 4, "h" ], [ 4, "f" ] ] ], # 3 -# # [ [ "+", [ 6, nil ], [ 6, "k" ] ] ], # 4 -# # [ [ "!", [ 8, "n" ], [ 9, "r" ] ], # 5 -# # [ "!", [ 9, "p" ], [ 10, "s" ] ], -# # [ "+", [ 10, nil ], [ 11, "t" ] ] ] ] -# -# The five hunks are still present, but are significantly shorter in total -# presentation, because changed items are shown as changes ("!") instead of -# potentially "mismatched" pairs of additions and deletions. -# -# The result of this operation is similar to that of -# Diff::LCS::SDiffCallbacks. They may be compared as: -# -# s = Diff::LCS.sdiff(seq1, seq2).reject { |e| e.action == "=" } -# c = Diff::LCS.sdiff(seq1, seq2, Diff::LCS::ContextDiffCallbacks).flatten -# -# s == c # -> true -# -# === Use -# -# This callback object must be initialised and can be used by the -# Diff::LCS#diff or Diff::LCS#sdiff methods. -# -# cbo = Diff::LCS::ContextDiffCallbacks.new -# Diff::LCS.LCS(seq1, seq2, cbo) -# cbo.finish -# -# Note that the call to #finish is absolutely necessary, or the last set of -# changes will not be visible. Alternatively, can be used as: -# -# cbo = Diff::LCS::ContextDiffCallbacks.new { |tcbo| Diff::LCS.LCS(seq1, seq2, tcbo) } -# -# The necessary #finish call will be made. -# -# === Simplified Array Format -# -# The simplified array format used in the example above can be obtained -# with: -# -# require 'pp' -# pp diffs.map { |e| e.map { |f| f.to_a } } -class Diff::LCS::ContextDiffCallbacks < Diff::LCS::DiffCallbacks - def discard_a(event) - @hunk << Diff::LCS::ContextChange.simplify(event) - end - - def discard_b(event) - @hunk << Diff::LCS::ContextChange.simplify(event) - end - - def change(event) - @hunk << Diff::LCS::ContextChange.simplify(event) - end -end - -# This will produce a simple array of diff change objects. Each element in -# the #diffs array is a single ContextChange. In the set of #diffs provided -# by SDiffCallbacks, both old and new objects will be presented for both -# changed and unchanged objects. +nil+ will be substituted -# for a discarded object. -# -# The diffset produced by this callback, when provided to Diff::LCS#sdiff, -# will compute and display the necessary components to show two sequences -# and their minimized differences side by side, just like the Unix utility -# +sdiff+. -# -# same same -# before | after -# old < - -# - > new -# -# seq1 = %w(a b c e h j l m n p) -# seq2 = %w(b c d e f j k l m r s t) -# -# diffs = Diff::LCS.sdiff(seq1, seq2) -# # This example shows a simplified array format. -# # [ [ "-", [ 0, "a"], [ 0, nil ] ], -# # [ "=", [ 1, "b"], [ 0, "b" ] ], -# # [ "=", [ 2, "c"], [ 1, "c" ] ], -# # [ "+", [ 3, nil], [ 2, "d" ] ], -# # [ "=", [ 3, "e"], [ 3, "e" ] ], -# # [ "!", [ 4, "h"], [ 4, "f" ] ], -# # [ "=", [ 5, "j"], [ 5, "j" ] ], -# # [ "+", [ 6, nil], [ 6, "k" ] ], -# # [ "=", [ 6, "l"], [ 7, "l" ] ], -# # [ "=", [ 7, "m"], [ 8, "m" ] ], -# # [ "!", [ 8, "n"], [ 9, "r" ] ], -# # [ "!", [ 9, "p"], [ 10, "s" ] ], -# # [ "+", [ 10, nil], [ 11, "t" ] ] ] -# -# The result of this operation is similar to that of -# Diff::LCS::ContextDiffCallbacks. They may be compared as: -# -# s = Diff::LCS.sdiff(seq1, seq2).reject { |e| e.action == "=" } -# c = Diff::LCS.sdiff(seq1, seq2, Diff::LCS::ContextDiffCallbacks).flatten -# -# s == c # -> true -# -# === Use -# -# This callback object must be initialised and is used by the Diff::LCS#sdiff -# method. -# -# cbo = Diff::LCS::SDiffCallbacks.new -# Diff::LCS.LCS(seq1, seq2, cbo) -# -# As with the other initialisable callback objects, -# Diff::LCS::SDiffCallbacks can be initialised with a block. As there is no -# "fininishing" to be done, this has no effect on the state of the object. -# -# cbo = Diff::LCS::SDiffCallbacks.new { |tcbo| Diff::LCS.LCS(seq1, seq2, tcbo) } -# -# === Simplified Array Format -# -# The simplified array format used in the example above can be obtained -# with: -# -# require 'pp' -# pp diffs.map { |e| e.to_a } -class Diff::LCS::SDiffCallbacks - # Returns the difference set collected during the diff process. - attr_reader :diffs - - def initialize #:yields self: - @diffs = [] - yield self if block_given? - end - - def match(event) - @diffs << Diff::LCS::ContextChange.simplify(event) - end - - def discard_a(event) - @diffs << Diff::LCS::ContextChange.simplify(event) - end - - def discard_b(event) - @diffs << Diff::LCS::ContextChange.simplify(event) - end - - def change(event) - @diffs << Diff::LCS::ContextChange.simplify(event) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/change.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/change.rb deleted file mode 100644 index 4077095..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/change.rb +++ /dev/null @@ -1,177 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -# Represents a simplistic (non-contextual) change. Represents the removal or -# addition of an element from either the old or the new sequenced -# enumerable. -class Diff::LCS::Change - # The only actions valid for changes are '+' (add), '-' (delete), '=' - # (no change), '!' (changed), '<' (tail changes from first sequence), or - # '>' (tail changes from second sequence). The last two ('<>') are only - # found with Diff::LCS::diff and Diff::LCS::sdiff. - VALID_ACTIONS = %W(+ - = ! > <) - - def self.valid_action?(action) - VALID_ACTIONS.include? action - end - - # Returns the action this Change represents. - attr_reader :action - - # Returns the position of the Change. - attr_reader :position - # Returns the sequence element of the Change. - attr_reader :element - - def initialize(*args) - @action, @position, @element = *args - - unless Diff::LCS::Change.valid_action?(@action) - raise "Invalid Change Action '#{@action}'" - end - raise "Invalid Position Type" unless @position.kind_of? Fixnum - end - - def inspect - to_a.inspect - end - - def to_a - [ @action, @position, @element ] - end - - def self.from_a(arr) - arr = arr.flatten(1) - case arr.size - when 5 - Diff::LCS::ContextChange.new(*(arr[0...5])) - when 3 - Diff::LCS::Change.new(*(arr[0...3])) - else - raise "Invalid change array format provided." - end - end - - include Comparable - - def ==(other) - (self.action == other.action) and - (self.position == other.position) and - (self.element == other.element) - end - - def <=>(other) - r = self.action <=> other.action - r = self.position <=> other.position if r.zero? - r = self.element <=> other.element if r.zero? - r - end - - def adding? - @action == '+' - end - - def deleting? - @action == '-' - end - - def unchanged? - @action == '=' - end - - def changed? - @action == '!' - end - - def finished_a? - @action == '>' - end - - def finished_b? - @action == '<' - end -end - -# Represents a contextual change. Contains the position and values of the -# elements in the old and the new sequenced enumerables as well as the action -# taken. -class Diff::LCS::ContextChange < Diff::LCS::Change - # We don't need these two values. - undef :position - undef :element - - # Returns the old position being changed. - attr_reader :old_position - # Returns the new position being changed. - attr_reader :new_position - # Returns the old element being changed. - attr_reader :old_element - # Returns the new element being changed. - attr_reader :new_element - - def initialize(*args) - @action, @old_position, @old_element, @new_position, @new_element = *args - - unless Diff::LCS::Change.valid_action?(@action) - raise "Invalid Change Action '#{@action}'" - end - unless @old_position.nil? or @old_position.kind_of? Fixnum - raise "Invalid (Old) Position Type" - end - unless @new_position.nil? or @new_position.kind_of? Fixnum - raise "Invalid (New) Position Type" - end - end - - def to_a - [ @action, - [ @old_position, @old_element ], - [ @new_position, @new_element ] - ] - end - - def inspect(*args) - to_a.inspect - end - - def self.from_a(arr) - Diff::LCS::Change.from_a(arr) - end - - # Simplifies a context change for use in some diff callbacks. '<' actions - # are converted to '-' and '>' actions are converted to '+'. - def self.simplify(event) - ea = event.to_a - - case ea[0] - when '-' - ea[2][1] = nil - when '<' - ea[0] = '-' - ea[2][1] = nil - when '+' - ea[1][1] = nil - when '>' - ea[0] = '+' - ea[1][1] = nil - end - - Diff::LCS::ContextChange.from_a(ea) - end - - def ==(other) - (@action == other.action) and - (@old_position == other.old_position) and - (@new_position == other.new_position) and - (@old_element == other.old_element) and - (@new_element == other.new_element) - end - - def <=>(other) - r = @action <=> other.action - r = @old_position <=> other.old_position if r.zero? - r = @new_position <=> other.new_position if r.zero? - r = @old_element <=> other.old_element if r.zero? - r = @new_element <=> other.new_element if r.zero? - r - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/htmldiff.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/htmldiff.rb deleted file mode 100644 index 56b972c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/htmldiff.rb +++ /dev/null @@ -1,149 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'cgi' - -class Diff::LCS::HTMLDiff - class << self - attr_accessor :can_expand_tabs #:nodoc: - end - self.can_expand_tabs = true - - class Callbacks - attr_accessor :output - attr_accessor :match_class - attr_accessor :only_a_class - attr_accessor :only_b_class - - def initialize(output, options = {}) - @output = output - options ||= {} - - @match_class = options[:match_class] || "match" - @only_a_class = options[:only_a_class] || "only_a" - @only_b_class = options[:only_b_class] || "only_b" - end - - def htmlize(element, css_class) - element = " " if element.empty? - %Q|
#{element}
\n| - end - private :htmlize - - # This will be called with both lines are the same - def match(event) - @output << htmlize(event.old_element, :match_class) - end - - # This will be called when there is a line in A that isn't in B - def discard_a(event) - @output << htmlize(event.old_element, :only_a_class) - end - - # This will be called when there is a line in B that isn't in A - def discard_b(event) - @output << htmlize(event.new_element, :only_b_class) - end - end - - DEFAULT_OPTIONS = { - :expand_tabs => nil, - :output => nil, - :css => nil, - :title => nil, - } - - DEFAULT_CSS = <<-CSS -body { margin: 0; } -.diff -{ - border: 1px solid black; - margin: 1em 2em; -} -p -{ - margin-left: 2em; -} -pre -{ - padding-left: 1em; - margin: 0; - font-family: Inconsolata, Consolas, Lucida, Courier, monospaced; - white-space: pre; -} -.match { } -.only_a -{ - background-color: #fdd; - color: red; - text-decoration: line-through; -} -.only_b -{ - background-color: #ddf; - color: blue; - border-left: 3px solid blue -} -h1 { margin-left: 2em; } - CSS - - def initialize(left, right, options = nil) - @left = left - @right = right - @options = options - - @options = DEFAULT_OPTIONS.dup if @options.nil? - end - - def verify_options - @options[:expand_tabs] ||= 4 - @options[:expand_tabs] = 4 if @options[:expand_tabs] < 0 - - @options[:output] ||= $stdout - - @options[:css] ||= DEFAULT_CSS.dup - - @options[:title] ||= "diff" - end - private :verify_options - - attr_reader :options - - def run - verify_options - - if @options[:expand_tabs] > 0 && self.class.can_expand_tabs - formatter = Text::Format.new - formatter.tabstop = @options[:expand_tabs] - - @left = left.map { |line| formatter.expand(line.chomp) } - @right = right.map { |line| formatter.expand(line.chomp) } - end - - @left.map! { |line| CGI.escapeHTML(line.chomp) } - @right.map! { |line| CGI.escapeHTML(line.chomp) } - - @options[:output] << <<-OUTPUT - - - #{@options[:title]} - - - -

#{@options[:title]}

-

Legend: Only in Old  - Only in New

-
- OUTPUT - - callbacks = Callbacks.new(@options[:output]) - Diff::LCS.traverse_sequences(@left, @right, callbacks) - - @options[:output] << <<-OUTPUT -
- - - OUTPUT - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/hunk.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/hunk.rb deleted file mode 100644 index 05c3fb6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/hunk.rb +++ /dev/null @@ -1,276 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'diff/lcs/block' - -# A Hunk is a group of Blocks which overlap because of the context -# surrounding each block. (So if we're not using context, every hunk will -# contain one block.) Used in the diff program (bin/diff). -class Diff::LCS::Hunk - # Create a hunk using references to both the old and new data, as well as - # the piece of data. - def initialize(data_old, data_new, piece, flag_context, file_length_difference) - # At first, a hunk will have just one Block in it - @blocks = [ Diff::LCS::Block.new(piece) ] - if String.method_defined?(:encoding) - @preferred_data_encoding = data_old.fetch(0, data_new.fetch(0,'') ).encoding - end - @data_old = data_old - @data_new = data_new - - before = after = file_length_difference - after += @blocks[0].diff_size - @file_length_difference = after # The caller must get this manually - - # Save the start & end of each array. If the array doesn't exist (e.g., - # we're only adding items in this block), then figure out the line - # number based on the line number of the other file and the current - # difference in file lengths. - if @blocks[0].remove.empty? - a1 = a2 = nil - else - a1 = @blocks[0].remove[0].position - a2 = @blocks[0].remove[-1].position - end - - if @blocks[0].insert.empty? - b1 = b2 = nil - else - b1 = @blocks[0].insert[0].position - b2 = @blocks[0].insert[-1].position - end - - @start_old = a1 || (b1 - before) - @start_new = b1 || (a1 + before) - @end_old = a2 || (b2 - after) - @end_new = b2 || (a2 + after) - - self.flag_context = flag_context - end - - attr_reader :blocks - attr_reader :start_old, :start_new - attr_reader :end_old, :end_new - attr_reader :file_length_difference - - # Change the "start" and "end" fields to note that context should be added - # to this hunk. - attr_accessor :flag_context - undef :flag_context=; - def flag_context=(context) #:nodoc: - return if context.nil? or context.zero? - - add_start = (context > @start_old) ? @start_old : context - @start_old -= add_start - @start_new -= add_start - - if (@end_old + context) > @data_old.size - add_end = @data_old.size - @end_old - else - add_end = context - end - @end_old += add_end - @end_new += add_end - end - - # Merges this hunk and the provided hunk together if they overlap. Returns - # a truthy value so that if there is no overlap, you can know the merge - # was skipped. - def merge(hunk) - if overlaps?(hunk) - @start_old = hunk.start_old - @start_new = hunk.start_new - blocks.unshift(*hunk.blocks) - else - nil - end - end - alias_method :unshift, :merge - - # Determines whether there is an overlap between this hunk and the - # provided hunk. This will be true if the difference between the two hunks - # start or end positions is within one position of each other. - def overlaps?(hunk) - hunk and (((@start_old - hunk.end_old) <= 1) or - ((@start_new - hunk.end_new) <= 1)) - end - - # Returns a diff string based on a format. - def diff(format) - case format - when :old - old_diff - when :unified - unified_diff - when :context - context_diff - when :ed - self - when :reverse_ed, :ed_finish - ed_diff(format) - else - raise "Unknown diff format #{format}." - end - end - - # Note that an old diff can't have any context. Therefore, we know that - # there's only one block in the hunk. - def old_diff - warn "Expecting only one block in an old diff hunk!" if @blocks.size > 1 - op_act = { "+" => 'a', "-" => 'd', "!" => "c" } - - block = @blocks[0] - - # Calculate item number range. Old diff range is just like a context - # diff range, except the ranges are on one line with the action between - # them. - s = encode("#{context_range(:old)}#{op_act[block.op]}#{context_range(:new)}\n") - # If removing anything, just print out all the remove lines in the hunk - # which is just all the remove lines in the block. - @data_old[@start_old .. @end_old].each { |e| s << encode("< ") + e + encode("\n") } unless block.remove.empty? - s << encode("---\n") if block.op == "!" - @data_new[@start_new .. @end_new].each { |e| s << encode("> ") + e + encode("\n") } unless block.insert.empty? - s - end - private :old_diff - - def unified_diff - # Calculate item number range. - s = encode("@@ -#{unified_range(:old)} +#{unified_range(:new)} @@\n") - - # Outlist starts containing the hunk of the old file. Removing an item - # just means putting a '-' in front of it. Inserting an item requires - # getting it from the new file and splicing it in. We splice in - # +num_added+ items. Remove blocks use +num_added+ because splicing - # changed the length of outlist. - # - # We remove +num_removed+ items. Insert blocks use +num_removed+ - # because their item numbers -- corresponding to positions in the NEW - # file -- don't take removed items into account. - lo, hi, num_added, num_removed = @start_old, @end_old, 0, 0 - - outlist = @data_old[lo .. hi].map { |e| e.insert(0, encode(' ')) } - - @blocks.each do |block| - block.remove.each do |item| - op = item.action.to_s # - - offset = item.position - lo + num_added - outlist[offset][0, 1] = encode(op) - num_removed += 1 - end - block.insert.each do |item| - op = item.action.to_s # + - offset = item.position - @start_new + num_removed - outlist[offset, 0] = encode(op) + @data_new[item.position] - num_added += 1 - end - end - - s << outlist.join(encode("\n")) - end - private :unified_diff - - def context_diff - s = encode("***************\n") - s << encode("*** #{context_range(:old)} ****\n") - r = context_range(:new) - - # Print out file 1 part for each block in context diff format if there - # are any blocks that remove items - lo, hi = @start_old, @end_old - removes = @blocks.select { |e| not e.remove.empty? } - if removes - outlist = @data_old[lo .. hi].map { |e| e.insert(0, encode(' ')) } - - removes.each do |block| - block.remove.each do |item| - outlist[item.position - lo][0, 1] = encode(block.op) # - or ! - end - end - s << outlist.join("\n") - end - - s << encode("\n--- #{r} ----\n") - lo, hi = @start_new, @end_new - inserts = @blocks.select { |e| not e.insert.empty? } - if inserts - outlist = @data_new[lo .. hi].collect { |e| e.insert(0, encode(' ')) } - inserts.each do |block| - block.insert.each do |item| - outlist[item.position - lo][0, 1] = encode(block.op) # + or ! - end - end - s << outlist.join("\n") - end - s - end - private :context_diff - - def ed_diff(format) - op_act = { "+" => 'a', "-" => 'd', "!" => "c" } - warn "Expecting only one block in an old diff hunk!" if @blocks.size > 1 - - if format == :reverse_ed - s = encode("#{op_act[@blocks[0].op]}#{context_range(:old)}\n") - else - s = encode("#{context_range(:old, ' ')}#{op_act[@blocks[0].op]}\n") - end - - unless @blocks[0].insert.empty? - @data_new[@start_new .. @end_new].each { |e| s << e + encode("\n") } - s << encode(".\n") - end - s - end - private :ed_diff - - # Generate a range of item numbers to print. Only print 1 number if the - # range has only one item in it. Otherwise, it's 'start,end' - def context_range(mode, op = ',') - case mode - when :old - s, e = (@start_old + 1), (@end_old + 1) - when :new - s, e = (@start_new + 1), (@end_new + 1) - end - - (s < e) ? "#{s}#{op}#{e}" : "#{e}" - end - private :context_range - - # Generate a range of item numbers to print for unified diff. Print number - # where block starts, followed by number of lines in the block - # (don't print number of lines if it's 1) - def unified_range(mode) - case mode - when :old - s, e = (@start_old + 1), (@end_old + 1) - when :new - s, e = (@start_new + 1), (@end_new + 1) - end - - length = e - s + 1 - first = (length < 2) ? e : s # "strange, but correct" - (length == 1) ? "#{first}" : "#{first},#{length}" - end - private :unified_range - - if String.method_defined?(:encoding) - def encode(literal, target_encoding = @preferred_data_encoding) - literal.encode target_encoding - end - - def encode_as(string, *args) - args.map { |arg| arg.encode(string.encoding) } - end - else - def encode(literal, target_encoding = nil) - literal - end - def encode_as(string, *args) - args - end - end - - private :encode - private :encode_as -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/internals.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/internals.rb deleted file mode 100644 index 9d9e3f3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/internals.rb +++ /dev/null @@ -1,301 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -class << Diff::LCS - def diff_traversal(method, seq1, seq2, callbacks, &block) - callbacks = callbacks_for(callbacks) - case method - when :diff - traverse_sequences(seq1, seq2, callbacks) - when :sdiff - traverse_balanced(seq1, seq2, callbacks) - end - callbacks.finish if callbacks.respond_to? :finish - - if block - callbacks.diffs.map do |hunk| - if hunk.kind_of? Array - hunk.map { |hunk_block| block[hunk_block] } - else - block[hunk] - end - end - else - callbacks.diffs - end - end - private :diff_traversal -end - -module Diff::LCS::Internals # :nodoc: -end - -class << Diff::LCS::Internals - # Compute the longest common subsequence between the sequenced - # Enumerables +a+ and +b+. The result is an array whose contents is such - # that - # - # result = Diff::LCS::Internals.lcs(a, b) - # result.each_with_index do |e, i| - # assert_equal(a[i], b[e]) unless e.nil? - # end - def lcs(a, b) - a_start = b_start = 0 - a_finish = a.size - 1 - b_finish = b.size - 1 - vector = [] - - # Prune off any common elements at the beginning... - while ((a_start <= a_finish) and (b_start <= b_finish) and - (a[a_start] == b[b_start])) - vector[a_start] = b_start - a_start += 1 - b_start += 1 - end - b_start = a_start - - # Now the end... - while ((a_start <= a_finish) and (b_start <= b_finish) and - (a[a_finish] == b[b_finish])) - vector[a_finish] = b_finish - a_finish -= 1 - b_finish -= 1 - end - - # Now, compute the equivalence classes of positions of elements. - b_matches = position_hash(b, b_start..b_finish) - - thresh = [] - links = [] - string = a.kind_of?(String) - - (a_start .. a_finish).each do |i| - ai = string ? a[i, 1] : a[i] - bm = b_matches[ai] - k = nil - bm.reverse_each do |j| - if k and (thresh[k] > j) and (thresh[k - 1] < j) - thresh[k] = j - else - k = replace_next_larger(thresh, j, k) - end - links[k] = [ (k > 0) ? links[k - 1] : nil, i, j ] unless k.nil? - end - end - - unless thresh.empty? - link = links[thresh.size - 1] - while not link.nil? - vector[link[1]] = link[2] - link = link[0] - end - end - - vector - end - - # This method will analyze the provided patchset to provide a - # single-pass normalization (conversion of the array form of - # Diff::LCS::Change objects to the object form of same) and detection of - # whether the patchset represents changes to be made. - def analyze_patchset(patchset, depth = 0) - raise "Patchset too complex" if depth > 1 - - has_changes = false - - # Format: - # [ # patchset - # # hunk (change) - # [ # hunk - # # change - # ] - # ] - - patchset = patchset.map do |hunk| - case hunk - when Diff::LCS::Change - has_changes ||= !hunk.unchanged? - hunk - when Array - # Detect if the 'hunk' is actually an array-format - # Change object. - if Diff::LCS::Change.valid_action? hunk[0] - hunk = Diff::LCS::Change.from_a(hunk) - has_changes ||= !hunk.unchanged? - hunk - else - with_changes, hunk = analyze_patchset(hunk, depth + 1) - has_changes ||= with_changes - hunk.flatten - end - else - raise ArgumentError, "Cannot normalise a hunk of class #{hunk.class}." - end - end - - [ has_changes, patchset.flatten(1) ] - end - - # Examine the patchset and the source to see in which direction the - # patch should be applied. - # - # WARNING: By default, this examines the whole patch, so this could take - # some time. This also works better with Diff::LCS::ContextChange or - # Diff::LCS::Change as its source, as an array will cause the creation - # of one of the above. - # - # Note: This will be deprecated as a public function in a future release. - def intuit_diff_direction(src, patchset, limit = nil) - string = src.kind_of?(String) - count = left_match = left_miss = right_match = right_miss = 0 - - patchset.each do |change| - count += 1 - - case change - when Diff::LCS::ContextChange - le = string ? src[change.old_position, 1] : src[change.old_position] - re = string ? src[change.new_position, 1] : src[change.new_position] - - case change.action - when '-' # Remove details from the old string - if le == change.old_element - left_match += 1 - else - left_miss += 1 - end - when '+' - if re == change.new_element - right_match += 1 - else - right_miss += 1 - end - when '=' - left_miss += 1 if le != change.old_element - right_miss += 1 if re != change.new_element - when '!' - if le == change.old_element - left_match += 1 - else - if re == change.new_element - right_match += 1 - else - left_miss += 1 - right_miss += 1 - end - end - end - when Diff::LCS::Change - # With a simplistic change, we can't tell the difference between - # the left and right on '!' actions, so we ignore those. On '=' - # actions, if there's a miss, we miss both left and right. - element = string ? src[change.position, 1] : src[change.position] - - case change.action - when '-' - if element == change.element - left_match += 1 - else - left_miss += 1 - end - when '+' - if element == change.element - right_match += 1 - else - right_miss += 1 - end - when '=' - if element != change.element - left_miss += 1 - right_miss += 1 - end - end - end - - break if (not limit.nil?) && (count > limit) - end - - no_left = (left_match == 0) && (left_miss > 0) - no_right = (right_match == 0) && (right_miss > 0) - - case [no_left, no_right] - when [false, true] - :patch - when [true, false] - :unpatch - else - case left_match <=> right_match - when 1 - :patch - when -1 - :unpatch - else - raise "The provided patchset does not appear to apply to the provided value as either source or destination value." - end - end - end - - # Find the place at which +value+ would normally be inserted into the - # Enumerable. If that place is already occupied by +value+, do nothing - # and return +nil+. If the place does not exist (i.e., it is off the end - # of the Enumerable), add it to the end. Otherwise, replace the element - # at that point with +value+. It is assumed that the Enumerable's values - # are numeric. - # - # This operation preserves the sort order. - def replace_next_larger(enum, value, last_index = nil) - # Off the end? - if enum.empty? or (value > enum[-1]) - enum << value - return enum.size - 1 - end - - # Binary search for the insertion point - last_index ||= enum.size - first_index = 0 - while (first_index <= last_index) - i = (first_index + last_index) >> 1 - - found = enum[i] - - if value == found - return nil - elsif value > found - first_index = i + 1 - else - last_index = i - 1 - end - end - - # The insertion point is in first_index; overwrite the next larger - # value. - enum[first_index] = value - return first_index - end - private :replace_next_larger - - # If +vector+ maps the matching elements of another collection onto this - # Enumerable, compute the inverse of +vector+ that maps this Enumerable - # onto the collection. (Currently unused.) - def inverse_vector(a, vector) - inverse = a.dup - (0...vector.size).each do |i| - inverse[vector[i]] = i unless vector[i].nil? - end - inverse - end - private :inverse_vector - - # Returns a hash mapping each element of an Enumerable to the set of - # positions it occupies in the Enumerable, optionally restricted to the - # elements specified in the range of indexes specified by +interval+. - def position_hash(enum, interval) - string = enum.kind_of?(String) - hash = Hash.new { |h, k| h[k] = [] } - interval.each do |i| - k = string ? enum[i, 1] : enum[i] - hash[k] << i - end - hash - end - private :position_hash -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/ldiff.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/ldiff.rb deleted file mode 100644 index fff325a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/ldiff.rb +++ /dev/null @@ -1,195 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'optparse' -require 'ostruct' -require 'diff/lcs/hunk' - -# == ldiff Usage -# ldiff [options] oldfile newfile -# -# -c:: Displays a context diff with 3 lines of context. -# -C [LINES], --context [LINES]:: Displays a context diff with LINES lines of context. Default 3 lines. -# -u:: Displays a unified diff with 3 lines of context. -# -U [LINES], --unified [LINES]:: Displays a unified diff with LINES lines of context. Default 3 lines. -# -e:: Creates an 'ed' script to change oldfile to newfile. -# -f:: Creates an 'ed' script to change oldfile to newfile in reverse order. -# -a, --text:: Treats the files as text and compares them line-by-line, even if they do not seem to be text. -# --binary:: Treats the files as binary. -# -q, --brief:: Reports only whether or not the files differ, not the details. -# --help:: Shows the command-line help. -# --version:: Shows the version of Diff::LCS. -# -# By default, runs produces an "old-style" diff, with output like UNIX diff. -# -# == Copyright -# Copyright © 2004 Austin Ziegler -# -# Part of Diff::LCS -# Austin Ziegler -# -# This program is free software. It may be redistributed and/or modified under -# the terms of the GPL version 2 (or later), the Perl Artistic licence, or the -# Ruby licence. -module Diff::LCS::Ldiff - BANNER = <<-COPYRIGHT -ldiff #{Diff::LCS::VERSION} - Copyright 2004-2013 Austin Ziegler - - Part of Diff::LCS. - http://rubyforge.org/projects/ruwiki/ - - Austin Ziegler - - This program is free software. It may be redistributed and/or modified under - the terms of the GPL version 2 (or later), the Perl Artistic licence, or the - MIT licence. - COPYRIGHT -end - -class << Diff::LCS::Ldiff - attr_reader :format, :lines #:nodoc: - attr_reader :file_old, :file_new #:nodoc: - attr_reader :data_old, :data_new #:nodoc: - - def run(args, input = $stdin, output = $stdout, error = $stderr) #:nodoc: - @binary = nil - - args.options do |o| - o.banner = "Usage: #{File.basename($0)} [options] oldfile newfile" - o.separator "" - o.on('-c', '-C', '--context [LINES]', Numeric, 'Displays a context diff with LINES lines', 'of context. Default 3 lines.') do |ctx| - @format = :context - @lines = ctx || 3 - end - o.on('-u', '-U', '--unified [LINES]', Numeric, 'Displays a unified diff with LINES lines', 'of context. Default 3 lines.') do |ctx| - @format = :unified - @lines = ctx || 3 - end - o.on('-e', 'Creates an \'ed\' script to change', 'oldfile to newfile.') do |ctx| - @format = :ed - end - o.on('-f', 'Creates an \'ed\' script to change', 'oldfile to newfile in reverse order.') do |ctx| - @format = :reverse_ed - end - o.on('-a', '--text', 'Treat the files as text and compare them', 'line-by-line, even if they do not seem', 'to be text.') do |txt| - @binary = false - end - o.on('--binary', 'Treats the files as binary.') do |bin| - @binary = true - end - o.on('-q', '--brief', 'Report only whether or not the files', 'differ, not the details.') do |ctx| - @format = :report - end - o.on_tail('--help', 'Shows this text.') do - error << o - return 0 - end - o.on_tail('--version', 'Shows the version of Diff::LCS.') do - error << BANNER - return 0 - end - o.on_tail "" - o.on_tail 'By default, runs produces an "old-style" diff, with output like UNIX diff.' - o.parse! - end - - unless args.size == 2 - error << args.options - return 127 - end - - # Defaults are for old-style diff - @format ||= :old - @lines ||= 0 - - file_old, file_new = *ARGV - - case @format - when :context - char_old = '*' * 3 - char_new = '-' * 3 - when :unified - char_old = '-' * 3 - char_new = '+' * 3 - end - - # After we've read up to a certain point in each file, the number of - # items we've read from each file will differ by FLD (could be 0). - file_length_difference = 0 - - if @binary.nil? or @binary - data_old = IO::read(file_old) - data_new = IO::read(file_new) - - # Test binary status - if @binary.nil? - old_txt = data_old[0...4096].scan(/\0/).empty? - new_txt = data_new[0...4096].scan(/\0/).empty? - @binary = (not old_txt) or (not new_txt) - old_txt = new_txt = nil - end - - unless @binary - data_old = data_old.split($/).map { |e| e.chomp } - data_new = data_new.split($/).map { |e| e.chomp } - end - else - data_old = IO::readlines(file_old).map { |e| e.chomp } - data_new = IO::readlines(file_new).map { |e| e.chomp } - end - - # diff yields lots of pieces, each of which is basically a Block object - if @binary - diffs = (data_old == data_new) - else - diffs = Diff::LCS.diff(data_old, data_new) - diffs = nil if diffs.empty? - end - - return 0 unless diffs - - if @format == :report - output << "Files #{file_old} and #{file_new} differ\n" - return 1 - end - - if (@format == :unified) or (@format == :context) - ft = File.stat(file_old).mtime.localtime.strftime('%Y-%m-%d %H:%M:%S.%N %z') - puts "#{char_old} #{file_old}\t#{ft}" - ft = File.stat(file_new).mtime.localtime.strftime('%Y-%m-%d %H:%M:%S.%N %z') - puts "#{char_new} #{file_new}\t#{ft}" - end - - # Loop over hunks. If a hunk overlaps with the last hunk, join them. - # Otherwise, print out the old one. - oldhunk = hunk = nil - - if @format == :ed - real_output = output - output = [] - end - - diffs.each do |piece| - begin - hunk = Diff::LCS::Hunk.new(data_old, data_new, piece, @lines, - file_length_difference) - file_length_difference = hunk.file_length_difference - - next unless oldhunk - next if (@lines > 0) and hunk.merge(oldhunk) - - output << oldhunk.diff(@format) << "\n" - ensure - oldhunk = hunk - end - end - - output << oldhunk.diff(@format) << "\n" - - if @format == :ed - output.reverse_each { |e| real_output << e.diff(:ed_finish) } - end - - return 1 - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/string.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/string.rb deleted file mode 100644 index 8545bcf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/lib/diff/lcs/string.rb +++ /dev/null @@ -1,5 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -class String - include Diff::LCS -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/change_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/change_spec.rb deleted file mode 100644 index dfe385f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/change_spec.rb +++ /dev/null @@ -1,65 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe Diff::LCS::Change do - describe "an add" do - subject { described_class.new('+', 0, 'element') } - it { should_not be_deleting } - it { should be_adding } - it { should_not be_unchanged } - it { should_not be_changed } - it { should_not be_finished_a } - it { should_not be_finished_b } - end - - describe "a delete" do - subject { described_class.new('-', 0, 'element') } - it { should be_deleting } - it { should_not be_adding } - it { should_not be_unchanged } - it { should_not be_changed } - it { should_not be_finished_a } - it { should_not be_finished_b } - end - - describe "an unchanged" do - subject { described_class.new('=', 0, 'element') } - it { should_not be_deleting } - it { should_not be_adding } - it { should be_unchanged } - it { should_not be_changed } - it { should_not be_finished_a } - it { should_not be_finished_b } - end - - describe "a changed" do - subject { described_class.new('!', 0, 'element') } - it { should_not be_deleting } - it { should_not be_adding } - it { should_not be_unchanged } - it { should be_changed } - it { should_not be_finished_a } - it { should_not be_finished_b } - end - - describe "a finished_a" do - subject { described_class.new('>', 0, 'element') } - it { should_not be_deleting } - it { should_not be_adding } - it { should_not be_unchanged } - it { should_not be_changed } - it { should be_finished_a } - it { should_not be_finished_b } - end - - describe "a finished_b" do - subject { described_class.new('<', 0, 'element') } - it { should_not be_deleting } - it { should_not be_adding } - it { should_not be_unchanged } - it { should_not be_changed } - it { should_not be_finished_a } - it { should be_finished_b } - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/diff_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/diff_spec.rb deleted file mode 100644 index 95d7b40..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/diff_spec.rb +++ /dev/null @@ -1,47 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe "Diff::LCS.diff" do - include Diff::LCS::SpecHelper::Matchers - - it "should correctly diff seq1 to seq2" do - diff_s1_s2 = Diff::LCS.diff(seq1, seq2) - change_diff(correct_forward_diff).should == diff_s1_s2 - end - - it "should correctly diff seq2 to seq1" do - diff_s2_s1 = Diff::LCS.diff(seq2, seq1) - change_diff(correct_backward_diff).should == diff_s2_s1 - end - - it "should correctly diff against an empty sequence" do - diff = Diff::LCS.diff(word_sequence, []) - correct_diff = [ - [ [ '-', 0, 'abcd' ], - [ '-', 1, 'efgh' ], - [ '-', 2, 'ijkl' ], - [ '-', 3, 'mnopqrstuvwxyz' ] ] - ] - - change_diff(correct_diff).should == diff - - diff = Diff::LCS.diff([], word_sequence) - correct_diff.each { |hunk| hunk.each { |change| change[0] = '+' } } - change_diff(correct_diff).should == diff - end - - it "should correctly diff 'xx' and 'xaxb'" do - left = 'xx' - right = 'xaxb' - Diff::LCS.patch(left, Diff::LCS.diff(left, right)).should == right - end - - it "should return an empty diff with (hello, hello)" do - Diff::LCS.diff(hello, hello).should == [] - end - - it "should return an empty diff with (hello_ary, hello_ary)" do - Diff::LCS.diff(hello_ary, hello_ary).should == [] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/hunk_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/hunk_spec.rb deleted file mode 100644 index dc6f532..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/hunk_spec.rb +++ /dev/null @@ -1,72 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -def h(v) - v.to_s.bytes.to_a.map { |e| "%02x" % e }.join -end - -describe "Diff::LCS::Hunk" do - if String.method_defined?(:encoding) - - let(:old_data) { ["Tu avec carté {count} itém has".encode('UTF-16LE')] } - let(:new_data) { ["Tu avec carte {count} item has".encode('UTF-16LE')] } - let(:pieces) { Diff::LCS.diff old_data, new_data } - let(:hunk) { Diff::LCS::Hunk.new(old_data, new_data, pieces[0], 3, 0) } - - it 'should be able to produce a unified diff from the two pieces' do - expected = (<<-EOD.gsub(/^\s+/,'').encode('UTF-16LE').chomp) - @@ -1,2 +1,2 @@ - -Tu avec carté {count} itém has - +Tu avec carte {count} item has - EOD - expect(hunk.diff(:unified).to_s == expected).to eql true - end - - it 'should be able to produce a context diff from the two pieces' do - expected = (<<-EOD.gsub(/^\s+/,'').encode('UTF-16LE').chomp) - *************** - *** 1,2 **** - !Tu avec carté {count} itém has - --- 1,2 ---- - !Tu avec carte {count} item has - EOD - - expect(hunk.diff(:context).to_s == expected).to eql true - end - - it 'should be able to produce an old diff from the two pieces' do - expected = (<<-EOD.gsub(/^ +/,'').encode('UTF-16LE').chomp) - 1,2c1,2 - < Tu avec carté {count} itém has - --- - > Tu avec carte {count} item has - - EOD - expect(hunk.diff(:old).to_s == expected).to eql true - end - - it 'should be able to produce a reverse ed diff from the two pieces' do - expected = (<<-EOD.gsub(/^ +/,'').encode('UTF-16LE').chomp) - c1,2 - Tu avec carte {count} item has - . - - EOD - expect(hunk.diff(:reverse_ed).to_s == expected).to eql true - end - - context 'with empty first data set' do - let(:old_data) { [] } - - it 'should be able to produce a unified diff' do - expected = (<<-EOD.gsub(/^\s+/,'').encode('UTF-16LE').chomp) - @@ -1 +1,2 @@ - +Tu avec carte {count} item has - EOD - expect(hunk.diff(:unified).to_s == expected).to eql true - end - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/issues_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/issues_spec.rb deleted file mode 100644 index c3d8f87..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/issues_spec.rb +++ /dev/null @@ -1,24 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe "Diff::LCS Issues" do - include Diff::LCS::SpecHelper::Matchers - - it "should not fail to provide a simple patchset (issue 1)" do - s1, s2 = *%W(aX bXaX) - correct_forward_diff = [ - [ [ '+', 0, 'b' ], - [ '+', 1, 'X' ] ], - ] - - diff_s1_s2 = Diff::LCS.diff(s1, s2) - change_diff(correct_forward_diff).should == diff_s1_s2 - expect do - Diff::LCS.patch(s1, diff_s1_s2).should == s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - expect do - Diff::LCS.patch(s2, diff_s1_s2).should == s1 - end.to_not raise_error(RuntimeError, /provided patchset/) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/lcs_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/lcs_spec.rb deleted file mode 100644 index 205d563..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/lcs_spec.rb +++ /dev/null @@ -1,54 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe "Diff::LCS::Internals.lcs" do - include Diff::LCS::SpecHelper::Matchers - - it "should return a meaningful LCS array with (seq1, seq2)" do - res = Diff::LCS::Internals.lcs(seq1, seq2) - # The result of the LCS (less the +nil+ values) must be as long as the - # correct result. - res.compact.size.should == correct_lcs.size - res.should correctly_map_sequence(seq1).to_other_sequence(seq2) - - # Compact these transformations and they should be the correct LCS. - x_seq1 = (0...res.size).map { |ix| res[ix] ? seq1[ix] : nil }.compact - x_seq2 = (0...res.size).map { |ix| res[ix] ? seq2[res[ix]] : nil }.compact - - x_seq1.should == correct_lcs - x_seq2.should == correct_lcs - end - - it "should return all indexes with (hello, hello)" do - Diff::LCS::Internals.lcs(hello, hello).should == (0...hello.size).to_a - end - - it "should return all indexes with (hello_ary, hello_ary)" do - Diff::LCS::Internals.lcs(hello_ary, hello_ary).should == (0...hello_ary.size).to_a - end -end - -describe "Diff::LCS.LCS" do - include Diff::LCS::SpecHelper::Matchers - - it "should return the correct compacted values from Diff::LCS.LCS" do - res = Diff::LCS.LCS(seq1, seq2) - res.should == correct_lcs - res.compact.should == res - end - - it "should be transitive" do - res = Diff::LCS.LCS(seq2, seq1) - res.should == correct_lcs - res.compact.should == res - end - - it "should return %W(h e l l o) with (hello, hello)" do - Diff::LCS.LCS(hello, hello).should == hello.split(//) - end - - it "should return hello_ary with (hello_ary, hello_ary)" do - Diff::LCS.LCS(hello_ary, hello_ary).should == hello_ary - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/patch_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/patch_spec.rb deleted file mode 100644 index 0fc9160..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/patch_spec.rb +++ /dev/null @@ -1,414 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe "Diff::LCS.patch" do - include Diff::LCS::SpecHelper::Matchers - - shared_examples "patch sequences correctly" do - it "should correctly patch left-to-right (patch autodiscovery)" do - Diff::LCS.patch(s1, patch_set).should == s2 - end - - it "should correctly patch left-to-right (explicit patch)" do - Diff::LCS.patch(s1, patch_set, :patch).should == s2 - Diff::LCS.patch!(s1, patch_set).should == s2 - end - - it "should correctly patch right-to-left (unpatch autodiscovery)" do - Diff::LCS.patch(s2, patch_set).should == s1 - end - - it "should correctly patch right-to-left (explicit unpatch)" do - Diff::LCS.patch(s2, patch_set, :unpatch).should == s1 - Diff::LCS.unpatch!(s2, patch_set).should == s1 - end - end - - describe "using a Diff::LCS.diff patchset" do - describe "an empty patchset returns the source" do - it "works on a string (hello)" do - Diff::LCS::patch(hello, Diff::LCS.diff(hello, hello)).should == hello - end - - it "works on an array %W(h e l l o)" do - Diff::LCS::patch(hello_ary, Diff::LCS.diff(hello_ary, hello_ary)).should == hello_ary - end - end - - describe "with default diff callbacks (DiffCallbacks)" do - describe "forward (s1 -> s2)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq1 } - let(:s2) { seq2 } - let(:patch_set) { Diff::LCS.diff(seq1, seq2) } - end - end - - describe "reverse (s2 -> s1)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq2 } - let(:s2) { seq1 } - let(:patch_set) { Diff::LCS.diff(seq2, seq1) } - end - end - end - - describe "with context diff callbacks (ContextDiffCallbacks)" do - describe "forward (s1 -> s2)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq1 } - let(:s2) { seq2 } - let(:patch_set) { - Diff::LCS.diff(seq1, seq2, Diff::LCS::ContextDiffCallbacks) - } - end - end - - describe "reverse (s2 -> s1)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq2 } - let(:s2) { seq1 } - let(:patch_set) { - Diff::LCS.diff(seq2, seq1, Diff::LCS::ContextDiffCallbacks) - } - end - end - end - - describe "with sdiff callbacks (SDiffCallbacks)" do - describe "forward (s1 -> s2)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq1 } - let(:s2) { seq2 } - let(:patch_set) { - Diff::LCS.diff(seq1, seq2, Diff::LCS::SDiffCallbacks) - } - end - end - - describe "reverse (s2 -> s1)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq2 } - let(:s2) { seq1 } - let(:patch_set) { - Diff::LCS.diff(seq2, seq1, Diff::LCS::SDiffCallbacks) - } - end - end - end - end - - describe "using a Diff::LCS.sdiff patchset" do - describe "an empty patchset returns the source" do - it "works on a string (hello)" do - Diff::LCS::patch(hello, Diff::LCS.sdiff(hello, hello)).should == hello - end - - it "works on an array %W(h e l l o)" do - Diff::LCS::patch(hello_ary, Diff::LCS.sdiff(hello_ary, hello_ary)).should == hello_ary - end - end - - describe "with default diff callbacks (DiffCallbacks)" do - describe "forward (s1 -> s2)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq1 } - let(:s2) { seq2 } - let(:patch_set) { - Diff::LCS.sdiff(seq1, seq2, Diff::LCS::DiffCallbacks) - } - end - end - - describe "reverse (s2 -> s1)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq2 } - let(:s2) { seq1 } - let(:patch_set) { - Diff::LCS.sdiff(seq2, seq1, Diff::LCS::DiffCallbacks) - } - end - end - end - - describe "with context diff callbacks (DiffCallbacks)" do - describe "forward (s1 -> s2)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq1 } - let(:s2) { seq2 } - let(:patch_set) { - Diff::LCS.sdiff(seq1, seq2, Diff::LCS::ContextDiffCallbacks) - } - end - end - - describe "reverse (s2 -> s1)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq2 } - let(:s2) { seq1 } - let(:patch_set) { - Diff::LCS.sdiff(seq2, seq1, Diff::LCS::ContextDiffCallbacks) - } - end - end - end - - describe "with sdiff callbacks (SDiffCallbacks)" do - describe "forward (s1 -> s2)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq1 } - let(:s2) { seq2 } - let(:patch_set) { Diff::LCS.sdiff(seq1, seq2) } - end - end - - describe "reverse (s2 -> s1)" do - it_has_behavior "patch sequences correctly" do - let(:s1) { seq2 } - let(:s2) { seq1 } - let(:patch_set) { Diff::LCS.sdiff(seq2, seq1) } - end - end - end - end - - # Note: because of the error in autodiscovery ("does not autodiscover s1 - # to s2 patches"), this cannot use the "patch sequences correctly" shared - # set. Once the bug in autodiscovery is fixed, this can be converted as - # above. - describe "fix bug 891: patchsets do not contain the last equal part" do - before(:each) do - @s1 = %w(a b c d e f g h i j k) - @s2 = %w(a b c d D e f g h i j k) - end - - describe "using Diff::LCS.diff with default diff callbacks" do - before(:each) do - @patch_set_s1_s2 = Diff::LCS.diff(@s1, @s2) - @patch_set_s2_s1 = Diff::LCS.diff(@s2, @s1) - end - - it "should autodiscover s1 to s2 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s1_s2).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s2_s1).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 the left-to-right patches" do - Diff::LCS.patch(@s2, @patch_set_s2_s1).should == @s1 - Diff::LCS.patch(@s2, @patch_set_s1_s2).should == @s1 - end - - it "should correctly patch left-to-right (explicit patch)" do - Diff::LCS.patch(@s1, @patch_set_s1_s2, :patch).should == @s2 - Diff::LCS.patch(@s2, @patch_set_s2_s1, :patch).should == @s1 - Diff::LCS.patch!(@s1, @patch_set_s1_s2).should == @s2 - Diff::LCS.patch!(@s2, @patch_set_s2_s1).should == @s1 - end - - it "should correctly patch right-to-left (explicit unpatch)" do - Diff::LCS.patch(@s2, @patch_set_s1_s2, :unpatch).should == @s1 - Diff::LCS.patch(@s1, @patch_set_s2_s1, :unpatch).should == @s2 - Diff::LCS.unpatch!(@s2, @patch_set_s1_s2).should == @s1 - Diff::LCS.unpatch!(@s1, @patch_set_s2_s1).should == @s2 - end - end - - describe "using Diff::LCS.diff with context diff callbacks" do - before(:each) do - @patch_set_s1_s2 = Diff::LCS.diff(@s1, @s2, Diff::LCS::ContextDiffCallbacks) - @patch_set_s2_s1 = Diff::LCS.diff(@s2, @s1, Diff::LCS::ContextDiffCallbacks) - end - - it "should autodiscover s1 to s2 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s1_s2).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s2_s1).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 the left-to-right patches" do - Diff::LCS.patch(@s2, @patch_set_s2_s1).should == @s1 - Diff::LCS.patch(@s2, @patch_set_s1_s2).should == @s1 - end - - it "should correctly patch left-to-right (explicit patch)" do - Diff::LCS.patch(@s1, @patch_set_s1_s2, :patch).should == @s2 - Diff::LCS.patch(@s2, @patch_set_s2_s1, :patch).should == @s1 - Diff::LCS.patch!(@s1, @patch_set_s1_s2).should == @s2 - Diff::LCS.patch!(@s2, @patch_set_s2_s1).should == @s1 - end - - it "should correctly patch right-to-left (explicit unpatch)" do - Diff::LCS.patch(@s2, @patch_set_s1_s2, :unpatch).should == @s1 - Diff::LCS.patch(@s1, @patch_set_s2_s1, :unpatch).should == @s2 - Diff::LCS.unpatch!(@s2, @patch_set_s1_s2).should == @s1 - Diff::LCS.unpatch!(@s1, @patch_set_s2_s1).should == @s2 - end - end - - describe "using Diff::LCS.diff with sdiff callbacks" do - before(:each) do - @patch_set_s1_s2 = Diff::LCS.diff(@s1, @s2, Diff::LCS::SDiffCallbacks) - @patch_set_s2_s1 = Diff::LCS.diff(@s2, @s1, Diff::LCS::SDiffCallbacks) - end - - it "should autodiscover s1 to s2 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s1_s2).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s2_s1).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 the left-to-right patches" do - Diff::LCS.patch(@s2, @patch_set_s2_s1).should == @s1 - Diff::LCS.patch(@s2, @patch_set_s1_s2).should == @s1 - end - - it "should correctly patch left-to-right (explicit patch)" do - Diff::LCS.patch(@s1, @patch_set_s1_s2, :patch).should == @s2 - Diff::LCS.patch(@s2, @patch_set_s2_s1, :patch).should == @s1 - Diff::LCS.patch!(@s1, @patch_set_s1_s2).should == @s2 - Diff::LCS.patch!(@s2, @patch_set_s2_s1).should == @s1 - end - - it "should correctly patch right-to-left (explicit unpatch)" do - Diff::LCS.patch(@s2, @patch_set_s1_s2, :unpatch).should == @s1 - Diff::LCS.patch(@s1, @patch_set_s2_s1, :unpatch).should == @s2 - Diff::LCS.unpatch!(@s2, @patch_set_s1_s2).should == @s1 - Diff::LCS.unpatch!(@s1, @patch_set_s2_s1).should == @s2 - end - end - - describe "using Diff::LCS.sdiff with default sdiff callbacks" do - before(:each) do - @patch_set_s1_s2 = Diff::LCS.sdiff(@s1, @s2) - @patch_set_s2_s1 = Diff::LCS.sdiff(@s2, @s1) - end - - it "should autodiscover s1 to s2 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s1_s2).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s2_s1).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 the left-to-right patches" do - Diff::LCS.patch(@s2, @patch_set_s2_s1).should == @s1 - Diff::LCS.patch(@s2, @patch_set_s1_s2).should == @s1 - end - - it "should correctly patch left-to-right (explicit patch)", :only => true do - Diff::LCS.patch(@s1, @patch_set_s1_s2, :patch).should == @s2 - Diff::LCS.patch(@s2, @patch_set_s2_s1, :patch).should == @s1 - Diff::LCS.patch!(@s1, @patch_set_s1_s2).should == @s2 - Diff::LCS.patch!(@s2, @patch_set_s2_s1).should == @s1 - end - - it "should correctly patch right-to-left (explicit unpatch)" do - Diff::LCS.patch(@s2, @patch_set_s1_s2, :unpatch).should == @s1 - Diff::LCS.patch(@s1, @patch_set_s2_s1, :unpatch).should == @s2 - Diff::LCS.unpatch!(@s2, @patch_set_s1_s2).should == @s1 - Diff::LCS.unpatch!(@s1, @patch_set_s2_s1).should == @s2 - end - end - - describe "using Diff::LCS.sdiff with context diff callbacks" do - before(:each) do - @patch_set_s1_s2 = Diff::LCS.sdiff(@s1, @s2, Diff::LCS::ContextDiffCallbacks) - @patch_set_s2_s1 = Diff::LCS.sdiff(@s2, @s1, Diff::LCS::ContextDiffCallbacks) - end - - it "should autodiscover s1 to s2 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s1_s2).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s2_s1).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 the left-to-right patches" do - Diff::LCS.patch(@s2, @patch_set_s2_s1).should == @s1 - Diff::LCS.patch(@s2, @patch_set_s1_s2).should == @s1 - end - - it "should correctly patch left-to-right (explicit patch)" do - Diff::LCS.patch(@s1, @patch_set_s1_s2, :patch).should == @s2 - Diff::LCS.patch(@s2, @patch_set_s2_s1, :patch).should == @s1 - Diff::LCS.patch!(@s1, @patch_set_s1_s2).should == @s2 - Diff::LCS.patch!(@s2, @patch_set_s2_s1).should == @s1 - end - - it "should correctly patch right-to-left (explicit unpatch)" do - Diff::LCS.patch(@s2, @patch_set_s1_s2, :unpatch).should == @s1 - Diff::LCS.patch(@s1, @patch_set_s2_s1, :unpatch).should == @s2 - Diff::LCS.unpatch!(@s2, @patch_set_s1_s2).should == @s1 - Diff::LCS.unpatch!(@s1, @patch_set_s2_s1).should == @s2 - end - end - - describe "using Diff::LCS.sdiff with default diff callbacks" do - before(:each) do - @patch_set_s1_s2 = Diff::LCS.sdiff(@s1, @s2, Diff::LCS::DiffCallbacks) - @patch_set_s2_s1 = Diff::LCS.sdiff(@s2, @s1, Diff::LCS::DiffCallbacks) - end - - it "should autodiscover s1 to s2 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s1_s2).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 patches" do - expect do - Diff::LCS.patch(@s1, @patch_set_s2_s1).should == @s2 - end.to_not raise_error(RuntimeError, /provided patchset/) - end - - it "should autodiscover s2 to s1 the left-to-right patches" do - Diff::LCS.patch(@s2, @patch_set_s2_s1).should == @s1 - Diff::LCS.patch(@s2, @patch_set_s1_s2).should == @s1 - end - - it "should correctly patch left-to-right (explicit patch)" do - Diff::LCS.patch(@s1, @patch_set_s1_s2, :patch).should == @s2 - Diff::LCS.patch(@s2, @patch_set_s2_s1, :patch).should == @s1 - Diff::LCS.patch!(@s1, @patch_set_s1_s2).should == @s2 - Diff::LCS.patch!(@s2, @patch_set_s2_s1).should == @s1 - end - - it "should correctly patch right-to-left (explicit unpatch)" do - Diff::LCS.patch(@s2, @patch_set_s1_s2, :unpatch).should == @s1 - Diff::LCS.patch(@s1, @patch_set_s2_s1, :unpatch).should == @s2 - Diff::LCS.unpatch!(@s2, @patch_set_s1_s2).should == @s1 - Diff::LCS.unpatch!(@s1, @patch_set_s2_s1).should == @s2 - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/sdiff_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/sdiff_spec.rb deleted file mode 100644 index 7ab3bb6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/sdiff_spec.rb +++ /dev/null @@ -1,214 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe "Diff::LCS.sdiff" do - include Diff::LCS::SpecHelper::Matchers - - shared_examples "compare sequences correctly" do - it "should compare s1 -> s2 correctly" do - Diff::LCS.sdiff(s1, s2).should == context_diff(result) - end - - it "should compare s2 -> s1 correctly" do - Diff::LCS.sdiff(s2, s1).should == context_diff(reverse_sdiff(result)) - end - end - - describe "using seq1 & seq2" do - let(:s1) { seq1 } - let(:s2) { seq2 } - let(:result) { correct_forward_sdiff } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(abc def yyy xxx ghi jkl) & %w(abc dxf xxx ghi jkl)" do - let(:s1) { %w(abc def yyy xxx ghi jkl) } - let(:s2) { %w(abc dxf xxx ghi jkl) } - let(:result) { - [ - [ '=', [ 0, 'abc' ], [ 0, 'abc' ] ], - [ '!', [ 1, 'def' ], [ 1, 'dxf' ] ], - [ '-', [ 2, 'yyy' ], [ 2, nil ] ], - [ '=', [ 3, 'xxx' ], [ 2, 'xxx' ] ], - [ '=', [ 4, 'ghi' ], [ 3, 'ghi' ] ], - [ '=', [ 5, 'jkl' ], [ 4, 'jkl' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(a b c d e) & %w(a e)" do - let(:s1) { %w(a b c d e) } - let(:s2) { %w(a e) } - let(:result) { - [ - [ '=', [ 0, 'a' ], [ 0, 'a' ] ], - [ '-', [ 1, 'b' ], [ 1, nil ] ], - [ '-', [ 2, 'c' ], [ 1, nil ] ], - [ '-', [ 3, 'd' ], [ 1, nil ] ], - [ '=', [ 4, 'e' ], [ 1, 'e' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(a e) & %w(a b c d e)" do - let(:s1) { %w(a e) } - let(:s2) { %w(a b c d e) } - let(:result) { - [ - [ '=', [ 0, 'a' ], [ 0, 'a' ] ], - [ '+', [ 1, nil ], [ 1, 'b' ] ], - [ '+', [ 1, nil ], [ 2, 'c' ] ], - [ '+', [ 1, nil ], [ 3, 'd' ] ], - [ '=', [ 1, 'e' ], [ 4, 'e' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(v x a e) & %w(w y a b c d e)" do - let(:s1) { %w(v x a e) } - let(:s2) { %w(w y a b c d e) } - let(:result) { - [ - [ '!', [ 0, 'v' ], [ 0, 'w' ] ], - [ '!', [ 1, 'x' ], [ 1, 'y' ] ], - [ '=', [ 2, 'a' ], [ 2, 'a' ] ], - [ '+', [ 3, nil ], [ 3, 'b' ] ], - [ '+', [ 3, nil ], [ 4, 'c' ] ], - [ '+', [ 3, nil ], [ 5, 'd' ] ], - [ '=', [ 3, 'e' ], [ 6, 'e' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(x a e) & %w(a b c d e)" do - let(:s1) { %w(x a e) } - let(:s2) { %w(a b c d e) } - let(:result) { - [ - [ '-', [ 0, 'x' ], [ 0, nil ] ], - [ '=', [ 1, 'a' ], [ 0, 'a' ] ], - [ '+', [ 2, nil ], [ 1, 'b' ] ], - [ '+', [ 2, nil ], [ 2, 'c' ] ], - [ '+', [ 2, nil ], [ 3, 'd' ] ], - [ '=', [ 2, 'e' ], [ 4, 'e' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(a e) & %w(x a b c d e)" do - let(:s1) { %w(a e) } - let(:s2) { %w(x a b c d e) } - let(:result) { - [ - [ '+', [ 0, nil ], [ 0, 'x' ] ], - [ '=', [ 0, 'a' ], [ 1, 'a' ] ], - [ '+', [ 1, nil ], [ 2, 'b' ] ], - [ '+', [ 1, nil ], [ 3, 'c' ] ], - [ '+', [ 1, nil ], [ 4, 'd' ] ], - [ '=', [ 1, 'e' ], [ 5, 'e' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(a e v) & %w(x a b c d e w x)" do - let(:s1) { %w(a e v) } - let(:s2) { %w(x a b c d e w x) } - let(:result) { - [ - [ '+', [ 0, nil ], [ 0, 'x' ] ], - [ '=', [ 0, 'a' ], [ 1, 'a' ] ], - [ '+', [ 1, nil ], [ 2, 'b' ] ], - [ '+', [ 1, nil ], [ 3, 'c' ] ], - [ '+', [ 1, nil ], [ 4, 'd' ] ], - [ '=', [ 1, 'e' ], [ 5, 'e' ] ], - [ '!', [ 2, 'v' ], [ 6, 'w' ] ], - [ '+', [ 3, nil ], [ 7, 'x' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w() & %w(a b c)" do - let(:s1) { %w() } - let(:s2) { %w(a b c) } - let(:result) { - [ - [ '+', [ 0, nil ], [ 0, 'a' ] ], - [ '+', [ 0, nil ], [ 1, 'b' ] ], - [ '+', [ 0, nil ], [ 2, 'c' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(a b c) & %w(1)" do - let(:s1) { %w(a b c) } - let(:s2) { %w(1) } - let(:result) { - [ - [ '!', [ 0, 'a' ], [ 0, '1' ] ], - [ '-', [ 1, 'b' ], [ 1, nil ] ], - [ '-', [ 2, 'c' ], [ 1, nil ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(a b c) & %w(c)" do - let(:s1) { %w(a b c) } - let(:s2) { %w(c) } - let(:result) { - [ - [ '-', [ 0, 'a' ], [ 0, nil ] ], - [ '-', [ 1, 'b' ], [ 0, nil ] ], - [ '=', [ 2, 'c' ], [ 0, 'c' ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using %w(abcd efgh ijkl mnop) & []" do - let(:s1) { %w(abcd efgh ijkl mnop) } - let(:s2) { [] } - let(:result) { - [ - [ '-', [ 0, 'abcd' ], [ 0, nil ] ], - [ '-', [ 1, 'efgh' ], [ 0, nil ] ], - [ '-', [ 2, 'ijkl' ], [ 0, nil ] ], - [ '-', [ 3, 'mnop' ], [ 0, nil ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end - - describe "using [[1,2]] & []" do - let(:s1) { [ [ 1, 2 ] ] } - let(:s2) { [] } - let(:result) { - [ - [ '-', [ 0, [ 1, 2 ] ], [ 0, nil ] ] - ] - } - - it_has_behavior "compare sequences correctly" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/spec_helper.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/spec_helper.rb deleted file mode 100644 index a5ca00d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/spec_helper.rb +++ /dev/null @@ -1,290 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'rubygems' -require 'pathname' - -file = Pathname.new(__FILE__).expand_path -path = file.parent -parent = path.parent - -$:.unshift parent.join('lib') - -require 'diff-lcs' - -module Diff::LCS::SpecHelper - def hello - "hello" - end - - def hello_ary - %W(h e l l o) - end - - def seq1 - %w(a b c e h j l m n p) - end - - def skipped_seq1 - %w(a h n p) - end - - def seq2 - %w(b c d e f j k l m r s t) - end - - def skipped_seq2 - %w(d f k r s t) - end - - def word_sequence - %w(abcd efgh ijkl mnopqrstuvwxyz) - end - - def correct_lcs - %w(b c e j l m) - end - - def correct_forward_diff - [ - [ [ '-', 0, 'a' ] ], - [ [ '+', 2, 'd' ] ], - [ [ '-', 4, 'h' ], - [ '+', 4, 'f' ] ], - [ [ '+', 6, 'k' ] ], - [ [ '-', 8, 'n' ], - [ '-', 9, 'p' ], - [ '+', 9, 'r' ], - [ '+', 10, 's' ], - [ '+', 11, 't' ] ] - ] - end - - def correct_backward_diff - [ - [ [ '+', 0, 'a' ] ], - [ [ '-', 2, 'd' ] ], - [ [ '-', 4, 'f' ], - [ '+', 4, 'h' ] ], - [ [ '-', 6, 'k' ] ], - [ - [ '-', 9, 'r' ], - [ '-', 10, 's' ], - [ '+', 8, 'n' ], - [ '-', 11, 't' ], - [ '+', 9, 'p' ] ] - ] - end - - def correct_forward_sdiff - [ - [ '-', [ 0, 'a' ], [ 0, nil ] ], - [ '=', [ 1, 'b' ], [ 0, 'b' ] ], - [ '=', [ 2, 'c' ], [ 1, 'c' ] ], - [ '+', [ 3, nil ], [ 2, 'd' ] ], - [ '=', [ 3, 'e' ], [ 3, 'e' ] ], - [ '!', [ 4, 'h' ], [ 4, 'f' ] ], - [ '=', [ 5, 'j' ], [ 5, 'j' ] ], - [ '+', [ 6, nil ], [ 6, 'k' ] ], - [ '=', [ 6, 'l' ], [ 7, 'l' ] ], - [ '=', [ 7, 'm' ], [ 8, 'm' ] ], - [ '!', [ 8, 'n' ], [ 9, 'r' ] ], - [ '!', [ 9, 'p' ], [ 10, 's' ] ], - [ '+', [ 10, nil ], [ 11, 't' ] ] - ] - end - - def reverse_sdiff(forward_sdiff) - forward_sdiff.map { |line| - line[1], line[2] = line[2], line[1] - case line[0] - when '-' then line[0] = '+' - when '+' then line[0] = '-' - end - line - } - end - - def change_diff(diff) - map_diffs(diff, Diff::LCS::Change) - end - - def context_diff(diff) - map_diffs(diff, Diff::LCS::ContextChange) - end - - def format_diffs(diffs) - diffs.map do |e| - if e.kind_of?(Array) - e.map { |f| f.to_a.join }.join(", ") - else - e.to_a.join - end - end.join("\n") - end - - def map_diffs(diffs, klass = Diff::LCS::ContextChange) - diffs.map do |chunks| - if klass == Diff::LCS::ContextChange - klass.from_a(chunks) - else - chunks.map { |changes| klass.from_a(changes) } - end - end - end - - def balanced_traversal(s1, s2, callback_type) - callback = __send__(callback_type) - Diff::LCS.traverse_balanced(s1, s2, callback) - callback - end - - def balanced_reverse(change_result) - new_result = [] - change_result.each { |line| - line = [ line[0], line[2], line[1] ] - case line[0] - when '<' - line[0] = '>' - when '>' - line[0] = '<' - end - new_result << line - } - new_result.sort_by { |line| [ line[1], line[2] ] } - end - - def map_to_no_change(change_result) - new_result = [] - change_result.each { |line| - case line[0] - when '!' - new_result << [ '<', line[1], line[2] ] - new_result << [ '>', line[1] + 1, line[2] ] - else - new_result << line - end - } - new_result - end - - def simple_callback - callbacks = Object.new - class << callbacks - attr_reader :matched_a - attr_reader :matched_b - attr_reader :discards_a - attr_reader :discards_b - attr_reader :done_a - attr_reader :done_b - - def reset - @matched_a = [] - @matched_b = [] - @discards_a = [] - @discards_b = [] - @done_a = [] - @done_b = [] - end - - def match(event) - @matched_a << event.old_element - @matched_b << event.new_element - end - - def discard_b(event) - @discards_b << event.new_element - end - - def discard_a(event) - @discards_a << event.old_element - end - - def finished_a(event) - @done_a << [event.old_element, event.old_position, - event.new_element, event.new_position] - end - - def finished_b(event) - p "called #finished_b" - @done_b << [event.old_element, event.old_position, - event.new_element, event.new_position] - end - end - callbacks.reset - callbacks - end - - def simple_callback_no_finishers - simple = simple_callback - class << simple - undef :finished_a - undef :finished_b - end - simple - end - - def balanced_callback - cb = Object.new - class << cb - attr_reader :result - - def reset - @result = [] - end - - def match(event) - @result << [ "=", event.old_position, event.new_position ] - end - - def discard_a(event) - @result << [ "<", event.old_position, event.new_position ] - end - - def discard_b(event) - @result << [ ">", event.old_position, event.new_position ] - end - - def change(event) - @result << [ "!", event.old_position, event.new_position ] - end - end - cb.reset - cb - end - - def balanced_callback_no_change - balanced = balanced_callback - class << balanced - undef :change - end - balanced - end - - module Matchers - extend RSpec::Matchers::DSL - - matcher :be_nil_or_match_values do |ii, s1, s2| - match do |ee| - ee.should satisfy { |vee| vee.nil? || s1[ii] == s2[ee] } - end - end - - matcher :correctly_map_sequence do |s1| - match do |actual| - actual.each_with_index { |ee, ii| - ee.should be_nil_or_match_values(ii, s1, @s2) - } - end - - chain :to_other_sequence do |s2| - @s2 = s2 - end - end - end -end - -RSpec.configure do |conf| - conf.include Diff::LCS::SpecHelper - conf.alias_it_should_behave_like_to :it_has_behavior, 'has behavior:' - conf.filter_run_excluding :broken => true -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/traverse_balanced_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/traverse_balanced_spec.rb deleted file mode 100644 index 63fe1eb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/traverse_balanced_spec.rb +++ /dev/null @@ -1,310 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe "Diff::LCS.traverse_balanced" do - include Diff::LCS::SpecHelper::Matchers - - shared_examples "with a #change callback" do |s1, s2, result| - it "should traverse s1 -> s2 correctly" do - traversal = balanced_traversal(s1, s2, :balanced_callback) - traversal.result.should == result - end - - it "should traverse s2 -> s1 correctly" do - traversal = balanced_traversal(s2, s1, :balanced_callback) - traversal.result.should == balanced_reverse(result) - end - end - - shared_examples "without a #change callback" do |s1, s2, result| - it "should traverse s1 -> s2 correctly" do - traversal = balanced_traversal(s1, s2, :balanced_callback_no_change) - traversal.result.should == map_to_no_change(result) - end - - it "should traverse s2 -> s1 correctly" do - traversal = balanced_traversal(s2, s1, :balanced_callback_no_change) - traversal.result.should == map_to_no_change(balanced_reverse(result)) - end - end - - describe "identical string sequences ('abc')" do - s1 = s2 = "abc" - - result = [ - [ '=', 0, 0 ], - [ '=', 1, 1 ], - [ '=', 2, 2 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "identical array sequences %w(a b c)" do - s1 = s2 = %w(a b c) - - result = [ - [ '=', 0, 0 ], - [ '=', 1, 1 ], - [ '=', 2, 2 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(a b c) & %w(a x c)" do - s1 = %w(a b c) - s2 = %w(a x c) - - result = [ - [ '=', 0, 0 ], - [ '!', 1, 1 ], - [ '=', 2, 2 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(a x y c) & %w(a v w c)" do - s1 = %w(a x y c) - s2 = %w(a v w c) - - result = [ - [ '=', 0, 0 ], - [ '!', 1, 1 ], - [ '!', 2, 2 ], - [ '=', 3, 3 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(x y c) & %w(v w c)" do - s1 = %w(x y c) - s2 = %w(v w c) - result = [ - [ '!', 0, 0 ], - [ '!', 1, 1 ], - [ '=', 2, 2 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(a x y z) & %w(b v w)" do - s1 = %w(a x y z) - s2 = %w(b v w) - result = [ - [ '!', 0, 0 ], - [ '!', 1, 1 ], - [ '!', 2, 2 ], - [ '<', 3, 3 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(a z) & %w(a)" do - s1 = %w(a z) - s2 = %w(a) - result = [ - [ '=', 0, 0 ], - [ '<', 1, 1 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(z a) & %w(a)" do - s1 = %w(z a) - s2 = %w(a) - result = [ - [ '<', 0, 0 ], - [ '=', 1, 0 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(a b c) & %w(x y z)" do - s1 = %w(a b c) - s2 = %w(x y z) - result = [ - [ '!', 0, 0 ], - [ '!', 1, 1 ], - [ '!', 2, 2 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "sequences %w(abcd efgh ijkl mnoopqrstuvwxyz) & []" do - s1 = %w(abcd efgh ijkl mnopqrstuvwxyz) - s2 = [] - result = [ - [ '<', 0, 0 ], - [ '<', 1, 0 ], - [ '<', 2, 0 ], - [ '<', 3, 0 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(a b c) & %Q(a x c)" do - s1 = %Q(a b c) - s2 = %Q(a x c) - - result = [ - [ '=', 0, 0 ], - [ '=', 1, 1 ], - [ '!', 2, 2 ], - [ '=', 3, 3 ], - [ '=', 4, 4 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(a x y c) & %Q(a v w c)" do - s1 = %Q(a x y c) - s2 = %Q(a v w c) - - result = [ - [ '=', 0, 0 ], - [ '=', 1, 1 ], - [ '!', 2, 2 ], - [ '=', 3, 3 ], - [ '!', 4, 4 ], - [ '=', 5, 5 ], - [ '=', 6, 6 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(x y c) & %Q(v w c)" do - s1 = %Q(x y c) - s2 = %Q(v w c) - result = [ - [ '!', 0, 0 ], - [ '=', 1, 1 ], - [ '!', 2, 2 ], - [ '=', 3, 3 ], - [ '=', 4, 4 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(a x y z) & %Q(b v w)" do - s1 = %Q(a x y z) - s2 = %Q(b v w) - result = [ - [ '!', 0, 0 ], - [ '=', 1, 1 ], - [ '!', 2, 2 ], - [ '=', 3, 3 ], - [ '!', 4, 4 ], - [ '<', 5, 5 ], - [ '<', 6, 5 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(a z) & %Q(a)" do - s1 = %Q(a z) - s2 = %Q(a) - result = [ - [ '=', 0, 0 ], - [ '<', 1, 1 ], - [ '<', 2, 1 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(z a) & %Q(a)" do - s1 = %Q(z a) - s2 = %Q(a) - result = [ - [ '<', 0, 0 ], - [ '<', 1, 0 ], - [ '=', 2, 0 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(a b c) & %Q(x y z)" do - s1 = %Q(a b c) - s2 = %Q(x y z) - result = [ - [ '!', 0, 0 ], - [ '=', 1, 1 ], - [ '!', 2, 2 ], - [ '=', 3, 3 ], - [ '!', 4, 4 ] - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end - - describe "strings %Q(abcd efgh ijkl mnopqrstuvwxyz) & %Q()" do - s1 = %Q(abcd efgh ijkl mnopqrstuvwxyz) - s2 = "" - result = [ - [ '<', 0, 0 ], - [ '<', 1, 0 ], - [ '<', 2, 0 ], - [ '<', 3, 0 ], - [ '<', 4, 0 ], - [ '<', 5, 0 ], - [ '<', 6, 0 ], - [ '<', 7, 0 ], - [ '<', 8, 0 ], - [ '<', 9, 0 ], - [ '<', 10, 0 ], - [ '<', 11, 0 ], - [ '<', 12, 0 ], - [ '<', 13, 0 ], - [ '<', 14, 0 ], - [ '<', 15, 0 ], - [ '<', 16, 0 ], - [ '<', 17, 0 ], - [ '<', 18, 0 ], - [ '<', 19, 0 ], - [ '<', 20, 0 ], - [ '<', 21, 0 ], - [ '<', 22, 0 ], - [ '<', 23, 0 ], - [ '<', 24, 0 ], - [ '<', 25, 0 ], - [ '<', 26, 0 ], - [ '<', 27, 0 ], - [ '<', 28, 0 ], - ] - - it_has_behavior "with a #change callback", s1, s2, result - it_has_behavior "without a #change callback", s1, s2, result - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/traverse_sequences_spec.rb b/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/traverse_sequences_spec.rb deleted file mode 100644 index f4480df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/diff-lcs-1.2.5/spec/traverse_sequences_spec.rb +++ /dev/null @@ -1,139 +0,0 @@ -# -*- ruby encoding: utf-8 -*- - -require 'spec_helper' - -describe "Diff::LCS.traverse_sequences" do - describe "callback with no finishers" do - describe "over (seq1, seq2)" do - before(:each) do - @callback_s1_s2 = simple_callback_no_finishers - Diff::LCS.traverse_sequences(seq1, seq2, @callback_s1_s2) - - @callback_s2_s1 = simple_callback_no_finishers - Diff::LCS.traverse_sequences(seq2, seq1, @callback_s2_s1) - end - - it "should have the correct LCS result on left-matches" do - @callback_s1_s2.matched_a.should == correct_lcs - @callback_s2_s1.matched_a.should == correct_lcs - end - - it "should have the correct LCS result on right-matches" do - @callback_s1_s2.matched_b.should == correct_lcs - @callback_s2_s1.matched_b.should == correct_lcs - end - - it "should have the correct skipped sequences with the left sequence" do - @callback_s1_s2.discards_a.should == skipped_seq1 - @callback_s2_s1.discards_a.should == skipped_seq2 - end - - it "should have the correct skipped sequences with the right sequence" do - @callback_s1_s2.discards_b.should == skipped_seq2 - @callback_s2_s1.discards_b.should == skipped_seq1 - end - - it "should not have anything done markers from the left or right sequences" do - @callback_s1_s2.done_a.should be_empty - @callback_s1_s2.done_b.should be_empty - @callback_s2_s1.done_a.should be_empty - @callback_s2_s1.done_b.should be_empty - end - end - - describe "over (hello, hello)" do - before(:each) do - @callback = simple_callback_no_finishers - Diff::LCS.traverse_sequences(hello, hello, @callback) - end - - it "should have the correct LCS result on left-matches" do - @callback.matched_a.should == hello.split(//) - end - - it "should have the correct LCS result on right-matches" do - @callback.matched_b.should == hello.split(//) - end - - it "should have the correct skipped sequences with the left sequence", :only => true do - @callback.discards_a.should be_empty - end - - it "should have the correct skipped sequences with the right sequence" do - @callback.discards_b.should be_empty - end - - it "should not have anything done markers from the left or right sequences" do - @callback.done_a.should be_empty - @callback.done_b.should be_empty - end - end - - describe "over (hello_ary, hello_ary)" do - before(:each) do - @callback = simple_callback_no_finishers - Diff::LCS.traverse_sequences(hello_ary, hello_ary, @callback) - end - - it "should have the correct LCS result on left-matches" do - @callback.matched_a.should == hello_ary - end - - it "should have the correct LCS result on right-matches" do - @callback.matched_b.should == hello_ary - end - - it "should have the correct skipped sequences with the left sequence" do - @callback.discards_a.should be_empty - end - - it "should have the correct skipped sequences with the right sequence" do - @callback.discards_b.should be_empty - end - - it "should not have anything done markers from the left or right sequences" do - @callback.done_a.should be_empty - @callback.done_b.should be_empty - end - end - end - - describe "callback with finisher" do - before(:each) do - @callback_s1_s2 = simple_callback - Diff::LCS.traverse_sequences(seq1, seq2, @callback_s1_s2) - @callback_s2_s1 = simple_callback - Diff::LCS.traverse_sequences(seq2, seq1, @callback_s2_s1) - end - - it "should have the correct LCS result on left-matches" do - @callback_s1_s2.matched_a.should == correct_lcs - @callback_s2_s1.matched_a.should == correct_lcs - end - - it "should have the correct LCS result on right-matches" do - @callback_s1_s2.matched_b.should == correct_lcs - @callback_s2_s1.matched_b.should == correct_lcs - end - - it "should have the correct skipped sequences for the left sequence" do - @callback_s1_s2.discards_a.should == skipped_seq1 - @callback_s2_s1.discards_a.should == skipped_seq2 - end - - it "should have the correct skipped sequences for the right sequence" do - @callback_s1_s2.discards_b.should == skipped_seq2 - @callback_s2_s1.discards_b.should == skipped_seq1 - end - - it "should have done markers differently-sized sequences" do - @callback_s1_s2.done_a.should == [[ "p", 9, "s", 10 ]] - @callback_s1_s2.done_b.should be_empty - - # 20110731 I don't yet understand why this particular behaviour - # isn't transitive. - @callback_s2_s1.done_a.should be_empty - @callback_s2_s1.done_b.should be_empty - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.env b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.env deleted file mode 100644 index 6daac06..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.env +++ /dev/null @@ -1 +0,0 @@ -DOTENV=true \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.gitignore b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.gitignore deleted file mode 100644 index 6e78401..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -*.gem -*.rbc -.bundle -.config -.yardoc -Gemfile.lock -tmp -vendor diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.travis.yml b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.travis.yml deleted file mode 100644 index 827df5f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: ruby -rvm: - - 2.1.0 - - 2.0.0 - - 1.9.3 - - 1.8.7 - - ree - - jruby-19mode - - rbx -bundler_args: --without=guard \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Changelog.md b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Changelog.md deleted file mode 100644 index e63c78a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Changelog.md +++ /dev/null @@ -1,107 +0,0 @@ -# Changelog - -## 0.11.1 - Apr 22, 2014 - -* Depend on dotenv-deployment ~>0.0.2, which fixes issues with 0.0.1 - -## 0.11.0 - Apr 21, 2014 - -* Extract dotenv-deployment gem. https://github.com/bkeepers/dotenv-deployment - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.10.0...v0.11.0) - -## 0.10.0 - Feb 22, 2014 - -* Add support for executing interpolated commands. (Ruby >= 1.9 only) - - HEAD_SHA=$(git rev-parse HEAD) - -* Add `dotenv_role` option in Capistrano. - - set :dotenv_role, [:app, web] - -* Add `Dotenv.overload` to overwrite existing environment values. - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.9.0...v0.10.0) - -## 0.9.0 - Aug 29, 2013 - -* Add support for variable expansion. - - HOST="example.com" - URL="http://${USER}@${HOST}" - ESCAPED_VARIABLE="this is \$NOT replaced" - -* Allow setting variables without a value. - - BLANK= - -* Add `dotenv` executable to load `.env` for other scripts. - - $ dotenv ./script.py - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.8.0...v0.9.0) - -## 0.8.0 - June 12, 2013 - -* Added a capistrano recipe to symlink in `.env` on deploy. - -* Allow inline comments - - VARIABLE=value # this is a comment - -* Raises Dotenv::FormatError when parsing fails - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.7.0...v0.8.0) - -## 0.7.0 - April 15, 2013 - -* Remove deprectated autoloading. Upgrade to 0.6 first and fix any warnings. - -* Add Dotenv.load! which raises Errno::ENOENT if the file does not exist - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.6.0...v0.7.0) - -## 0.6.0 - Mar 22, 2013 - -* Add dotenv-rails gem for autoloading in a Rails app - -* Deprecated autoloading with plain dotenv gem - -* Support for double quotes - - A="some value" - B="with \"escaped\" quotes" - C="and newline\n expansion" - -* Support for pow-style variables prefixed with export - - export VARIABLE="some value" - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.5.0...v0.6.0) - -## 0.5.0 - Jan 25, 2013 - -* Load immediately on require in Rails instead of waiting for initialization - -* Add YAML-style variables - - VARIABLE: some value - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.4.0...v0.5.0) - -## 0.4.0 - Nov 13, 2012 - -* Add support for quoted options, e.g.: - - VARIABLE='some value' - -* Fix rake deprecation warnings - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.3.0...v0.4.0) - -## 0.3.0 - Oct 25, 2012 - -* Avoid overriding existing ENV variables so values set before loading the app are maintained. - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.2.0...v0.3.0) diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Gemfile b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Gemfile deleted file mode 100644 index 4566c90..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Gemfile +++ /dev/null @@ -1,14 +0,0 @@ -source 'https://rubygems.org' -gemspec :name => 'dotenv' - -gem 'dotenv-deployment', :github => 'bkeepers/dotenv-deployment' - -group :guard do - gem 'guard-rspec' - gem 'guard-bundler' - gem 'rb-fsevent' -end - -platforms :rbx do - gem 'rubysl', '~> 2.0' # if using anything in the ruby standard library -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Guardfile b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Guardfile deleted file mode 100644 index 363de7a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Guardfile +++ /dev/null @@ -1,9 +0,0 @@ -guard 'bundler' do - watch('Gemfile') -end - -guard 'rspec' do - watch(%r{^spec/.+_spec\.rb$}) - watch(%r{^spec/spec_helper.rb$}) { "spec" } - watch(%r{^lib/(.+)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" } -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/LICENSE b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/LICENSE deleted file mode 100644 index 0b67483..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012 Brandon Keepers - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/README.md b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/README.md deleted file mode 100644 index 98d1e81..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# dotenv [![Build Status](https://secure.travis-ci.org/bkeepers/dotenv.png?branch=master)](https://travis-ci.org/bkeepers/dotenv) - -Shim to load environment variables from `.env` into `ENV` in *development*. - -Storing [configuration in the environment](http://www.12factor.net/config) is one of the tenets of a [twelve-factor app](http://www.12factor.net/). Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables. - -But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. dotenv loads variables from a `.env` file into `ENV` when the environment is bootstrapped. - -dotenv is intended to be used in development. If you would like to use it in production or other environments, see [dotenv-deployment](https://github.com/bkeepers/dotenv-deployment) - - -## Installation - -### Rails - -Add this line to the top of your application's Gemfile: - -```ruby -gem 'dotenv-rails', :groups => [:development, :test] -``` - -And then execute: - -```shell -$ bundle -``` - -It should be listed in the Gemfile before any other gems that use environment variables, otherwise those gems will get initialized with the wrong values. - -### Sinatra or Plain ol' Ruby - -Install the gem: - -```shell -$ gem install dotenv -``` - -As early as possible in your application bootstrap process, load `.env`: - -```ruby -require 'dotenv' -Dotenv.load -``` - -Alternatively, you can use the `dotenv` executable to launch your application: - -```shell -$ dotenv ./script.py -``` - -To ensure `.env` is loaded in rake, load the tasks: - -```ruby -require 'dotenv/tasks' - -task :mytask => :dotenv do - # things that require .env -end -``` - -## Usage - -Add your application configuration to your `.env` file in the root of your project: - -```shell -S3_BUCKET=YOURS3BUCKET -SECRET_KEY=YOURSECRETKEYGOESHERE -``` - -An alternate yaml-like syntax is supported: - -```yaml -S3_BUCKET: yamlstyleforyours3bucket -SECRET_KEY: thisisalsoanokaysecret -``` - -Whenever your application loads, these variables will be available in `ENV`: - -```ruby -config.fog_directory = ENV['S3_BUCKET'] -``` - -## Should I commit my .env file? - -It is recommended that you store development-only settings in your `.env` file, and commit it to your repository. Make sure that all your credentials for your development environment are different from your other deployments. This makes it easy for other developers to get started on your project, without compromising your credentials for other environments. - -## Contributing - -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Added some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Rakefile b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Rakefile deleted file mode 100644 index f49d219..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/Rakefile +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env rake - -require 'bundler/gem_helper' - -namespace 'dotenv' do - Bundler::GemHelper.install_tasks :name => 'dotenv' -end - -namespace 'dotenv-rails' do - class DotenvRailsGemHelper < Bundler::GemHelper - def guard_already_tagged; end # noop - def tag_version; end # noop - end - - DotenvRailsGemHelper.install_tasks :name => 'dotenv-rails' -end - -task :build => ["dotenv:build", 'dotenv-rails:build'] -task :install => ["dotenv:install", 'dotenv-rails:install'] -task :release => ["dotenv:release", 'dotenv-rails:release'] - -require 'rspec/core/rake_task' - -desc "Run all specs" -RSpec::Core::RakeTask.new(:spec) do |t| - t.rspec_opts = %w[--color] - t.verbose = false -end - -task :default => :spec diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/bin/dotenv b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/bin/dotenv deleted file mode 100755 index ec295cb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/bin/dotenv +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env ruby - -require 'dotenv' - -begin - Dotenv.load! -rescue Errno::ENOENT => e - abort e.message -else - exec *ARGV unless ARGV.empty? -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/dotenv-rails.gemspec b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/dotenv-rails.gemspec deleted file mode 100644 index 6ef242e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/dotenv-rails.gemspec +++ /dev/null @@ -1,18 +0,0 @@ -# -*- encoding: utf-8 -*- -require File.expand_path('../lib/dotenv/version', __FILE__) - -Gem::Specification.new do |gem| - gem.version = Dotenv::VERSION - gem.authors = ["Brandon Keepers"] - gem.email = ["brandon@opensoul.org"] - gem.description = %q{Autoload dotenv in Rails.} - gem.summary = %q{Autoload dotenv in Rails.} - gem.homepage = "https://github.com/bkeepers/dotenv" - gem.license = 'MIT' - - gem.files = ["lib/dotenv-rails.rb"] - gem.name = "dotenv-rails" - gem.require_paths = ["lib"] - - gem.add_dependency 'dotenv', Dotenv::VERSION -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/dotenv.gemspec b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/dotenv.gemspec deleted file mode 100644 index 8ce80ec..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/dotenv.gemspec +++ /dev/null @@ -1,23 +0,0 @@ -# -*- encoding: utf-8 -*- -require File.expand_path('../lib/dotenv/version', __FILE__) - -Gem::Specification.new do |gem| - gem.version = Dotenv::VERSION - gem.authors = ["Brandon Keepers"] - gem.email = ["brandon@opensoul.org"] - gem.description = %q{Loads environment variables from `.env`.} - gem.summary = %q{Loads environment variables from `.env`.} - gem.homepage = "https://github.com/bkeepers/dotenv" - gem.license = 'MIT' - - gem.files = `git ls-files`.split($\) - gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } - gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) - gem.name = "dotenv" - gem.require_paths = ["lib"] - - gem.add_dependency "dotenv-deployment", "~>0.0.2" - - gem.add_development_dependency 'rake' - gem.add_development_dependency 'rspec' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv-rails.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv-rails.rb deleted file mode 100644 index d4dc801..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv-rails.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'dotenv/railtie' - -env_file = ".env.#{Rails.env}" -if File.exists?(env_file) && !defined?(Dotenv::Deployment) - warn "Auto-loading of `#{env_file}` will be removed in 1.0. See " + - "https://github.com/bkeepers/dotenv-deployment if you would like to " + - "continue using this feature." - Dotenv.load ".env.#{Rails.env}" -end - -Dotenv.load '.env' diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv.rb deleted file mode 100644 index 6d13ec5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'dotenv/parser' -require 'dotenv/environment' - -module Dotenv - def self.load(*filenames) - with(*filenames) { |f| Environment.new(f).apply if File.exists?(f) } - end - - # same as `load`, but raises Errno::ENOENT if any files don't exist - def self.load!(*filenames) - with(*filenames) { |f| Environment.new(f).apply } - end - - # same as `load`, but will override existing values in `ENV` - def self.overload(*filenames) - with(*filenames) { |f| Environment.new(f).apply! if File.exists?(f) } - end - -protected - - def self.with(*filenames, &block) - filenames << '.env' if filenames.empty? - - filenames.inject({}) do |hash, filename| - filename = File.expand_path filename - hash.merge(block.call(filename) || {}) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/capistrano.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/capistrano.rb deleted file mode 100644 index 0f1b1d7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/capistrano.rb +++ /dev/null @@ -1,6 +0,0 @@ -warn "Capistrano support has been moved to the dotenv-deployment gem. Add it " + - "to your Gemfile and change the require to 'dotenv/deployment/capistrano'. " + - "See https://github.com/bkeepers/dotenv-deployment#capistrano." - -# This will be removed in 1.0 -require 'dotenv/deployment/capistrano' diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/environment.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/environment.rb deleted file mode 100644 index 4cf7520..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/environment.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Dotenv - class Environment < Hash - - def initialize(filename) - @filename = filename - load - end - - def load - update Parser.call(read) - end - - def read - File.read(@filename) - end - - def apply - each { |k,v| ENV[k] ||= v } - end - - def apply! - each { |k,v| ENV[k] = v } - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/parser.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/parser.rb deleted file mode 100644 index 8d298ad..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/parser.rb +++ /dev/null @@ -1,63 +0,0 @@ -require 'dotenv/substitutions/variable' -if RUBY_VERSION > '1.8.7' - require 'dotenv/substitutions/command' -end - -module Dotenv - class FormatError < SyntaxError; end - - class Parser - @@substitutions = Substitutions.constants.map { |const| Substitutions.const_get(const) } - - LINE = / - \A - (?:export\s+)? # optional export - ([\w\.]+) # key - (?:\s*=\s*|:\s+?) # separator - ( # optional value begin - '(?:\'|[^'])*' # single quoted value - | # or - "(?:\"|[^"])*" # double quoted value - | # or - [^#\n]+ # unquoted value - )? # value end - (?:\s*\#.*)? # optional comment - \z - /x - - def self.call(string) - new(string).call - end - - def initialize(string) - @string = string - end - - def call - @string.split("\n").inject({}) do |hash, line| - if match = line.match(LINE) - key, value = match.captures - - value ||= '' - # Remove surrounding quotes - value = value.strip.sub(/\A(['"])(.*)\1\z/, '\2') - - if $1 == '"' - value = value.gsub('\n', "\n") - # Unescape all characters except $ so variables can be escaped properly - value = value.gsub(/\\([^$])/, '\1') - end - - @@substitutions.each do |proc| - value = proc.call(value, hash) - end - - hash[key] = value - elsif line !~ /\A\s*(?:#.*)?\z/ # not comment or blank line - raise FormatError, "Line #{line.inspect} doesn't match format" - end - hash - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/railtie.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/railtie.rb deleted file mode 100644 index 7637a39..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/railtie.rb +++ /dev/null @@ -1,12 +0,0 @@ -require 'dotenv' - -module Dotenv - class Railtie < Rails::Railtie - rake_tasks do - task :dotenv do - # If the dotenv task is defined, then dotenv has already been loaded. - warn "The `dotenv` task is no longer needed and will be removed in 1.0." - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/substitutions/command.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/substitutions/command.rb deleted file mode 100644 index 75f6fcb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/substitutions/command.rb +++ /dev/null @@ -1,32 +0,0 @@ -module Dotenv - module Substitutions - module Command - class << self - - INTERPOLATED_SHELL_COMMAND = / - (?\\)? - \$ - (? # collect command content for eval - \( # require opening paren - ([^()]|\g)+ # allow any number of non-parens, or balanced parens (by nesting the expression recursively) - \) # require closing paren - ) - /x - - def call(value, env) - # Process interpolated shell commands - value.gsub(INTERPOLATED_SHELL_COMMAND) do |*| - command = $~[:cmd][1..-2] # Eliminate opening and closing parentheses - - if $~[:backslash] - $~[0][1..-1] - else - `#{command}`.chomp - end - end - end - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/substitutions/variable.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/substitutions/variable.rb deleted file mode 100644 index f73aced..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/substitutions/variable.rb +++ /dev/null @@ -1,35 +0,0 @@ -module Dotenv - module Substitutions - module Variable - class << self - - VARIABLE = / - (\\)? - (\$) - ( # collect braces with var for sub - \{? # allow brace wrapping - ([A-Z0-9_]+) # match the variable - \}? # closing brace - ) - /xi - - def call(value, env) - # Process embedded variables - value.scan(VARIABLE).each do |parts| - if parts.first == '\\' - replace = parts[1...-1].join('') - else - replace = env.fetch(parts.last) { ENV[parts.last] } - end - - value = value.sub(parts[0...-1].join(''), replace || '') - end - - value - end - end - - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/tasks.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/tasks.rb deleted file mode 100644 index 32cab8f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/tasks.rb +++ /dev/null @@ -1,7 +0,0 @@ -desc 'Load environment settings from .env' -task :dotenv do - require 'dotenv' - Dotenv.load -end - -task :environment => :dotenv \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/version.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/version.rb deleted file mode 100644 index 2e97bef..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/lib/dotenv/version.rb +++ /dev/null @@ -1,3 +0,0 @@ -module Dotenv - VERSION = '0.11.1' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv/environment_spec.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv/environment_spec.rb deleted file mode 100644 index c5a5d51..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv/environment_spec.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'spec_helper' - -describe Dotenv::Environment do - subject { env("OPTION_A=1\nOPTION_B=2") } - - describe 'initialize' do - it 'reads the file' do - expect(subject['OPTION_A']).to eq('1') - expect(subject['OPTION_B']).to eq('2') - end - - it 'fails if file does not exist' do - expect { - Dotenv::Environment.new('.does_not_exists') - }.to raise_error(Errno::ENOENT) - end - end - - describe 'apply' do - it 'sets variables in ENV' do - subject.apply - expect(ENV['OPTION_A']).to eq('1') - end - - it 'does not override defined variables' do - ENV['OPTION_A'] = 'predefined' - subject.apply - expect(ENV['OPTION_A']).to eq('predefined') - end - end - - describe 'apply!' do - it 'sets variables in the ENV' do - subject.apply - expect(ENV['OPTION_A']).to eq('1') - end - - it 'overrides defined variables' do - ENV['OPTION_A'] = 'predefined' - subject.apply! - expect(ENV['OPTION_A']).to eq('1') - end - end - - require 'tempfile' - def env(text) - file = Tempfile.new('dotenv') - file.write text - file.close - env = Dotenv::Environment.new(file.path) - file.unlink - env - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv/parser_spec.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv/parser_spec.rb deleted file mode 100644 index f6a5874..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv/parser_spec.rb +++ /dev/null @@ -1,129 +0,0 @@ -require 'spec_helper' - -describe Dotenv::Parser do - def env(string) - Dotenv::Parser.call(string) - end - - it 'parses unquoted values' do - expect(env('FOO=bar')).to eql('FOO' => 'bar') - end - - it 'parses values with spaces around equal sign' do - expect(env("FOO =bar")).to eql('FOO' => 'bar') - expect(env("FOO= bar")).to eql('FOO' => 'bar') - end - - it 'parses double quoted values' do - expect(env('FOO="bar"')).to eql('FOO' => 'bar') - end - - it 'parses single quoted values' do - expect(env("FOO='bar'")).to eql('FOO' => 'bar') - end - - it 'parses escaped double quotes' do - expect(env('FOO="escaped\"bar"')).to eql('FOO' => 'escaped"bar') - end - - it 'parses empty values' do - expect(env('FOO=')).to eql('FOO' => '') - end - - it 'expands variables found in values' do - expect(env("FOO=test\nBAR=$FOO")).to eql('FOO' => 'test', 'BAR' => 'test') - end - - it 'parses variables wrapped in brackets' do - expect(env("FOO=test\nBAR=${FOO}bar")).to eql('FOO' => 'test', 'BAR' => 'testbar') - end - - it 'reads variables from ENV when expanding if not found in local env' do - ENV['FOO'] = 'test' - expect(env('BAR=$FOO')).to eql('BAR' => 'test') - end - - it 'expands undefined variables to an empty string' do - expect(env('BAR=$FOO')).to eql('BAR' => '') - end - - it 'expands variables in quoted strings' do - expect(env("FOO=test\nBAR='quote $FOO'")).to eql('FOO' => 'test', 'BAR' => 'quote test') - end - - it 'does not expand escaped variables' do - expect(env('FOO="foo\$BAR"')).to eql('FOO' => 'foo$BAR') - expect(env('FOO="foo\${BAR}"')).to eql('FOO' => 'foo${BAR}') - end - - it 'parses yaml style options' do - expect(env('OPTION_A: 1')).to eql('OPTION_A' => '1') - end - - it 'parses export keyword' do - expect(env('export OPTION_A=2')).to eql('OPTION_A' => '2') - end - - it 'expands newlines in quoted strings' do - expect(env('FOO="bar\nbaz"')).to eql('FOO' => "bar\nbaz") - end - - it 'parses variables with "." in the name' do - expect(env('FOO.BAR=foobar')).to eql('FOO.BAR' => 'foobar') - end - - it 'strips unquoted values' do - expect(env('foo=bar ')).to eql('foo' => 'bar') # not 'bar ' - end - - it 'throws an error if line format is incorrect' do - expect{env('lol$wut')}.to raise_error(Dotenv::FormatError) - end - - it 'ignores empty lines' do - expect(env("\n \t \nfoo=bar\n \nfizz=buzz")).to eql('foo' => 'bar', 'fizz' => 'buzz') - end - - it 'ignores inline comments' do - expect(env("foo=bar # this is foo")).to eql('foo' => 'bar') - end - - it 'allows # in quoted value' do - expect(env('foo="bar#baz" # comment')).to eql('foo' => 'bar#baz') - end - - it 'ignores comment lines' do - expect(env("\n\n\n # HERE GOES FOO \nfoo=bar")).to eql('foo' => 'bar') - end - - it 'parses # in quoted values' do - expect(env('foo="ba#r"')).to eql('foo' => 'ba#r') - expect(env("foo='ba#r'")).to eql('foo' => 'ba#r') - end - - if RUBY_VERSION > '1.8.7' - it 'parses shell commands interpolated in $()' do - expect(env('ruby_v=$(ruby -v)')).to eql('ruby_v' => RUBY_DESCRIPTION) - end - - it 'allows balanced parentheses within interpolated shell commands' do - expect(env('ruby_v=$(echo "$(echo "$(echo "$(ruby -v)")")")')).to eql('ruby_v' => RUBY_DESCRIPTION) - end - - it "doesn't interpolate shell commands when escape says not to" do - expect(env('ruby_v=escaped-\$(ruby -v)')).to eql('ruby_v' => 'escaped-$(ruby -v)') - end - - it 'is not thrown off by quotes in interpolated shell commands' do - expect(env('interp=$(echo "Quotes won\'t be a problem")')['interp']).to eql("Quotes won't be a problem") - end - - # This functionality is not supported on JRuby or Rubinius - if (!defined?(RUBY_ENGINE) || RUBY_ENGINE != 'jruby') && !defined?(Rubinius) - it 'substitutes shell variables within interpolated shell commands' do - expect(env(%(VAR1=var1\ninterp=$(echo "VAR1 is $VAR1")))['interp']).to eql("VAR1 is var1") - end - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv_spec.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv_spec.rb deleted file mode 100644 index db12447..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/dotenv_spec.rb +++ /dev/null @@ -1,102 +0,0 @@ -require 'spec_helper' - -describe Dotenv do - shared_examples 'load' do - context 'with no args' do - let(:env_files) { [] } - - it 'defaults to .env' do - expect(Dotenv::Environment).to receive(:new).with(expand('.env')). - and_return(double(:apply => {}, :apply! => {})) - subject - end - end - - context 'with a tilde path' do - let(:env_files) { ['~/.env'] } - - it 'expands the path' do - expected = expand("~/.env") - allow(File).to receive(:exists?){ |arg| arg == expected } - expect(Dotenv::Environment).to receive(:new).with(expected). - and_return(double(:apply => {}, :apply! => {})) - subject - end - end - - context 'with multiple files' do - let(:env_files) { ['.env', fixture_path('plain.env')] } - - let(:expected) do - { 'OPTION_A' => '1', - 'OPTION_B' => '2', - 'OPTION_C' => '3', - 'OPTION_D' => '4', - 'OPTION_E' => '5', - 'DOTENV' => 'true' } - end - - it 'loads all files' do - subject - expected.each do |key, value| - expect(ENV[key]).to eq(value) - end - end - - it 'returns hash of loaded environments' do - expect(subject).to eq(expected) - end - end - end - - describe 'load' do - subject { Dotenv.load(*env_files) } - - it_behaves_like 'load' - - context 'when the file does not exist' do - let(:env_files) { ['.env_does_not_exist'] } - - it 'fails silently' do - expect { subject }.not_to raise_error - expect(ENV.keys).to eq(@env_keys) - end - end - end - - describe 'load!' do - subject { Dotenv.load!(*env_files) } - - it_behaves_like 'load' - - context 'when one file exists and one does not' do - let(:env_files) { ['.env', '.env_does_not_exist'] } - - it 'raises an Errno::ENOENT error' do - expect { subject }.to raise_error(Errno::ENOENT) - end - end - end - - describe 'overload' do - let(:env_files) { [fixture_path('plain.env')] } - subject { Dotenv.overload(*env_files) } - it_behaves_like 'load' - - it 'overrides any existing ENV variables' do - ENV['OPTION_A'] = 'predefined' - - subject - - expect(ENV['OPTION_A']).to eq('1') - end - end - - def fixture_path(name) - File.join(File.expand_path('../fixtures', __FILE__), name) - end - - def expand(path) - File.expand_path path - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/exported.env b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/exported.env deleted file mode 100644 index 5821377..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/exported.env +++ /dev/null @@ -1,2 +0,0 @@ -export OPTION_A=2 -export OPTION_B='\n' diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/plain.env b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/plain.env deleted file mode 100644 index c983b06..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/plain.env +++ /dev/null @@ -1,5 +0,0 @@ -OPTION_A=1 -OPTION_B=2 -OPTION_C= 3 -OPTION_D =4 -OPTION_E = 5 diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/quoted.env b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/quoted.env deleted file mode 100644 index a03ce24..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/quoted.env +++ /dev/null @@ -1,8 +0,0 @@ -OPTION_A='1' -OPTION_B='2' -OPTION_C='' -OPTION_D='\n' -OPTION_E="1" -OPTION_F="2" -OPTION_G="" -OPTION_H="\n" diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/yaml.env b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/yaml.env deleted file mode 100644 index ea7ec65..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/fixtures/yaml.env +++ /dev/null @@ -1,4 +0,0 @@ -OPTION_A: 1 -OPTION_B: '2' -OPTION_C: '' -OPTION_D: '\n' diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/spec_helper.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/spec_helper.rb deleted file mode 100644 index 18a5be0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-0.11.1/spec/spec_helper.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'dotenv' - -RSpec.configure do |config| - # Restore the state of ENV after each spec - config.before { @env_keys = ENV.keys } - config.after { ENV.delete_if { |k,v| !@env_keys.include?(k) } } -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/.gitignore b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/.gitignore deleted file mode 100644 index fc398a0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/.gitignore +++ /dev/null @@ -1,18 +0,0 @@ -*.gem -*.rbc -.bundle -.config -.yardoc -.idea -Gemfile.lock -InstalledFiles -_yardoc -coverage -doc/ -lib/bundler/man -pkg -rdoc -spec/reports -test/tmp -test/version_tmp -tmp diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Changelog.md b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Changelog.md deleted file mode 100644 index c7a3d6b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Changelog.md +++ /dev/null @@ -1,11 +0,0 @@ -# Changelog - -## 0.0.2 - Apr 22, 2014 - -* Fix syntax errors after extracting from `dotenv` - -[Full Changelog](https://github.com/bkeepers/dotenv/compare/v0.0.1...v0.0.2) - -## 0.0.1 - Apr 21, 2014 - -* Extract from https://github.com/bkeepers/dotenv diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Gemfile b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Gemfile deleted file mode 100644 index 851fabc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Gemfile +++ /dev/null @@ -1,2 +0,0 @@ -source 'https://rubygems.org' -gemspec diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/LICENSE.txt b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/LICENSE.txt deleted file mode 100644 index 91692b7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 Brandon Keepers - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/README.md b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/README.md deleted file mode 100644 index 53d2e35..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# dotenv-deployment - -[dotenv](https://github.com/bkeepers/dotenv) is designed to load configuration variables into `ENV` in *development*. It does not concern itself with production environments because there are typically better ways to manage configuration in those environments—such as `/etc/environment` managed by [Puppet](https://github.com/puppetlabs/puppet) or [Chef](https://github.com/opscode/chef), `heroku config`, etc. - -However, some find dotenv to be a convenient way to configure applications in staging and production environments. This gem makes it easier to do that by adding support for: - -* [multiple environments](#multiple-environments) -* [Capistrano](#capistrano) - -## Installation - -Add this line to your application's Gemfile: - - gem 'dotenv-deployment' - -And then execute: - - $ bundle - -## Usage - -## Multiple Environments - -By default `.env` will be loaded when `dotenv-deployment` is required. It will not override existing environment variables. - -If you're using Rails or `ENV['RACK_ENV']` is set, an environment-specific file (like `.env.production`) will be loaded and override any existing variables. In a Rails project, `config/*.env` and `config/*.env.#{environment}` will also be loaded. - -## Capistrano - -### Capistrano 2 - -Add the gem to your `config/deploy.rb` file: - -```ruby -require "dotenv/deployment/capistrano" -``` - -**NOTE: If you are upgrading from previous versions of dotenv, you will need to change your require from "dotenv/capistrano" to "dotenv/deployment/capistrano".** - -It will symlink the `.env` located in `/path/to/shared` in the new release. - -### Capistrano 3 - -Just add `.env` to the list of linked files, for example: - -```ruby -set :linked_files, %w{config/database.yml .env} -``` - -## Contributing - -1. Fork it ( http://github.com/bkeepers/dotenv-deployment/fork ) -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Rakefile b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Rakefile deleted file mode 100644 index 2995527..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/Rakefile +++ /dev/null @@ -1 +0,0 @@ -require "bundler/gem_tasks" diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/dotenv-deployment.gemspec b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/dotenv-deployment.gemspec deleted file mode 100644 index 7877a88..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/dotenv-deployment.gemspec +++ /dev/null @@ -1,22 +0,0 @@ -# coding: utf-8 -lib = File.expand_path('../lib', __FILE__) -$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'dotenv/deployment/version' - -Gem::Specification.new do |spec| - spec.name = "dotenv-deployment" - spec.version = Dotenv::Deployment::VERSION - spec.authors = ["Brandon Keepers"] - spec.email = ["brandon@opensoul.org"] - spec.summary = %q{Deployment concerns for dotenv} - spec.homepage = "https://github.com/bkeepers/dotenv-deployment" - spec.license = "MIT" - - spec.files = `git ls-files`.split($/) - spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } - spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) - spec.require_paths = ["lib"] - - spec.add_development_dependency "bundler", "~> 1.5" - spec.add_development_dependency "rake" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment.rb deleted file mode 100644 index 254ddd1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "dotenv" -require "dotenv/deployment/version" - -# Load defaults from .env or *.env in config -Dotenv.load '.env' -Dotenv.load *Dir.glob("#{Rails.root}/config/**/*.env") if defined?(Rails) - -# Override any existing variables if an environment-specific file exists -if environment = ENV['RACK_ENV'] || (defined?(Rails) && Rails.env) - Dotenv.overload ".env.#{environment}" - Dotenv.overload *Dir.glob("#{Rails.root}/config/**/*.env.#{environment}") if defined?(Rails) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/capistrano.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/capistrano.rb deleted file mode 100644 index aaa3231..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/capistrano.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'capistrano/version' - -if defined?(Capistrano::VERSION) && Capistrano::VERSION >= '3.0' - raise 'Please read https://github.com/bkeepers/dotenv-deployment#capistrano to update your dotenv configuration for new Capistrano version' -else - require 'dotenv/deployment/capistrano/recipes' - - Capistrano::Configuration.instance(:must_exist).load do - before "deploy:finalize_update", "dotenv:symlink" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/capistrano/recipes.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/capistrano/recipes.rb deleted file mode 100644 index 1e1b226..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/capistrano/recipes.rb +++ /dev/null @@ -1,12 +0,0 @@ -Capistrano::Configuration.instance(:must_exist).load do - _cset(:dotenv_path){ "#{shared_path}/.env" } - - symlink_args = (role = fetch(:dotenv_role, nil) ? {:roles => role} : {}) - - namespace :dotenv do - desc "Symlink shared .env to current release" - task :symlink, symlink_args do - run "ln -nfs #{dotenv_path} #{release_path}/.env" - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/version.rb b/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/version.rb deleted file mode 100644 index d2b210f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/dotenv-deployment-0.0.2/lib/dotenv/deployment/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Dotenv - module Deployment - VERSION = "0.0.2" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/README.md b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/README.md deleted file mode 100644 index 735a9c5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/README.md +++ /dev/null @@ -1,63 +0,0 @@ -# Foreman - -[![Build Status](https://travis-ci.org/ddollar/foreman.svg?branch=master)](https://travis-ci.org/ddollar/foreman) -[![Code Climate](https://codeclimate.com/github/ddollar/foreman.png)](https://codeclimate.com/github/ddollar/foreman) - -Manage Procfile-based applications - - - - - - - - - - - - - - -
If you have...Install with...
Ruby (MRI, JRuby, Windows)
$ gem install foreman
Mac OS Xforeman.pkg
- -## Installation - - $ gem install foreman - -Ruby users should take care *not* to install foreman in their project's `Gemfile`. - -## Getting Started - -* http://blog.daviddollar.org/2011/05/06/introducing-foreman.html - -## Supported Ruby versions - -* 1.9.3 -* 2.0.0 - -## Documentation - -* [man page](http://ddollar.github.com/foreman) -* [wiki](http://github.com/ddollar/foreman/wiki) -* [changelog](https://github.com/ddollar/foreman/blob/master/Changelog.md) - -## Ports - -* [shoreman](https://github.com/hecticjeff/shoreman) - shell -* [honcho](https://github.com/nickstenning/honcho) - python -* [norman](https://github.com/josh/norman) - node.js -* [forego](https://github.com/ddollar/forego) - Go - -## Authors - -#### Created and maintained by -David Dollar - -#### Patches contributed by -[Contributor List](https://github.com/ddollar/foreman/contributors) - -## License - -Foreman is licensed under the MIT license. - -See LICENSE for the full license text. diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/bin/foreman b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/bin/foreman deleted file mode 100755 index 18f41af..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/bin/foreman +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env ruby - -$:.unshift File.expand_path("../../lib", __FILE__) - -require "foreman/cli" - -Foreman::CLI.start diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/bin/foreman-runner b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/bin/foreman-runner deleted file mode 100755 index 9709a1d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/bin/foreman-runner +++ /dev/null @@ -1,41 +0,0 @@ -#!/bin/sh -# -#/ Usage: foreman-runner [-d ] [-p] [...] -#/ -#/ Run a command with exec, optionally changing directory first - -set -e - -error() { - echo $@ >&2 - exit 1 -} - -usage() { - cat $0 | grep '^#/' | cut -c4- - exit -} - -read_profile="" - -while getopts ":hd:p" OPT; do - case $OPT in - d) cd "$OPTARG" ;; - p) read_profile="1" ;; - h) usage ;; - \?) error "invalid option: -$OPTARG" ;; - :) error "option -$OPTARG requires an argument" ;; - esac -done - -shift $((OPTIND-1)) - -[ -z "$1" ] && usage - -if [ "$read_profile" = "1" ]; then - if [ -f .profile ]; then - . ./.profile - fi -fi - -exec "$@" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/Procfile b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/Procfile deleted file mode 100644 index 219cd90..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/Procfile +++ /dev/null @@ -1,4 +0,0 @@ -ticker: ruby ./ticker $PORT -error: ruby ./error -utf8: ruby ./utf8 -spawner: ./spawner diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/Procfile.without_colon b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/Procfile.without_colon deleted file mode 100644 index d6451a9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/Procfile.without_colon +++ /dev/null @@ -1,2 +0,0 @@ -ticker ./ticker $PORT -error ./error \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/error b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/error deleted file mode 100755 index 2ef00b4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/error +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env ruby - -$stdout.sync = true - -puts "will error in 10s" -sleep 5 -raise "Dying" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/log/neverdie.log b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/log/neverdie.log deleted file mode 100644 index a8ce255..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/log/neverdie.log +++ /dev/null @@ -1,4 +0,0 @@ -tick -tick -./never_die:6:in `sleep': Interrupt - from ./never_die:6 diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/spawnee b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/spawnee deleted file mode 100755 index afdcf49..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/spawnee +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh - -NAME="$1" - -sigterm() { - echo "$NAME: got sigterm" -} - -#trap sigterm SIGTERM - -while true; do - echo "$NAME: ping $$" - sleep 1 -done diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/spawner b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/spawner deleted file mode 100755 index 8c1a6fc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/spawner +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -./spawnee A & -./spawnee B & -./spawnee C & - -wait diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/ticker b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/ticker deleted file mode 100755 index fe0d629..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/ticker +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env ruby - -$stdout.sync = true - -%w( SIGINT SIGTERM ).each do |signal| - trap(signal) do - puts "received #{signal} but i'm ignoring it!" - end -end - -while true - puts "tick: #{ARGV.inspect} -- FOO:#{ENV["FOO"]}" - sleep 1 -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/utf8 b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/utf8 deleted file mode 100755 index 00b90a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/example/utf8 +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env ruby -# encoding: BINARY - -$stdout.sync = true - -while true - puts "\u65e5\u672c\u8a9e\u6587\u5b57\u5217" - puts "\u0915\u0932\u094d\u0907\u0928\u0643\u0637\u0628\u041a\u0430\u043b\u0438\u043d\u0430" - puts "\xff\x03" - sleep 1 -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/bluepill/master.pill.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/bluepill/master.pill.erb deleted file mode 100644 index 9403902..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/bluepill/master.pill.erb +++ /dev/null @@ -1,28 +0,0 @@ -Bluepill.application("<%= app %>", :foreground => false, :log_file => "/var/log/bluepill.log") do |app| - - app.uid = "<%= user %>" - app.gid = "<%= user %>" - -<% engine.each_process do |name, process| %> -<% 1.upto(engine.formation[name]) do |num| %> - <% port = engine.port_for(process, num) %> - app.process("<%= name %>-<%= num %>") do |process| - process.start_command = %Q{<%= process.command %>} - - process.working_dir = "<%= engine.root %>" - process.daemonize = true - process.environment = <%= engine.env.merge("PORT" => port.to_s).inspect %> - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "<%= log %>/<%= app %>-<%= name %>-<%= num %>.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "<%= app %>-<%= name %>" - end -<% end %> -<% end %> -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/master.conf.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/master.conf.erb deleted file mode 100644 index 0b2d2f7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/master.conf.erb +++ /dev/null @@ -1,14 +0,0 @@ -pre-start script - -bash << "EOF" -mkdir -p <%= log %> -chown -R <%= user %> <%= log %> -mkdir -p <%= run %> -chown -R <%= user %> <%= run %> -EOF - -end script - -start on runlevel [2345] - -stop on runlevel [016] diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/process.conf.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/process.conf.erb deleted file mode 100644 index b133bbe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/process.conf.erb +++ /dev/null @@ -1,8 +0,0 @@ -start on starting <%= app %>-<%= name.gsub('_', '-') %> -stop on stopping <%= app %>-<%= name.gsub('_', '-') %> -respawn - -env PORT=<%= port %><% engine.env.each_pair do |var, env| %> -env <%= var.upcase %>=<%= env %><% end %> - -exec start-stop-daemon --start --chuid <%= user %> --chdir <%= engine.root %> --make-pidfile --pidfile <%= run %>/<%= app %>-<%= name %>-<%= num %>.pid --exec <%= executable %><%= arguments %> >> <%= log %>/<%= app %>-<%= name %>-<%= num %>.log 2>&1 diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/process_master.conf.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/process_master.conf.erb deleted file mode 100644 index c9cc851..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/daemon/process_master.conf.erb +++ /dev/null @@ -1,2 +0,0 @@ -start on starting <%= app %> -stop on stopping <%= app %> diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/launchd/launchd.plist.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/launchd/launchd.plist.erb deleted file mode 100644 index fe02308..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/launchd/launchd.plist.erb +++ /dev/null @@ -1,33 +0,0 @@ - - - - - Label - <%= "#{app}-#{name}-#{num}" %> - EnvironmentVariables - - <%- engine.env.merge("PORT" => port).each_pair do |var,env| -%> - <%= var.upcase %> - <%= env %> - <%- end -%> - - ProgramArguments - - <%- command_args.each do |command| -%> - <%= command %> - <%- end -%> - - KeepAlive - - RunAtLoad - - StandardOutPath - <%= log %>/<%= app %>-<%= name %>-<%=num%>.log - StandardErrorPath - <%= log %>/<%= app %>-<%= name %>-<%=num%>.log - UserName - <%= user %> - WorkingDirectory - <%= engine.root %> - - diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/runit/log/run.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/runit/log/run.erb deleted file mode 100644 index f5e3a2b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/runit/log/run.erb +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=<%= log %>/<%= name %>-<%= num %> - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown <%= user %> "$LOG" -exec chpst -u <%= user %> svlogd "$LOG" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/runit/run.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/runit/run.erb deleted file mode 100644 index 4d6ceed..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/runit/run.erb +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd <%= engine.root %> -exec 2>&1 -exec chpst -u <%= user %> -e <%= File.join(location, "#{process_directory}/env") %> <%= process.command %> diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/supervisord/app.conf.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/supervisord/app.conf.erb deleted file mode 100644 index 22fd63d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/supervisord/app.conf.erb +++ /dev/null @@ -1,27 +0,0 @@ -<% -app_names = [] -engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - full_name = "#{app}-#{name}-#{num}" - environment = engine.env.merge("PORT" => port.to_s).map do |key, value| - "#{key}=\"#{shell_quote(value)}\"" - end - app_names << full_name -%> -[program:<%= full_name %>] -command=<%= process.command %> -autostart=true -autorestart=true -stopsignal=QUIT -stdout_logfile=<%= log %>/<%= name %>-<%= num %>.log -stderr_logfile=<%= log %>/<%= name %>-<%= num %>.error.log -user=<%= user %> -directory=<%= engine.root %> -environment=<%= environment.join(',') %><% - end -end -%> - -[group:<%= app %>] -programs=<%= app_names.join(',') %> diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/master.target.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/master.target.erb deleted file mode 100644 index d054c29..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/master.target.erb +++ /dev/null @@ -1,6 +0,0 @@ -[Unit] -StopWhenUnneeded=true -Wants=<%= process_master_names.join(' ') %> - -[Install] -WantedBy=multi-user.target diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/process.service.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/process.service.erb deleted file mode 100644 index aa2668d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/process.service.erb +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -StopWhenUnneeded=true - -[Service] -User=<%= user %> -WorkingDirectory=<%= engine.root %> -Environment=PORT=<%= port %><% engine.env.each_pair do |var,env| %> -Environment=<%= var.upcase %>=<%= env %><% end %> -ExecStart=/bin/bash -lc '<%= process.command %>' -Restart=always -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=process diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/process_master.target.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/process_master.target.erb deleted file mode 100644 index 7b3b9bb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/systemd/process_master.target.erb +++ /dev/null @@ -1,3 +0,0 @@ -[Unit] -StopWhenUnneeded=true -Wants=<%= process_names.join(' ') %> diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/master.conf.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/master.conf.erb deleted file mode 100644 index 7bf1666..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/master.conf.erb +++ /dev/null @@ -1,2 +0,0 @@ -start on runlevel [2345] -stop on runlevel [!2345] diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/process.conf.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/process.conf.erb deleted file mode 100644 index 5bcd67e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/process.conf.erb +++ /dev/null @@ -1,14 +0,0 @@ -start on starting <%= app %>-<%= name %> -stop on stopping <%= app %>-<%= name %> -respawn - -env PORT=<%= port %> -<% engine.env.each do |name,value| -%> -env <%= name.upcase %>='<%= value.gsub(/'/, "'\"'\"'") %>' -<% end -%> - -setuid <%= user %> - -chdir <%= engine.root %> - -exec <%= process.command %> diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/process_master.conf.erb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/process_master.conf.erb deleted file mode 100644 index c9cc851..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/data/export/upstart/process_master.conf.erb +++ /dev/null @@ -1,2 +0,0 @@ -start on starting <%= app %> -stop on stopping <%= app %> diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman.rb deleted file mode 100644 index ca3f754..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "foreman/version" - -module Foreman - - def self.runner - File.expand_path("../../bin/foreman-runner", __FILE__) - end - - def self.ruby_18? - defined?(RUBY_VERSION) and RUBY_VERSION =~ /^1\.8\.\d+/ - end - - def self.windows? - defined?(RUBY_PLATFORM) and RUBY_PLATFORM =~ /(win|w)32$/ - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/cli.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/cli.rb deleted file mode 100644 index 3b2e3aa..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/cli.rb +++ /dev/null @@ -1,157 +0,0 @@ -require "foreman" -require "foreman/helpers" -require "foreman/engine" -require "foreman/engine/cli" -require "foreman/export" -require "foreman/version" -require "shellwords" -require "yaml" -require "thor" - -class Foreman::CLI < Thor - - include Foreman::Helpers - - map ["-v", "--version"] => :version - - class_option :procfile, :type => :string, :aliases => "-f", :desc => "Default: Procfile" - class_option :root, :type => :string, :aliases => "-d", :desc => "Default: Procfile directory" - - desc "start [PROCESS]", "Start the application (or a specific PROCESS)" - - method_option :color, :type => :boolean, :aliases => "-c", :desc => "Force color to be enabled" - method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env" - method_option :formation, :type => :string, :aliases => "-m", :banner => '"alpha=5,bar=3"' - method_option :port, :type => :numeric, :aliases => "-p" - method_option :timeout, :type => :numeric, :aliases => "-t", :desc => "Specify the amount of time (in seconds) processes have to shutdown gracefully before receiving a SIGKILL, defaults to 5." - - class << self - # Hackery. Take the run method away from Thor so that we can redefine it. - def is_thor_reserved_word?(word, type) - return false if word == "run" - super - end - end - - def start(process=nil) - check_procfile! - load_environment! - engine.load_procfile(procfile) - engine.options[:formation] = "#{process}=1" if process - engine.start - end - - desc "export FORMAT LOCATION", "Export the application to another process management format" - - method_option :app, :type => :string, :aliases => "-a" - method_option :log, :type => :string, :aliases => "-l" - method_option :run, :type => :string, :aliases => "-r", :desc => "Specify the pid file directory, defaults to /var/run/" - method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env" - method_option :port, :type => :numeric, :aliases => "-p" - method_option :user, :type => :string, :aliases => "-u" - method_option :template, :type => :string, :aliases => "-t" - method_option :concurrency, :type => :string, :aliases => "-c", :banner => '"alpha=5,bar=3"' - - def export(format, location=nil) - check_procfile! - load_environment! - engine.load_procfile(procfile) - formatter = Foreman::Export.formatter(format) - formatter.new(location, engine, options).export - rescue Foreman::Export::Exception => ex - error ex.message - end - - desc "check", "Validate your application's Procfile" - - def check - check_procfile! - engine.load_procfile(procfile) - error "no processes defined" unless engine.processes.length > 0 - puts "valid procfile detected (#{engine.process_names.join(', ')})" - end - - desc "run COMMAND [ARGS...]", "Run a command using your application's environment" - - method_option :env, :type => :string, :aliases => "-e", :desc => "Specify an environment file to load, defaults to .env" - - def run(*args) - load_environment! - - if File.exist?(procfile) - engine.load_procfile(procfile) - end - - pid = fork do - begin - engine.env.each { |k,v| ENV[k] = v } - if args.size == 1 && process = engine.process(args.first) - process.exec(:env => engine.env) - else - exec args.shelljoin - end - rescue Errno::EACCES - error "not executable: #{args.first}" - rescue Errno::ENOENT - error "command not found: #{args.first}" - end - end - Process.wait(pid) - exit $?.exitstatus - rescue Interrupt - end - - desc "version", "Display Foreman gem version" - - def version - puts Foreman::VERSION - end - - no_tasks do - def engine - @engine ||= begin - engine_class = Foreman::Engine::CLI - engine = engine_class.new(options) - engine - end - end - end - -private ###################################################################### - - def error(message) - puts "ERROR: #{message}" - exit 1 - end - - def check_procfile! - error("#{procfile} does not exist.") unless File.exist?(procfile) - end - - def load_environment! - if options[:env] - options[:env].split(",").each do |file| - engine.load_env file - end - else - default_env = File.join(engine.root, ".env") - engine.load_env default_env if File.exists?(default_env) - end - end - - def procfile - case - when options[:procfile] then options[:procfile] - when options[:root] then File.expand_path(File.join(options[:root], "Procfile")) - else "Procfile" - end - end - - def options - original_options = super - return original_options unless File.exists?(".foreman") - defaults = ::YAML::load_file(".foreman") || {} - Thor::CoreExt::HashWithIndifferentAccess.new(defaults.merge(original_options)) - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/distribution.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/distribution.rb deleted file mode 100644 index 2d5650e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/distribution.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Foreman - module Distribution - def self.files - Dir[File.expand_path("../../../{bin,data,lib}/**/*", __FILE__)].select do |file| - File.file?(file) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/engine.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/engine.rb deleted file mode 100644 index 4122a58..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/engine.rb +++ /dev/null @@ -1,439 +0,0 @@ -require "foreman" -require "foreman/process" -require "foreman/procfile" -require "dotenv" -require "tempfile" -require "timeout" -require "fileutils" -require "thread" - -class Foreman::Engine - - # The signals that the engine cares about. - # - HANDLED_SIGNALS = [ :TERM, :INT, :HUP ] - - attr_reader :env - attr_reader :options - attr_reader :processes - - # Create an +Engine+ for running processes - # - # @param [Hash] options - # - # @option options [String] :formation (all=1) The process formation to use - # @option options [Fixnum] :port (5000) The base port to assign to processes - # @option options [String] :root (Dir.pwd) The root directory from which to run processes - # - def initialize(options={}) - @options = options.dup - - @options[:formation] ||= (options[:concurrency] || "all=1") - @options[:timeout] ||= 5 - - @env = {} - @mutex = Mutex.new - @names = {} - @processes = [] - @running = {} - @readers = {} - - # Self-pipe for deferred signal-handling (ala djb: http://cr.yp.to/docs/selfpipe.html) - reader, writer = create_pipe - reader.close_on_exec = true if reader.respond_to?(:close_on_exec) - writer.close_on_exec = true if writer.respond_to?(:close_on_exec) - @selfpipe = { :reader => reader, :writer => writer } - - # Set up a global signal queue - # http://blog.rubybestpractices.com/posts/ewong/016-Implementing-Signal-Handlers.html - Thread.main[:signal_queue] = [] - end - - # Start the processes registered to this +Engine+ - # - def start - register_signal_handlers - startup - spawn_processes - watch_for_output - sleep 0.1 - watch_for_termination { terminate_gracefully } - shutdown - end - - # Set up deferred signal handlers - # - def register_signal_handlers - HANDLED_SIGNALS.each do |sig| - if ::Signal.list.include? sig.to_s - trap(sig) { Thread.main[:signal_queue] << sig ; notice_signal } - end - end - end - - # Unregister deferred signal handlers - # - def restore_default_signal_handlers - HANDLED_SIGNALS.each do |sig| - trap(sig, :DEFAULT) if ::Signal.list.include? sig.to_s - end - end - - # Wake the main thread up via the selfpipe when there's a signal - # - def notice_signal - @selfpipe[:writer].write_nonblock( '.' ) - rescue Errno::EAGAIN - # Ignore writes that would block - rescue Errno::EINT - # Retry if another signal arrived while writing - retry - end - - # Invoke the real handler for signal +sig+. This shouldn't be called directly - # by signal handlers, as it might invoke code which isn't re-entrant. - # - # @param [Symbol] sig the name of the signal to be handled - # - def handle_signal(sig) - case sig - when :TERM - handle_term_signal - when :INT - handle_interrupt - when :HUP - handle_hangup - else - system "unhandled signal #{sig}" - end - end - - # Handle a TERM signal - # - def handle_term_signal - puts "SIGTERM received" - terminate_gracefully - end - - # Handle an INT signal - # - def handle_interrupt - puts "SIGINT received" - terminate_gracefully - end - - # Handle a HUP signal - # - def handle_hangup - puts "SIGHUP received" - terminate_gracefully - end - - # Register a process to be run by this +Engine+ - # - # @param [String] name A name for this process - # @param [String] command The command to run - # @param [Hash] options - # - # @option options [Hash] :env A custom environment for this process - # - def register(name, command, options={}) - options[:env] ||= env - options[:cwd] ||= File.dirname(command.split(" ").first) - process = Foreman::Process.new(command, options) - @names[process] = name - @processes << process - end - - # Clear the processes registered to this +Engine+ - # - def clear - @names = {} - @processes = [] - end - - # Register processes by reading a Procfile - # - # @param [String] filename A Procfile from which to read processes to register - # - def load_procfile(filename) - options[:root] ||= File.dirname(filename) - Foreman::Procfile.new(filename).entries do |name, command| - register name, command, :cwd => options[:root] - end - self - end - - # Load a .env file into the +env+ for this +Engine+ - # - # @param [String] filename A .env file to load into the environment - # - def load_env(filename) - @env.update Dotenv::Environment.new(filename) - end - - # Send a signal to all processes started by this +Engine+ - # - # @param [String] signal The signal to send to each process - # - def kill_children(signal="SIGTERM") - if Foreman.windows? - @running.each do |pid, (process, index)| - system "sending #{signal} to #{name_for(pid)} at pid #{pid}" - begin - Process.kill(signal, pid) - rescue Errno::ESRCH, Errno::EPERM - end - end - else - begin - Process.kill signal, *@running.keys unless @running.empty? - rescue Errno::ESRCH, Errno::EPERM - end - end - end - - # Send a signal to the whole process group. - # - # @param [String] signal The signal to send - # - def killall(signal="SIGTERM") - if Foreman.windows? - kill_children(signal) - else - begin - Process.kill "-#{signal}", Process.pid - rescue Errno::ESRCH, Errno::EPERM - end - end - end - - # Get the process formation - # - # @returns [Fixnum] The formation count for the specified process - # - def formation - @formation ||= parse_formation(options[:formation]) - end - - # List the available process names - # - # @returns [Array] A list of process names - # - def process_names - @processes.map { |p| @names[p] } - end - - # Get the +Process+ for a specifid name - # - # @param [String] name The process name - # - # @returns [Foreman::Process] The +Process+ for the specified name - # - def process(name) - @names.invert[name] - end - - # Yield each +Process+ in order - # - def each_process - process_names.each do |name| - yield name, process(name) - end - end - - # Get the root directory for this +Engine+ - # - # @returns [String] The root directory - # - def root - File.expand_path(options[:root] || Dir.pwd) - end - - # Get the port for a given process and offset - # - # @param [Foreman::Process] process A +Process+ associated with this engine - # @param [Fixnum] instance The instance of the process - # - # @returns [Fixnum] port The port to use for this instance of this process - # - def port_for(process, instance, base=nil) - if base - base + (@processes.index(process.process) * 100) + (instance - 1) - else - base_port + (@processes.index(process) * 100) + (instance - 1) - end - end - - # Get the base port for this foreman instance - # - # @returns [Fixnum] port The base port - # - def base_port - (options[:port] || env["PORT"] || ENV["PORT"] || 5000).to_i - end - - # deprecated - def environment - env - end - -private - -### Engine API ###################################################### - - def startup - raise TypeError, "must use a subclass of Foreman::Engine" - end - - def output(name, data) - raise TypeError, "must use a subclass of Foreman::Engine" - end - - def shutdown - raise TypeError, "must use a subclass of Foreman::Engine" - end - -## Helpers ########################################################## - - def create_pipe - IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY") - end - - def name_for(pid) - process, index = @running[pid] - name_for_index(process, index) - end - - def name_for_index(process, index) - [ @names[process], index.to_s ].compact.join(".") - end - - def parse_formation(formation) - pairs = formation.to_s.gsub(/\s/, "").split(",") - - pairs.inject(Hash.new(0)) do |ax, pair| - process, amount = pair.split("=") - process == "all" ? ax.default = amount.to_i : ax[process] = amount.to_i - ax - end - end - - def output_with_mutex(name, message) - @mutex.synchronize do - output name, message - end - end - - def system(message) - output_with_mutex "system", message - end - - def termination_message_for(status) - if status.exited? - "exited with code #{status.exitstatus}" - elsif status.signaled? - "terminated by SIG#{Signal.list.invert[status.termsig]}" - else - "died a mysterious death" - end - end - - def flush_reader(reader) - until reader.eof? - data = reader.gets - output_with_mutex name_for(@readers.key(reader)), data - end - end - -## Engine ########################################################### - - def spawn_processes - @processes.each do |process| - 1.upto(formation[@names[process]]) do |n| - reader, writer = create_pipe - begin - pid = process.run(:output => writer, :env => { - "PORT" => port_for(process, n).to_s, - "PS" => name_for_index(process, n) - }) - writer.puts "started with pid #{pid}" - rescue Errno::ENOENT - writer.puts "unknown command: #{process.command}" - end - @running[pid] = [process, n] - @readers[pid] = reader - end - end - end - - def read_self_pipe - @selfpipe[:reader].read_nonblock(11) - rescue Errno::EAGAIN, Errno::EINTR => err - # ignore - end - - def handle_signals - while sig = Thread.main[:signal_queue].shift - self.handle_signal(sig) - end - end - - def handle_io(readers) - readers.each do |reader| - next if reader == @selfpipe[:reader] - - if reader.eof? - @readers.delete_if { |key, value| value == reader } - else - data = reader.gets - output_with_mutex name_for(@readers.invert[reader]), data - end - end - end - - def watch_for_output - Thread.new do - begin - loop do - io = IO.select([@selfpipe[:reader]] + @readers.values, nil, nil, 30) - read_self_pipe - handle_signals - handle_io(io ? io.first : []) - end - rescue Exception => ex - puts ex.message - puts ex.backtrace - end - end - end - - def watch_for_termination - pid, status = Process.wait2 - output_with_mutex name_for(pid), termination_message_for(status) - @running.delete(pid) - yield if block_given? - pid - rescue Errno::ECHILD - end - - def terminate_gracefully - return if @terminating - restore_default_signal_handlers - @terminating = true - if Foreman.windows? - system "sending SIGKILL to all processes" - kill_children "SIGKILL" - else - system "sending SIGTERM to all processes" - kill_children "SIGTERM" - end - Timeout.timeout(options[:timeout]) do - watch_for_termination while @running.length > 0 - end - rescue Timeout::Error - system "sending SIGKILL to all processes" - kill_children "SIGKILL" - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/engine/cli.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/engine/cli.rb deleted file mode 100644 index e52d03b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/engine/cli.rb +++ /dev/null @@ -1,104 +0,0 @@ -require "foreman/engine" - -class Foreman::Engine::CLI < Foreman::Engine - - module Color - - ANSI = { - :reset => 0, - :black => 30, - :red => 31, - :green => 32, - :yellow => 33, - :blue => 34, - :magenta => 35, - :cyan => 36, - :white => 37, - :bright_black => 30, - :bright_red => 31, - :bright_green => 32, - :bright_yellow => 33, - :bright_blue => 34, - :bright_magenta => 35, - :bright_cyan => 36, - :bright_white => 37, - } - - def self.enable(io, force=false) - io.extend(self) - @@color_force = force - end - - def color? - return true if @@color_force - return false if Foreman.windows? - return false unless self.respond_to?(:isatty) - self.isatty && ENV["TERM"] - end - - def color(name) - return "" unless color? - return "" unless ansi = ANSI[name.to_sym] - "\e[#{ansi}m" - end - - end - - FOREMAN_COLORS = %w( cyan yellow green magenta red blue bright_cyan bright_yellow - bright_green bright_magenta bright_red bright_blue ) - - def startup - @colors = map_colors - proctitle "foreman: master" unless Foreman.windows? - Color.enable($stdout, options[:color]) - end - - def output(name, data) - data.to_s.lines.map(&:chomp).each do |message| - output = "" - output += $stdout.color(@colors[name.split(".").first].to_sym) - output += "#{Time.now.strftime("%H:%M:%S")} #{pad_process_name(name)} | " - output += $stdout.color(:reset) - output += message - $stdout.puts output - $stdout.flush - end - rescue Errno::EPIPE - terminate_gracefully - end - - def shutdown - end - -private - - def name_padding - @name_padding ||= begin - index_padding = @names.values.map { |n| formation[n] }.max.to_s.length + 1 - name_padding = @names.values.map { |n| n.length + index_padding }.sort.last - [ 6, name_padding ].max - end - end - - def pad_process_name(name) - name.ljust(name_padding, " ") - end - - def map_colors - colors = Hash.new("white") - @names.values.each_with_index do |name, index| - colors[name] = FOREMAN_COLORS[index % FOREMAN_COLORS.length] - end - colors["system"] = "bright_white" - colors - end - - def proctitle(title) - $0 = title - end - - def termtitle(title) - printf("\033]0;#{title}\007") unless Foreman.windows? - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export.rb deleted file mode 100644 index 04bf71c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export.rb +++ /dev/null @@ -1,36 +0,0 @@ -require "foreman" -require "foreman/helpers" -require "pathname" - -module Foreman::Export - extend Foreman::Helpers - - class Exception < ::Exception; end - - def self.formatter(format) - begin - require "foreman/export/#{ format.tr('-', '_') }" - classy_format = classify(format) - formatter = constantize("Foreman::Export::#{ classy_format }") - rescue NameError => ex - error "Unknown export format: #{format} (no class Foreman::Export::#{ classy_format })." - rescue LoadError => ex - error "Unknown export format: #{format} (unable to load file 'foreman/export/#{ format.tr('-', '_') }')." - end - end - - def self.error(message) - raise Foreman::Export::Exception.new(message) - end - -end - -require "foreman/export/base" -require "foreman/export/inittab" -require "foreman/export/upstart" -require "foreman/export/daemon" -require "foreman/export/bluepill" -require "foreman/export/runit" -require "foreman/export/supervisord" -require "foreman/export/launchd" -require "foreman/export/systemd" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/base.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/base.rb deleted file mode 100644 index f8b8a6f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/base.rb +++ /dev/null @@ -1,156 +0,0 @@ -require "foreman/export" -require "ostruct" -require "pathname" -require "shellwords" - -class Foreman::Export::Base - - attr_reader :location - attr_reader :engine - attr_reader :options - attr_reader :formation - - # deprecated - attr_reader :port - - def initialize(location, engine, options={}) - @location = location - @engine = engine - @options = options.dup - @formation = engine.formation - - # deprecated - def port - Foreman::Export::Base.warn_deprecation! - engine.base_port - end - - # deprecated - def template - Foreman::Export::Base.warn_deprecation! - options[:template] - end - - # deprecated - def @engine.procfile - Foreman::Export::Base.warn_deprecation! - @processes.map do |process| - OpenStruct.new( - :name => @names[process], - :process => process - ) - end - end - end - - def export - error("Must specify a location") unless location - FileUtils.mkdir_p(location) rescue error("Could not create: #{location}") - chown user, log - chown user, run - end - - def app - options[:app] || "app" - end - - def log - options[:log] || "/var/log/#{app}" - end - - def run - options[:run] || "/var/run/#{app}" - end - - def user - options[:user] || app - end - -private ###################################################################### - - def self.warn_deprecation! - @@deprecation_warned ||= false - return if @@deprecation_warned - puts "WARNING: Using deprecated exporter interface. Please update your exporter" - puts "the interface shown in the upstart exporter:" - puts - puts "https://github.com/ddollar/foreman/blob/master/lib/foreman/export/upstart.rb" - puts "https://github.com/ddollar/foreman/blob/master/data/export/upstart/process.conf.erb" - puts - @@deprecation_warned = true - end - - def chown user, dir - FileUtils.chown user, nil, dir - rescue - error("Could not chown #{dir} to #{user}") unless File.writable?(dir) || ! File.exists?(dir) - end - - def error(message) - raise Foreman::Export::Exception.new(message) - end - - def say(message) - puts "[foreman export] %s" % message - end - - def clean(filename) - return unless File.exists?(filename) - say "cleaning up: #{filename}" - FileUtils.rm(filename) - end - - def shell_quote(value) - Shellwords.escape(value) - end - - # deprecated - def old_export_template(exporter, file, template_root) - if template_root && File.exist?(file_path = File.join(template_root, file)) - File.read(file_path) - elsif File.exist?(file_path = File.expand_path(File.join("~/.foreman/templates", file))) - File.read(file_path) - else - File.read(File.expand_path("../../../../data/export/#{exporter}/#{file}", __FILE__)) - end - end - - def export_template(name, file=nil, template_root=nil) - if file && template_root - old_export_template name, file, template_root - else - name_without_first = name.split("/")[1..-1].join("/") - matchers = [] - matchers << File.join(options[:template], name_without_first) if options[:template] - matchers << File.expand_path("~/.foreman/templates/#{name}") - matchers << File.expand_path("../../../../data/export/#{name}", __FILE__) - File.read(matchers.detect { |m| File.exists?(m) }) - end - end - - def write_template(name, target, binding) - compiled = ERB.new(export_template(name), nil, '-').result(binding) - write_file target, compiled - end - - def chmod(mode, file) - say "setting #{file} to mode #{mode}" - FileUtils.chmod mode, File.join(location, file) - end - - def create_directory(dir) - say "creating: #{dir}" - FileUtils.mkdir_p(File.join(location, dir)) - end - - def write_file(filename, contents) - say "writing: #{filename}" - - filename = File.join(location, filename) unless Pathname.new(filename).absolute? - - File.open(filename, "w") do |file| - file.puts contents - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/bluepill.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/bluepill.rb deleted file mode 100644 index 1372b5a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/bluepill.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Bluepill < Foreman::Export::Base - - def export - super - clean "#{location}/#{app}.pill" - write_template "bluepill/master.pill.erb", "#{app}.pill", binding - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/daemon.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/daemon.rb deleted file mode 100644 index 40f623c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/daemon.rb +++ /dev/null @@ -1,28 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Daemon < Foreman::Export::Base - - def export - super - - (Dir["#{location}/#{app}-*.conf"] << "#{location}/#{app}.conf").each do |file| - clean file - end - - write_template "daemon/master.conf.erb", "#{app}.conf", binding - - engine.each_process do |name, process| - next if engine.formation[name] < 1 - write_template "daemon/process_master.conf.erb", "#{app}-#{name}.conf", binding - - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - arguments = process.command.split(" ") - executable = arguments.slice!(0) - arguments = arguments.size > 0 ? " -- #{arguments.join(' ')}" : "" - write_template "daemon/process.conf.erb", "#{app}-#{name}-#{num}.conf", binding - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/inittab.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/inittab.rb deleted file mode 100644 index d8b1f4d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/inittab.rb +++ /dev/null @@ -1,42 +0,0 @@ -require "foreman/export" - -class Foreman::Export::Inittab < Foreman::Export::Base - - def export - error("Must specify a location") unless location - - inittab = [] - inittab << "# ----- foreman #{app} processes -----" - - index = 1 - engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - id = app.slice(0, 2).upcase + sprintf("%02d", index) - port = engine.port_for(process, num) - - commands = [] - commands << "cd #{engine.root}" - commands << "export PORT=#{port}" - engine.env.each_pair do |var, env| - commands << "export #{var.upcase}=#{shell_quote(env)}" - end - commands << "#{process.command} >> #{log}/#{name}-#{num}.log 2>&1" - - inittab << "#{id}:4:respawn:/bin/su - #{user} -c '#{commands.join(";")}'" - index += 1 - end - end - - inittab << "# ----- end foreman #{app} processes -----" - - inittab = inittab.join("\n") + "\n" - - if location == "-" - puts inittab - else - say "writing: #{location}" - File.open(location, "w") { |file| file.puts inittab } - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/launchd.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/launchd.rb deleted file mode 100644 index b21a675..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/launchd.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Launchd < Foreman::Export::Base - - def export - super - engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - command_args = process.command.split(/\s+/).map{|arg| - case arg - when "$PORT" then port - else arg - end - } - write_template "launchd/launchd.plist.erb", "#{app}-#{name}-#{num}.plist", binding - end - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/runit.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/runit.rb deleted file mode 100644 index ce22d0e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/runit.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Runit < Foreman::Export::Base - - ENV_VARIABLE_REGEX = /([a-zA-Z_]+[a-zA-Z0-9_]*)=(\S+)/ - - def export - super - - engine.each_process do |name, process| - 1.upto(engine.formation[name]) do |num| - process_directory = "#{app}-#{name}-#{num}" - - create_directory process_directory - create_directory "#{process_directory}/env" - create_directory "#{process_directory}/log" - - write_template "runit/run.erb", "#{process_directory}/run", binding - chmod 0755, "#{process_directory}/run" - - port = engine.port_for(process, num) - engine.env.merge("PORT" => port.to_s).each do |key, value| - write_file "#{process_directory}/env/#{key}", value - end - - write_template "runit/log/run.erb", "#{process_directory}/log/run", binding - chmod 0755, "#{process_directory}/log/run" - end - end - - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/supervisord.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/supervisord.rb deleted file mode 100644 index 8a3a4dd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/supervisord.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Supervisord < Foreman::Export::Base - - def export - super - - Dir["#{location}/#{app}*.conf"].each do |file| - clean file - end - - write_template "supervisord/app.conf.erb", "#{app}.conf", binding - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/systemd.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/systemd.rb deleted file mode 100644 index 78a643c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/systemd.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Systemd < Foreman::Export::Base - - def export - super - - Dir["#{location}/#{app}*.target"].concat(Dir["#{location}/#{app}*.service"]).each do |file| - clean file - end - - process_master_names = [] - - engine.each_process do |name, process| - next if engine.formation[name] < 1 - - process_names = [] - - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - write_template "systemd/process.service.erb", "#{app}-#{name}-#{num}.service", binding - process_names << "#{app}-#{name}-#{num}.service" - end - - write_template "systemd/process_master.target.erb", "#{app}-#{name}.target", binding - process_master_names << "#{app}-#{name}.target" - end - - write_template "systemd/master.target.erb", "#{app}.target", binding - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/upstart.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/upstart.rb deleted file mode 100644 index b38b798..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/export/upstart.rb +++ /dev/null @@ -1,39 +0,0 @@ -require "erb" -require "foreman/export" - -class Foreman::Export::Upstart < Foreman::Export::Base - - def export - super - - (Dir["#{location}/#{app}-*.conf"] << "#{location}/#{app}.conf").each do |file| - clean file - end - - write_template master_template, "#{app}.conf", binding - - engine.each_process do |name, process| - next if engine.formation[name] < 1 - write_template process_master_template, "#{app}-#{name}.conf", binding - - 1.upto(engine.formation[name]) do |num| - port = engine.port_for(process, num) - write_template process_template, "#{app}-#{name}-#{num}.conf", binding - end - end - end - - private - - def master_template - "upstart/master.conf.erb" - end - - def process_master_template - "upstart/process_master.conf.erb" - end - - def process_template - "upstart/process.conf.erb" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/helpers.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/helpers.rb deleted file mode 100644 index 95b6e17..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/helpers.rb +++ /dev/null @@ -1,45 +0,0 @@ -module Foreman::Helpers - # Copied whole sale from, https://github.com/defunkt/resque/ - - # Given a word with dashes, returns a camel cased version of it. - # - # classify('job-name') # => 'JobName' - def classify(dashed_word) - dashed_word.split('-').each { |part| part[0] = part[0].chr.upcase }.join - end # Tries to find a constant with the name specified in the argument string: - - # - # constantize("Module") # => Module - # constantize("Test::Unit") # => Test::Unit - # - # The name is assumed to be the one of a top-level constant, no matter - # whether it starts with "::" or not. No lexical context is taken into - # account: - # - # C = 'outside' - # module M - # C = 'inside' - # C # => 'inside' - # constantize("C") # => 'outside', same as ::C - # end - # - # NameError is raised when the constant is unknown. - def constantize(camel_cased_word) - camel_cased_word = camel_cased_word.to_s - - names = camel_cased_word.split('::') - names.shift if names.empty? || names.first.empty? - - constant = Object - names.each do |name| - args = Module.method(:const_get).arity != 1 ? [false] : [] - - if constant.const_defined?(name, *args) - constant = constant.const_get(name) - else - constant = constant.const_missing(name) - end - end - constant - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/process.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/process.rb deleted file mode 100644 index ee3de94..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/process.rb +++ /dev/null @@ -1,80 +0,0 @@ -require "foreman" -require "shellwords" - -class Foreman::Process - - attr_reader :command - attr_reader :env - - # Create a Process - # - # @param [String] command The command to run - # @param [Hash] options - # - # @option options [String] :cwd (./) Change to this working directory before executing the process - # @option options [Hash] :env ({}) Environment variables to set for this process - # - def initialize(command, options={}) - @command = command - @options = options.dup - - @options[:env] ||= {} - end - - # Get environment-expanded command for a +Process+ - # - # @param [Hash] custom_env ({}) Environment variables to merge with defaults - # - # @return [String] The expanded command - # - def expanded_command(custom_env={}) - env = @options[:env].merge(custom_env) - expanded_command = command.dup - env.each do |key, val| - expanded_command.gsub!("$#{key}", val) - end - expanded_command - end - - # Run a +Process+ - # - # @param [Hash] options - # - # @option options :env ({}) Environment variables to set for this execution - # @option options :output ($stdout) The output stream - # - # @returns [Fixnum] pid The +pid+ of the process - # - def run(options={}) - env = @options[:env].merge(options[:env] || {}) - output = options[:output] || $stdout - runner = "#{Foreman.runner}".shellescape - - Dir.chdir(cwd) do - Process.spawn env, expanded_command(env), :out => output, :err => output - end - end - - # Exec a +Process+ - # - # @param [Hash] options - # - # @option options :env ({}) Environment variables to set for this execution - # - # @return Does not return - def exec(options={}) - env = @options[:env].merge(options[:env] || {}) - env.each { |k, v| ENV[k] = v } - Dir.chdir(cwd) - Kernel.exec expanded_command(env) - end - - # Returns the working directory for this +Process+ - # - # @returns [String] - # - def cwd - File.expand_path(@options[:cwd] || ".") - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/procfile.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/procfile.rb deleted file mode 100644 index fbbe995..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/procfile.rb +++ /dev/null @@ -1,92 +0,0 @@ -require "foreman" - -# Reads and writes Procfiles -# -# A valid Procfile entry is captured by this regex: -# -# /^([A-Za-z0-9_]+):\s*(.+)$/ -# -# All other lines are ignored. -# -class Foreman::Procfile - - # Initialize a Procfile - # - # @param [String] filename (nil) An optional filename to read from - # - def initialize(filename=nil) - @entries = [] - load(filename) if filename - end - - # Yield each +Procfile+ entry in order - # - def entries(&blk) - @entries.each do |(name, command)| - yield name, command - end - end - - # Retrieve a +Procfile+ command by name - # - # @param [String] name The name of the Procfile entry to retrieve - # - def [](name) - @entries.detect { |n,c| name == n }.last - end - - # Create a +Procfile+ entry - # - # @param [String] name The name of the +Procfile+ entry to create - # @param [String] command The command of the +Procfile+ entry to create - # - def []=(name, command) - delete name - @entries << [name, command] - end - - # Remove a +Procfile+ entry - # - # @param [String] name The name of the +Procfile+ entry to remove - # - def delete(name) - @entries.reject! { |n,c| name == n } - end - - # Load a Procfile from a file - # - # @param [String] filename The filename of the +Procfile+ to load - # - def load(filename) - @entries.replace parse(filename) - end - - # Save a Procfile to a file - # - # @param [String] filename Save the +Procfile+ to this file - # - def save(filename) - File.open(filename, 'w') do |file| - file.puts self.to_s - end - end - - # Get the +Procfile+ as a +String+ - # - def to_s - @entries.map do |name, command| - [ name, command ].join(": ") - end.join("\n") - end - -private - - def parse(filename) - File.read(filename).gsub("\r\n","\n").split("\n").map do |line| - if line =~ /^([A-Za-z0-9_-]+):\s*(.+)$/ - [$1, $2] - end - end.compact - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/version.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/version.rb deleted file mode 100644 index f9effe3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/lib/foreman/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Foreman - - VERSION = "0.74.0" - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/man/foreman.1 b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/man/foreman.1 deleted file mode 100644 index c542f53..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/man/foreman.1 +++ /dev/null @@ -1,274 +0,0 @@ -.\" generated with Ronn/v0.7.3 -.\" http://github.com/rtomayko/ronn/tree/0.7.3 -. -.TH "FOREMAN" "1" "June 2014" "Foreman 0.74.0" "Foreman Manual" -. -.SH "NAME" -\fBforeman\fR \- manage Procfile\-based applications -. -.SH "SYNOPSIS" -\fBforeman start [process]\fR -. -.br -\fBforeman run \fR -. -.br -\fBforeman export [location]\fR -. -.SH "DESCRIPTION" -Foreman is a manager for Procfile\-based applications\. Its aim is to abstract away the details of the Procfile format, and allow you to either run your application directly or export it to some other process management format\. -. -.SH "RUNNING" -\fBforeman start\fR is used to run your application directly from the command line\. -. -.P -If no additional parameters are passed, foreman will run one instance of each type of process defined in your Procfile\. -. -.P -If a parameter is passed, foreman will run one instance of the specified application type\. -. -.P -The following options control how the application is run: -. -.TP -\fB\-c\fR, \fB\-\-concurrency\fR -Specify the number of each process type to run\. The value passed in should be in the format \fBprocess=num,process=num\fR -. -.TP -\fB\-e\fR, \fB\-\-env\fR -Specify one or more \.env files to load -. -.TP -\fB\-f\fR, \fB\-\-procfile\fR -Specify an alternate Procfile to load, implies \fB\-d\fR at the Procfile root\. -. -.TP -\fB\-p\fR, \fB\-\-port\fR -Specify which port to use as the base for this application\. Should be a multiple of 1000\. -. -.P -\fBforeman run\fR is used to run one\-off commands using the same environment as your defined processes\. -. -.SH "EXPORTING" -\fBforeman export\fR is used to export your application to another process management format\. -. -.P -An location to export can be passed as an argument\. This argument may be either required or optional depending on the export format\. -. -.P -The following options control how the application is run: -. -.TP -\fB\-a\fR, \fB\-\-app\fR -Use this name rather than the application\'s root directory name as the name of the application when exporting\. -. -.TP -\fB\-c\fR, \fB\-\-concurrency\fR -Specify the number of each process type to run\. The value passed in should be in the format \fBprocess=num,process=num\fR -. -.TP -\fB\-l\fR, \fB\-\-log\fR -Specify the directory to place process logs in\. -. -.TP -\fB\-p\fR, \fB\-\-port\fR -Specify which port to use as the base for this application\. Should be a multiple of 1000\. -. -.TP -\fB\-t\fR, \fB\-\-template\fR -Specify an alternate template to use for creating export files\. See \fIhttps://github\.com/ddollar/foreman/tree/master/data/export\fR for examples\. -. -.TP -\fB\-u\fR, \fB\-\-user\fR -Specify the user the application should be run as\. Defaults to the app name -. -.SH "GLOBAL OPTIONS" -These options control all modes of foreman\'s operation\. -. -.TP -\fB\-d\fR, \fB\-\-root\fR -Specify an alternate application root\. This defaults to the directory containing the Procfile\. -. -.TP -\fB\-e\fR, \fB\-\-env\fR -Specify an alternate environment file\. You can specify more than one file by using: \fB\-\-env file1,file2\fR\. -. -.TP -\fB\-f\fR, \fB\-\-procfile\fR -Specify an alternate location for the application\'s Procfile\. This file\'s containing directory will be assumed to be the root directory of the application\. -. -.SH "EXPORT FORMATS" -foreman currently supports the following output formats: -. -.IP "\(bu" 4 -bluepill -. -.IP "\(bu" 4 -inittab -. -.IP "\(bu" 4 -launchd -. -.IP "\(bu" 4 -runit -. -.IP "\(bu" 4 -supervisord -. -.IP "\(bu" 4 -systemd -. -.IP "\(bu" 4 -upstart -. -.IP "" 0 -. -.SH "INITTAB EXPORT" -Will export a chunk of inittab\-compatible configuration: -. -.IP "" 4 -. -.nf - -# \-\-\-\-\- foreman example processes \-\-\-\-\- -EX01:4:respawn:/bin/su \- example \-c \'PORT=5000 bundle exec thin start >> /var/log/web\-1\.log 2>&1\' -EX02:4:respawn:/bin/su \- example \-c \'PORT=5100 bundle exec rake jobs:work >> /var/log/job\-1\.log 2>&1\' -# \-\-\-\-\- end foreman example processes \-\-\-\-\- -. -.fi -. -.IP "" 0 -. -.SH "SYSTEMD EXPORT" -Will create a series of systemd scripts in the location you specify\. Scripts will be structured to make the following commands valid: -. -.P -\fBsystemctl start appname\.target\fR -. -.P -\fBsystemctl stop appname\-processname\.target\fR -. -.P -\fBsystemctl restart appname\-processname\-3\.service\fR -. -.SH "UPSTART EXPORT" -Will create a series of upstart scripts in the location you specify\. Scripts will be structured to make the following commands valid: -. -.P -\fBstart appname\fR -. -.P -\fBstop appname\-processname\fR -. -.P -\fBrestart appname\-processname\-3\fR -. -.SH "PROCFILE" -A Procfile should contain both a name for the process and the command used to run it\. -. -.IP "" 4 -. -.nf - -web: bundle exec thin start -job: bundle exec rake jobs:work -. -.fi -. -.IP "" 0 -. -.P -A process name may contain letters, numbers and the underscore character\. You can validate your Procfile format using the \fBcheck\fR command: -. -.IP "" 4 -. -.nf - -$ foreman check -. -.fi -. -.IP "" 0 -. -.SH "ENVIRONMENT" -If a \fB\.env\fR file exists in the current directory, the default environment will be read from it\. This file should contain key/value pairs, separated by \fB=\fR, with one key/value pair per line\. -. -.IP "" 4 -. -.nf - -FOO=bar -BAZ=qux -. -.fi -. -.IP "" 0 -. -.SH "DEFAULT OPTIONS" -If a \fB\.foreman\fR file exists in the current directory, default options will be read from it\. This file should be in YAML format with the long option name as keys\. Example: -. -.IP "" 4 -. -.nf - -concurrency: alpha=0,bravo=1 -port: 15000 -. -.fi -. -.IP "" 0 -. -.SH "EXAMPLES" -Start one instance of each process type, interleave the output on stdout: -. -.IP "" 4 -. -.nf - -$ foreman start -. -.fi -. -.IP "" 0 -. -.P -Export the application in upstart format: -. -.IP "" 4 -. -.nf - -$ foreman export upstart /etc/init -. -.fi -. -.IP "" 0 -. -.P -Run one process type from the application defined in a specific Procfile: -. -.IP "" 4 -. -.nf - -$ foreman start alpha \-f ~/myapp/Procfile -. -.fi -. -.IP "" 0 -. -.P -Start all processes except the one named worker: -. -.IP "" 4 -. -.nf - -$ foreman start \-c all=1,worker=0 -. -.fi -. -.IP "" 0 -. -.SH "COPYRIGHT" -Foreman is Copyright (C) 2010 David Dollar \fIhttp://daviddollar\.org\fR diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/cli_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/cli_spec.rb deleted file mode 100644 index d62c13c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/cli_spec.rb +++ /dev/null @@ -1,103 +0,0 @@ -require "spec_helper" -require "foreman/cli" - -describe "Foreman::CLI", :fakefs do - subject { Foreman::CLI.new } - - describe ".foreman" do - before { File.open(".foreman", "w") { |f| f.puts "formation: alpha=2" } } - - it "provides default options" do - expect(subject.send(:options)["formation"]).to eq("alpha=2") - end - - it "is overridden by options at the cli" do - subject = Foreman::CLI.new([], :formation => "alpha=3") - expect(subject.send(:options)["formation"]).to eq("alpha=3") - end - end - - describe "start" do - describe "when a Procfile doesnt exist", :fakefs do - it "displays an error" do - mock_error(subject, "Procfile does not exist.") do - dont_allow.instance_of(Foreman::Engine).start - subject.start - end - end - end - - describe "with a valid Procfile" do - it "can run a single command" do - without_fakefs do - output = foreman("start env -f #{resource_path("Procfile")}") - expect(output).to match(/env.1/) - expect(output).not_to match(/test.1/) - end - end - - it "can run all commands" do - without_fakefs do - output = foreman("start -f #{resource_path("Procfile")} -e #{resource_path(".env")}") - expect(output).to match(/echo.1 \| echoing/) - expect(output).to match(/env.1 \| bar/) - expect(output).to match(/test.1 \| testing/) - end - end - - it "sets PS variable with the process name" do - without_fakefs do - output = foreman("start -f #{resource_path("Procfile")}") - expect(output).to match(/ps.1 \| PS env var is ps.1/) - end - end - end - end - - describe "check" do - it "with a valid Procfile displays the jobs" do - write_procfile - expect(foreman("check")).to eq("valid procfile detected (alpha, bravo, foo_bar, foo-bar)\n") - end - - it "with a blank Procfile displays an error" do - FileUtils.touch "Procfile" - expect(foreman("check")).to eq("ERROR: no processes defined\n") - end - - it "without a Procfile displays an error" do - FileUtils.rm_f "Procfile" - expect(foreman("check")).to eq("ERROR: Procfile does not exist.\n") - end - end - - describe "run" do - it "can run a command" do - expect(forked_foreman("run echo 1")).to eq("1\n") - end - - it "includes the environment" do - expect(forked_foreman("run #{resource_path("bin/env FOO")} -e #{resource_path(".env")}")).to eq("bar\n") - end - - it "can run a command from the Procfile" do - expect(forked_foreman("run -f #{resource_path("Procfile")} test")).to eq("testing\n") - end - - it "exits with the same exit code as the command" do - expect(fork_and_get_exitstatus("run echo 1")).to eq(0) - expect(fork_and_get_exitstatus("run date 'invalid_date'")).to eq(1) - end - end - - describe "version" do - it "displays gem version" do - expect(foreman("version").chomp).to eq(Foreman::VERSION) - end - - it "displays gem version on shortcut command" do - expect(foreman("-v").chomp).to eq(Foreman::VERSION) - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/engine_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/engine_spec.rb deleted file mode 100644 index 6f534c7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/engine_spec.rb +++ /dev/null @@ -1,112 +0,0 @@ -require "spec_helper" -require "foreman/engine" - -class Foreman::Engine::Tester < Foreman::Engine - attr_reader :buffer - - def startup - @buffer = "" - end - - def output(name, data) - @buffer += "#{name}: #{data}" - end - - def shutdown - end -end - -describe "Foreman::Engine", :fakefs do - subject do - write_procfile "Procfile" - Foreman::Engine::Tester.new.load_procfile("Procfile") - end - - describe "initialize" do - describe "with a Procfile" do - before { write_procfile } - - it "reads the processes" do - expect(subject.process("alpha").command).to eq("./alpha") - expect(subject.process("bravo").command).to eq("./bravo") - end - end - end - - describe "start" do - it "forks the processes" do - mock(subject.process("alpha")).run(anything) - mock(subject.process("bravo")).run(anything) - mock(subject).watch_for_output - mock(subject).watch_for_termination - subject.start - end - - it "handles concurrency" do - subject.options[:formation] = "alpha=2" - mock(subject.process("alpha")).run(anything).twice - mock(subject.process("bravo")).run(anything).never - mock(subject).watch_for_output - mock(subject).watch_for_termination - subject.start - end - end - - describe "directories" do - it "has the directory default relative to the Procfile" do - write_procfile "/some/app/Procfile" - engine = Foreman::Engine.new.load_procfile("/some/app/Procfile") - expect(engine.root).to eq("/some/app") - end - end - - describe "environment" do - it "should read env files" do - File.open("/tmp/env", "w") { |f| f.puts("FOO=baz") } - subject.load_env("/tmp/env") - expect(subject.env["FOO"]).to eq("baz") - end - - it "should read more than one if specified" do - File.open("/tmp/env1", "w") { |f| f.puts("FOO=bar") } - File.open("/tmp/env2", "w") { |f| f.puts("BAZ=qux") } - subject.load_env "/tmp/env1" - subject.load_env "/tmp/env2" - expect(subject.env["FOO"]).to eq("bar") - expect(subject.env["BAZ"]).to eq("qux") - end - - it "should handle quoted values" do - File.open("/tmp/env", "w") do |f| - f.puts 'FOO=bar' - f.puts 'BAZ="qux"' - f.puts "FRED='barney'" - f.puts 'OTHER="escaped\"quote"' - end - subject.load_env "/tmp/env" - expect(subject.env["FOO"]).to eq("bar") - expect(subject.env["BAZ"]).to eq("qux") - expect(subject.env["FRED"]).to eq("barney") - expect(subject.env["OTHER"]).to eq('escaped"quote') - end - - it "should handle multiline strings" do - File.open("/tmp/env", "w") do |f| - f.puts 'FOO="bar\nbaz"' - end - subject.load_env "/tmp/env" - expect(subject.env["FOO"]).to eq("bar\nbaz") - end - - it "should fail if specified and doesnt exist" do - expect { subject.load_env "/tmp/env" }.to raise_error(Errno::ENOENT) - end - - it "should set port from .env if specified" do - File.open("/tmp/env", "w") { |f| f.puts("PORT=9000") } - subject.load_env "/tmp/env" - expect(subject.send(:base_port)).to eq(9000) - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/base_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/base_spec.rb deleted file mode 100644 index 2a465d0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/base_spec.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export" - -describe "Foreman::Export::Base", :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:location) { "/tmp/init" } - let(:engine) { Foreman::Engine.new().load_procfile(procfile) } - let(:subject) { Foreman::Export::Base.new(location, engine) } - - it "has a say method for displaying info" do - mock(subject).puts("[foreman export] foo") - subject.send(:say, "foo") - end - - it "raises errors as a Foreman::Export::Exception" do - expect { subject.send(:error, "foo") }.to raise_error(Foreman::Export::Exception, "foo") - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/bluepill_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/bluepill_spec.rb deleted file mode 100644 index f1c15e9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/bluepill_spec.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/bluepill" -require "tmpdir" - -describe Foreman::Export::Bluepill, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:bluepill) { Foreman::Export::Bluepill.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("bluepill") } - before(:each) { stub(bluepill).say } - - it "exports to the filesystem" do - bluepill.export - expect(normalize_space(File.read("/tmp/init/app.pill"))).to eq(normalize_space(example_export_file("bluepill/app.pill"))) - end - - it "cleans up if exporting into an existing dir" do - mock(FileUtils).rm("/tmp/init/app.pill") - - bluepill.export - bluepill.export - end - - context "with a process formation" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - bluepill.export - expect(normalize_space(File.read("/tmp/init/app.pill"))).to eq(normalize_space(example_export_file("bluepill/app-concurrency.pill"))) - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/daemon_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/daemon_spec.rb deleted file mode 100644 index c163c96..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/daemon_spec.rb +++ /dev/null @@ -1,97 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/daemon" -require "tmpdir" - -describe Foreman::Export::Daemon, :fakefs do - let(:procfile) { write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:daemon) { Foreman::Export::Daemon.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("daemon") } - before(:each) { stub(daemon).say } - - it "exports to the filesystem" do - daemon.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("daemon/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("daemon/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("daemon/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-bravo.conf")).to eq(example_export_file("daemon/app-bravo.conf")) - expect(File.read("/tmp/init/app-bravo-1.conf")).to eq(example_export_file("daemon/app-bravo-1.conf")) - end - - it "cleans up if exporting into an existing dir" do - mock(FileUtils).rm("/tmp/init/app.conf") - mock(FileUtils).rm("/tmp/init/app-alpha.conf") - mock(FileUtils).rm("/tmp/init/app-alpha-1.conf") - mock(FileUtils).rm("/tmp/init/app-bravo.conf") - mock(FileUtils).rm("/tmp/init/app-bravo-1.conf") - mock(FileUtils).rm("/tmp/init/app-foo-bar.conf") - mock(FileUtils).rm("/tmp/init/app-foo-bar-1.conf") - mock(FileUtils).rm("/tmp/init/app-foo_bar.conf") - mock(FileUtils).rm("/tmp/init/app-foo_bar-1.conf") - - daemon.export - daemon.export - end - - it "does not delete exported files for similarly named applications" do - FileUtils.mkdir_p "/tmp/init" - - ["app2", "app2-alpha", "app2-alpha-1"].each do |name| - path = "/tmp/init/#{name}.conf" - FileUtils.touch(path) - dont_allow(FileUtils).rm(path) - end - - daemon.export - end - - context "with a formation" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - daemon.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("daemon/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("daemon/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("daemon/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-alpha-2.conf")).to eq(example_export_file("daemon/app-alpha-2.conf")) - expect(File.exists?("/tmp/init/app-bravo-1.conf")).to eq(false) - end - end - - context "with alternate templates" do - let(:template) { "/tmp/alternate" } - let(:options) { { :app => "app", :template => template } } - - before do - FileUtils.mkdir_p template - File.open("#{template}/master.conf.erb", "w") { |f| f.puts "alternate_template" } - end - - it "can export with alternate template files" do - daemon.export - expect(File.read("/tmp/init/app.conf")).to eq("alternate_template\n") - end - end - - context "with alternate templates from home dir" do - - before do - FileUtils.mkdir_p File.expand_path("~/.foreman/templates/daemon") - File.open(File.expand_path("~/.foreman/templates/daemon/master.conf.erb"), "w") do |file| - file.puts "default_alternate_template" - end - end - - it "can export with alternate template files" do - daemon.export - expect(File.read("/tmp/init/app.conf")).to eq("default_alternate_template\n") - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/inittab_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/inittab_spec.rb deleted file mode 100644 index 98382d1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/inittab_spec.rb +++ /dev/null @@ -1,40 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/inittab" -require "tmpdir" - -describe Foreman::Export::Inittab, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:location) { "/tmp/inittab" } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:inittab) { Foreman::Export::Inittab.new(location, engine, options) } - - before(:each) { load_export_templates_into_fakefs("inittab") } - before(:each) { stub(inittab).say } - - it "exports to the filesystem" do - inittab.export - expect(File.read("/tmp/inittab")).to eq(example_export_file("inittab/inittab.default")) - end - - context "to stdout" do - let(:location) { "-" } - - it "exports to stdout" do - mock(inittab).puts example_export_file("inittab/inittab.default") - inittab.export - end - end - - context "with concurrency" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - inittab.export - expect(File.read("/tmp/inittab")).to eq(example_export_file("inittab/inittab.concurrency")) - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/launchd_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/launchd_spec.rb deleted file mode 100644 index f42d025..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/launchd_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/launchd" -require "tmpdir" - -describe Foreman::Export::Launchd, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:options) { Hash.new } - let(:engine) { Foreman::Engine.new().load_procfile(procfile) } - let(:launchd) { Foreman::Export::Launchd.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("launchd") } - before(:each) { stub(launchd).say } - - it "exports to the filesystem" do - launchd.export - expect(File.read("/tmp/init/app-alpha-1.plist")).to eq(example_export_file("launchd/launchd-a.default")) - expect(File.read("/tmp/init/app-bravo-1.plist")).to eq(example_export_file("launchd/launchd-b.default")) - end - - context "with multiple command arguments" do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile", "charlie") } - - it "splits each command argument" do - launchd.export - expect(File.read("/tmp/init/app-alpha-1.plist")).to eq(example_export_file("launchd/launchd-c.default")) - end - - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/runit_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/runit_spec.rb deleted file mode 100644 index 586d4fc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/runit_spec.rb +++ /dev/null @@ -1,36 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/runit" -require "tmpdir" - -describe Foreman::Export::Runit, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile", 'bar=baz') } - let(:engine) { Foreman::Engine.new(:formation => "alpha=2,bravo=1").load_procfile(procfile) } - let(:options) { Hash.new } - let(:runit) { Foreman::Export::Runit.new('/tmp/init', engine, options) } - - before(:each) { load_export_templates_into_fakefs("runit") } - before(:each) { stub(runit).say } - before(:each) { stub(FakeFS::FileUtils).chmod } - - it "exports to the filesystem" do - engine.env["BAR"] = "baz" - runit.export - - expect(File.read("/tmp/init/app-alpha-1/run")).to eq(example_export_file('runit/app-alpha-1/run')) - expect(File.read("/tmp/init/app-alpha-1/log/run")).to eq(example_export_file('runit/app-alpha-1/log/run')) - expect(File.read("/tmp/init/app-alpha-1/env/PORT")).to eq("5000\n") - expect(File.read("/tmp/init/app-alpha-1/env/BAR")).to eq("baz\n") - expect(File.read("/tmp/init/app-alpha-2/run")).to eq(example_export_file('runit/app-alpha-2/run')) - expect(File.read("/tmp/init/app-alpha-2/log/run")).to eq(example_export_file('runit/app-alpha-2/log/run')) - expect(File.read("/tmp/init/app-alpha-2/env/PORT")).to eq("5001\n") - expect(File.read("/tmp/init/app-alpha-2/env/BAR")).to eq("baz\n") - expect(File.read("/tmp/init/app-bravo-1/run")).to eq(example_export_file('runit/app-bravo-1/run')) - expect(File.read("/tmp/init/app-bravo-1/log/run")).to eq(example_export_file('runit/app-bravo-1/log/run')) - expect(File.read("/tmp/init/app-bravo-1/env/PORT")).to eq("5100\n") - end - - it "creates a full path to the export directory" do - expect { runit.export }.to_not raise_error - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/supervisord_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/supervisord_spec.rb deleted file mode 100644 index 10c34a6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/supervisord_spec.rb +++ /dev/null @@ -1,36 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/supervisord" -require "tmpdir" - -describe Foreman::Export::Supervisord, :fakefs do - let(:procfile) { FileUtils.mkdir_p("/tmp/app"); write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:supervisord) { Foreman::Export::Supervisord.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("supervisord") } - before(:each) { stub(supervisord).say } - - it "exports to the filesystem" do - supervisord.export - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("supervisord/app-alpha-1.conf")) - end - - it "cleans up if exporting into an existing dir" do - mock(FileUtils).rm("/tmp/init/app.conf") - supervisord.export - supervisord.export - end - - context "with concurrency" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - supervisord.export - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("supervisord/app-alpha-2.conf")) - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/systemd_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/systemd_spec.rb deleted file mode 100644 index fd47b61..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/systemd_spec.rb +++ /dev/null @@ -1,91 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/systemd" -require "tmpdir" - -describe Foreman::Export::Systemd, :fakefs do - let(:procfile) { write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:systemd) { Foreman::Export::Systemd.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("systemd") } - before(:each) { stub(systemd).say } - - it "exports to the filesystem" do - systemd.export - - expect(File.read("/tmp/init/app.target")).to eq(example_export_file("systemd/standard/app.target")) - expect(File.read("/tmp/init/app-alpha.target")).to eq(example_export_file("systemd/standard/app-alpha.target")) - expect(File.read("/tmp/init/app-alpha-1.service")).to eq(example_export_file("systemd/standard/app-alpha-1.service")) - expect(File.read("/tmp/init/app-bravo.target")).to eq(example_export_file("systemd/standard/app-bravo.target")) - expect(File.read("/tmp/init/app-bravo-1.service")).to eq(example_export_file("systemd/standard/app-bravo-1.service")) - end - - it "cleans up if exporting into an existing dir" do - mock(FileUtils).rm("/tmp/init/app.target") - mock(FileUtils).rm("/tmp/init/app-alpha.target") - mock(FileUtils).rm("/tmp/init/app-alpha-1.service") - mock(FileUtils).rm("/tmp/init/app-bravo.target") - mock(FileUtils).rm("/tmp/init/app-bravo-1.service") - mock(FileUtils).rm("/tmp/init/app-foo-bar.target") - mock(FileUtils).rm("/tmp/init/app-foo-bar-1.service") - mock(FileUtils).rm("/tmp/init/app-foo_bar.target") - mock(FileUtils).rm("/tmp/init/app-foo_bar-1.service") - - systemd.export - systemd.export - end - - it "includes environment variables" do - engine.env['KEY'] = 'some "value"' - systemd.export - expect(File.read("/tmp/init/app-alpha-1.service")).to match(/KEY=some "value"$/) - end - - context "with a formation" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - systemd.export - - expect(File.read("/tmp/init/app.target")).to eq(example_export_file("systemd/concurrency/app.target")) - expect(File.read("/tmp/init/app-alpha.target")).to eq(example_export_file("systemd/concurrency/app-alpha.target")) - expect(File.read("/tmp/init/app-alpha-1.service")).to eq(example_export_file("systemd/concurrency/app-alpha-1.service")) - expect(File.read("/tmp/init/app-alpha-2.service")).to eq(example_export_file("systemd/concurrency/app-alpha-2.service")) - expect(File.exists?("/tmp/init/app-bravo-1.service")).to eq(false) - end - end - - context "with alternate templates" do - let(:template) { "/tmp/alternate" } - let(:options) { { :app => "app", :template => template } } - - before do - FileUtils.mkdir_p template - File.open("#{template}/master.target.erb", "w") { |f| f.puts "alternate_template" } - end - - it "can export with alternate template files" do - systemd.export - expect(File.read("/tmp/init/app.target")).to eq("alternate_template\n") - end - end - - context "with alternate templates from home dir" do - - before do - FileUtils.mkdir_p File.expand_path("~/.foreman/templates/systemd") - File.open(File.expand_path("~/.foreman/templates/systemd/master.target.erb"), "w") do |file| - file.puts "default_alternate_template" - end - end - - it "can export with alternate template files" do - systemd.export - expect(File.read("/tmp/init/app.target")).to eq("default_alternate_template\n") - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/upstart_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/upstart_spec.rb deleted file mode 100644 index 4820436..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export/upstart_spec.rb +++ /dev/null @@ -1,104 +0,0 @@ -require "spec_helper" -require "foreman/engine" -require "foreman/export/upstart" -require "tmpdir" - -describe Foreman::Export::Upstart, :fakefs do - let(:procfile) { write_procfile("/tmp/app/Procfile") } - let(:formation) { nil } - let(:engine) { Foreman::Engine.new(:formation => formation).load_procfile(procfile) } - let(:options) { Hash.new } - let(:upstart) { Foreman::Export::Upstart.new("/tmp/init", engine, options) } - - before(:each) { load_export_templates_into_fakefs("upstart") } - before(:each) { stub(upstart).say } - - it "exports to the filesystem" do - upstart.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("upstart/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("upstart/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("upstart/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-bravo.conf")).to eq(example_export_file("upstart/app-bravo.conf")) - expect(File.read("/tmp/init/app-bravo-1.conf")).to eq(example_export_file("upstart/app-bravo-1.conf")) - end - - it "cleans up if exporting into an existing dir" do - mock(FileUtils).rm("/tmp/init/app.conf") - mock(FileUtils).rm("/tmp/init/app-alpha.conf") - mock(FileUtils).rm("/tmp/init/app-alpha-1.conf") - mock(FileUtils).rm("/tmp/init/app-bravo.conf") - mock(FileUtils).rm("/tmp/init/app-bravo-1.conf") - mock(FileUtils).rm("/tmp/init/app-foo-bar.conf") - mock(FileUtils).rm("/tmp/init/app-foo-bar-1.conf") - mock(FileUtils).rm("/tmp/init/app-foo_bar.conf") - mock(FileUtils).rm("/tmp/init/app-foo_bar-1.conf") - - upstart.export - upstart.export - end - - it "does not delete exported files for similarly named applications" do - FileUtils.mkdir_p "/tmp/init" - - ["app2", "app2-alpha", "app2-alpha-1"].each do |name| - path = "/tmp/init/#{name}.conf" - FileUtils.touch(path) - dont_allow(FileUtils).rm(path) - end - - upstart.export - end - - it "quotes and escapes environment variables" do - engine.env['KEY'] = 'd"\|d' - upstart.export - expect("foobarfoo").to include "bar" - expect(File.read("/tmp/init/app-alpha-1.conf")).to match(/KEY='d"\\\|d'/) - end - - context "with a formation" do - let(:formation) { "alpha=2" } - - it "exports to the filesystem with concurrency" do - upstart.export - - expect(File.read("/tmp/init/app.conf")).to eq(example_export_file("upstart/app.conf")) - expect(File.read("/tmp/init/app-alpha.conf")).to eq(example_export_file("upstart/app-alpha.conf")) - expect(File.read("/tmp/init/app-alpha-1.conf")).to eq(example_export_file("upstart/app-alpha-1.conf")) - expect(File.read("/tmp/init/app-alpha-2.conf")).to eq(example_export_file("upstart/app-alpha-2.conf")) - expect(File.exists?("/tmp/init/app-bravo-1.conf")).to eq(false) - end - end - - context "with alternate templates" do - let(:template) { "/tmp/alternate" } - let(:options) { { :app => "app", :template => template } } - - before do - FileUtils.mkdir_p template - File.open("#{template}/master.conf.erb", "w") { |f| f.puts "alternate_template" } - end - - it "can export with alternate template files" do - upstart.export - expect(File.read("/tmp/init/app.conf")).to eq("alternate_template\n") - end - end - - context "with alternate templates from home dir" do - - before do - FileUtils.mkdir_p File.expand_path("~/.foreman/templates/upstart") - File.open(File.expand_path("~/.foreman/templates/upstart/master.conf.erb"), "w") do |file| - file.puts "default_alternate_template" - end - end - - it "can export with alternate template files" do - upstart.export - expect(File.read("/tmp/init/app.conf")).to eq("default_alternate_template\n") - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export_spec.rb deleted file mode 100644 index 2008dab..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/export_spec.rb +++ /dev/null @@ -1,24 +0,0 @@ -require "spec_helper" -require "foreman/export" - -describe "Foreman::Export" do - subject { Foreman::Export } - - describe "with a formatter that doesn't declare the appropriate class" do - it "prints an error" do - mock(subject).require("foreman/export/invalidformatter") - mock_export_error("Unknown export format: invalidformatter (no class Foreman::Export::Invalidformatter).") do - subject.formatter("invalidformatter") - end - end - end - - describe "with an invalid formatter" do - - it "prints an error" do - mock_export_error("Unknown export format: invalidformatter (unable to load file 'foreman/export/invalidformatter').") do - subject.formatter("invalidformatter") - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/helpers_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/helpers_spec.rb deleted file mode 100644 index 72d64f2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/helpers_spec.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "spec_helper" -require "foreman/helpers" - -describe "Foreman::Helpers" do - before do - module Foo - class Bar; end - end - end - - after do - Object.send(:remove_const, :Foo) - end - - subject { o = Object.new; o.extend(Foreman::Helpers); o } - - it "should classify words" do - expect(subject.classify("foo")).to eq("Foo") - expect(subject.classify("foo-bar")).to eq("FooBar") - end - - it "should constantize words" do - expect(subject.constantize("Object")).to eq(Object) - expect(subject.constantize("Foo::Bar")).to eq(Foo::Bar) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/process_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/process_spec.rb deleted file mode 100644 index 1837506..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/process_spec.rb +++ /dev/null @@ -1,71 +0,0 @@ -require 'spec_helper' -require 'foreman/process' -require 'ostruct' -require 'timeout' -require 'tmpdir' - -describe Foreman::Process do - - def run(process, options={}) - rd, wr = IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY") - process.run(options.merge(:output => wr)) - rd.gets - end - - describe "#run" do - - it "runs the process" do - process = Foreman::Process.new(resource_path("bin/test")) - expect(run(process)).to eq("testing\n") - end - - it "can set environment" do - process = Foreman::Process.new(resource_path("bin/env FOO"), :env => { "FOO" => "bar" }) - expect(run(process)).to eq("bar\n") - end - - it "can set per-run environment" do - process = Foreman::Process.new(resource_path("bin/env FOO")) - expect(run(process, :env => { "FOO" => "bar "})).to eq("bar\n") - end - - it "can handle env vars in the command" do - process = Foreman::Process.new(resource_path("bin/echo $FOO"), :env => { "FOO" => "bar" }) - expect(run(process)).to eq("bar\n") - end - - it "can handle per-run env vars in the command" do - process = Foreman::Process.new(resource_path("bin/echo $FOO")) - expect(run(process, :env => { "FOO" => "bar" })).to eq("bar\n") - end - - it "should output utf8 properly" do - process = Foreman::Process.new(resource_path("bin/utf8")) - expect(run(process)).to eq(Foreman.ruby_18? ? "\xFF\x03\n" : "\xFF\x03\n".force_encoding('binary')) - end - - it "can expand env in the command" do - process = Foreman::Process.new("command $FOO $BAR", :env => { "FOO" => "bar" }) - expect(process.expanded_command).to eq("command bar $BAR") - end - - it "can expand extra env in the command" do - process = Foreman::Process.new("command $FOO $BAR", :env => { "FOO" => "bar" }) - expect(process.expanded_command("BAR" => "qux")).to eq("command bar qux") - end - - it "can execute" do - mock(Kernel).exec "bin/command" - process = Foreman::Process.new("bin/command") - process.exec - end - - it "can execute with env" do - mock(Kernel).exec "bin/command bar" - process = Foreman::Process.new("bin/command $FOO") - process.exec(:env => { "FOO" => "bar" }) - end - - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/procfile_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/procfile_spec.rb deleted file mode 100644 index 0f2f420..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman/procfile_spec.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'spec_helper' -require 'foreman/procfile' -require 'pathname' -require 'tmpdir' - -describe Foreman::Procfile, :fakefs do - subject { Foreman::Procfile.new } - - it "can load from a file" do - write_procfile - subject.load "Procfile" - expect(subject["alpha"]).to eq("./alpha") - expect(subject["bravo"]).to eq("./bravo") - end - - it "loads a passed-in Procfile" do - write_procfile - procfile = Foreman::Procfile.new("Procfile") - expect(procfile["alpha"]).to eq("./alpha") - expect(procfile["bravo"]).to eq("./bravo") - expect(procfile["foo-bar"]).to eq("./foo-bar") - expect(procfile["foo_bar"]).to eq("./foo_bar") - end - - it "can have a process appended to it" do - subject["charlie"] = "./charlie" - expect(subject["charlie"]).to eq("./charlie") - end - - it "can write to a string" do - subject["foo"] = "./foo" - subject["bar"] = "./bar" - expect(subject.to_s).to eq("foo: ./foo\nbar: ./bar") - end - - it "can write to a file" do - subject["foo"] = "./foo" - subject["bar"] = "./bar" - subject.save "/tmp/proc" - expect(File.read("/tmp/proc")).to eq("foo: ./foo\nbar: ./bar\n") - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman_spec.rb deleted file mode 100644 index 77b7615..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/foreman_spec.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "spec_helper" -require "foreman" - -describe Foreman do - - describe "VERSION" do - subject { Foreman::VERSION } - it { should be_a String } - end - - describe "runner" do - it "should exist" do - expect(File.exists?(Foreman.runner)).to eq(true) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/helper_spec.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/helper_spec.rb deleted file mode 100644 index f04ff90..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/helper_spec.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "spec_helper" - -describe "spec helpers" do - describe "#preserving_env" do - after { ENV.delete "FOO" } - - it "should remove added environment vars" do - old = ENV["FOO"] - preserving_env { ENV["FOO"] = "baz" } - expect(ENV["FOO"]).to eq(old) - end - - it "should reset modified environment vars" do - ENV["FOO"] = "bar" - preserving_env { ENV["FOO"] = "baz"} - expect(ENV["FOO"]).to eq("bar") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/Procfile b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/Procfile deleted file mode 100644 index 8c7a324..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/Procfile +++ /dev/null @@ -1,5 +0,0 @@ -echo: bin/echo echoing -env: bin/env FOO -test: bin/test -utf8: bin/utf8 -ps: bin/echo PS env var is $PS diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/echo b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/echo deleted file mode 100755 index 94704ce..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/echo +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -echo $* diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/env b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/env deleted file mode 100755 index 3287f08..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/env +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/bash -echo ${!1} diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/test b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/test deleted file mode 100755 index 1b3f303..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/test +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -echo "testing" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/utf8 b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/utf8 deleted file mode 100755 index 18e158c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/bin/utf8 +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env ruby -puts "\xff\x03" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/bluepill/app-concurrency.pill b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/bluepill/app-concurrency.pill deleted file mode 100644 index a6d88ea..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/bluepill/app-concurrency.pill +++ /dev/null @@ -1,49 +0,0 @@ -Bluepill.application("app", :foreground => false, :log_file => "/var/log/bluepill.log") do |app| - - app.uid = "app" - app.gid = "app" - - - - - app.process("alpha-1") do |process| - process.start_command = %Q{./alpha} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5000"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-alpha-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-alpha" - end - - - app.process("alpha-2") do |process| - process.start_command = %Q{./alpha} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5001"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-alpha-2.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-alpha" - end - - - - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/bluepill/app.pill b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/bluepill/app.pill deleted file mode 100644 index e5d9180..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/bluepill/app.pill +++ /dev/null @@ -1,81 +0,0 @@ -Bluepill.application("app", :foreground => false, :log_file => "/var/log/bluepill.log") do |app| - - app.uid = "app" - app.gid = "app" - - - - - app.process("alpha-1") do |process| - process.start_command = %Q{./alpha} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5000"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-alpha-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-alpha" - end - - app.process("bravo-1") do |process| - process.start_command = %Q{./bravo} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5100"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-bravo-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-bravo" - end - - app.process("foo_bar-1") do |process| - process.start_command = %Q{./foo_bar} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5200"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-foo_bar-1.log" - - process.monitor_children do |children| - children.stop_command "kill {{PID}}" - end - - process.group = "app-foo_bar" - end - - app.process("foo-bar-1") do |process| - process.start_command = %Q{./foo-bar} - - process.working_dir = "/tmp/app" - process.daemonize = true - process.environment = {"PORT"=>"5300"} - process.stop_signals = [:quit, 30.seconds, :term, 5.seconds, :kill] - process.stop_grace_time = 45.seconds - - process.stdout = process.stderr = "/var/log/app/app-foo-bar-1.log" - - process.monitor_children do |children| - - children.stop_command "kill {{PID}}" - end - - process.group = "app-foo-bar" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha-1.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha-1.conf deleted file mode 100644 index 347fc3a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha-1.conf +++ /dev/null @@ -1,7 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5000 - -exec start-stop-daemon --start --chuid app --chdir /tmp/app --make-pidfile --pidfile /var/run/app/app-alpha-1.pid --exec ./alpha >> /var/log/app/app-alpha-1.log 2>&1 diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha-2.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha-2.conf deleted file mode 100644 index f72fe0c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha-2.conf +++ /dev/null @@ -1,7 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5001 - -exec start-stop-daemon --start --chuid app --chdir /tmp/app --make-pidfile --pidfile /var/run/app/app-alpha-2.pid --exec ./alpha >> /var/log/app/app-alpha-2.log 2>&1 diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha.conf deleted file mode 100644 index 848119e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-alpha.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-bravo-1.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-bravo-1.conf deleted file mode 100644 index 44c4c1a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-bravo-1.conf +++ /dev/null @@ -1,7 +0,0 @@ -start on starting app-bravo -stop on stopping app-bravo -respawn - -env PORT=5100 - -exec start-stop-daemon --start --chuid app --chdir /tmp/app --make-pidfile --pidfile /var/run/app/app-bravo-1.pid --exec ./bravo >> /var/log/app/app-bravo-1.log 2>&1 diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-bravo.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-bravo.conf deleted file mode 100644 index 848119e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app-bravo.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app.conf deleted file mode 100644 index f213f0e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/daemon/app.conf +++ /dev/null @@ -1,14 +0,0 @@ -pre-start script - -bash << "EOF" -mkdir -p /var/log/app -chown -R app /var/log/app -mkdir -p /var/run/app -chown -R app /var/run/app -EOF - -end script - -start on runlevel [2345] - -stop on runlevel [016] diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/inittab/inittab.concurrency b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/inittab/inittab.concurrency deleted file mode 100644 index 1f78357..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/inittab/inittab.concurrency +++ /dev/null @@ -1,4 +0,0 @@ -# ----- foreman app processes ----- -AP01:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5000;./alpha >> /var/log/app/alpha-1.log 2>&1' -AP02:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5001;./alpha >> /var/log/app/alpha-2.log 2>&1' -# ----- end foreman app processes ----- diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/inittab/inittab.default b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/inittab/inittab.default deleted file mode 100644 index 59655c7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/inittab/inittab.default +++ /dev/null @@ -1,6 +0,0 @@ -# ----- foreman app processes ----- -AP01:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5000;./alpha >> /var/log/app/alpha-1.log 2>&1' -AP02:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5100;./bravo >> /var/log/app/bravo-1.log 2>&1' -AP03:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5200;./foo_bar >> /var/log/app/foo_bar-1.log 2>&1' -AP04:4:respawn:/bin/su - app -c 'cd /tmp/app;export PORT=5300;./foo-bar >> /var/log/app/foo-bar-1.log 2>&1' -# ----- end foreman app processes ----- diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-a.default b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-a.default deleted file mode 100644 index 7342302..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-a.default +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Label - app-alpha-1 - EnvironmentVariables - - PORT - 5000 - - ProgramArguments - - ./alpha - - KeepAlive - - RunAtLoad - - StandardOutPath - /var/log/app/app-alpha-1.log - StandardErrorPath - /var/log/app/app-alpha-1.log - UserName - app - WorkingDirectory - /tmp/app - - diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-b.default b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-b.default deleted file mode 100644 index 51b6363..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-b.default +++ /dev/null @@ -1,29 +0,0 @@ - - - - - Label - app-bravo-1 - EnvironmentVariables - - PORT - 5100 - - ProgramArguments - - ./bravo - - KeepAlive - - RunAtLoad - - StandardOutPath - /var/log/app/app-bravo-1.log - StandardErrorPath - /var/log/app/app-bravo-1.log - UserName - app - WorkingDirectory - /tmp/app - - diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-c.default b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-c.default deleted file mode 100644 index b157d84..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/launchd/launchd-c.default +++ /dev/null @@ -1,30 +0,0 @@ - - - - - Label - app-alpha-1 - EnvironmentVariables - - PORT - 5000 - - ProgramArguments - - ./alpha - charlie - - KeepAlive - - RunAtLoad - - StandardOutPath - /var/log/app/app-alpha-1.log - StandardErrorPath - /var/log/app/app-alpha-1.log - UserName - app - WorkingDirectory - /tmp/app - - diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-1/log/run b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-1/log/run deleted file mode 100644 index 3b06c7b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-1/log/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=/var/log/app/alpha-1 - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown app "$LOG" -exec chpst -u app svlogd "$LOG" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-1/run b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-1/run deleted file mode 100644 index 9d6ea2f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-1/run +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd /tmp/app -exec 2>&1 -exec chpst -u app -e /tmp/init/app-alpha-1/env ./alpha bar=baz diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-2/log/run b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-2/log/run deleted file mode 100644 index 5f458b4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-2/log/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=/var/log/app/alpha-2 - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown app "$LOG" -exec chpst -u app svlogd "$LOG" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-2/run b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-2/run deleted file mode 100644 index 0477f43..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-alpha-2/run +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd /tmp/app -exec 2>&1 -exec chpst -u app -e /tmp/init/app-alpha-2/env ./alpha bar=baz diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-bravo-1/log/run b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-bravo-1/log/run deleted file mode 100644 index db68436..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-bravo-1/log/run +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh -set -e - -LOG=/var/log/app/bravo-1 - -test -d "$LOG" || mkdir -p -m 2750 "$LOG" && chown app "$LOG" -exec chpst -u app svlogd "$LOG" diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-bravo-1/run b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-bravo-1/run deleted file mode 100644 index 84bbbe6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/runit/app-bravo-1/run +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -cd /tmp/app -exec 2>&1 -exec chpst -u app -e /tmp/init/app-bravo-1/env ./bravo diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/supervisord/app-alpha-1.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/supervisord/app-alpha-1.conf deleted file mode 100644 index 8accbee..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/supervisord/app-alpha-1.conf +++ /dev/null @@ -1,44 +0,0 @@ - -[program:app-alpha-1] -command=./alpha -autostart=true -autorestart=true -stopsignal=QUIT -stdout_logfile=/var/log/app/alpha-1.log -stderr_logfile=/var/log/app/alpha-1.error.log -user=app -directory=/tmp/app -environment=PORT="5000" -[program:app-bravo-1] -command=./bravo -autostart=true -autorestart=true -stopsignal=QUIT -stdout_logfile=/var/log/app/bravo-1.log -stderr_logfile=/var/log/app/bravo-1.error.log -user=app -directory=/tmp/app -environment=PORT="5100" -[program:app-foo_bar-1] -command=./foo_bar -autostart=true -autorestart=true -stopsignal=QUIT -stdout_logfile=/var/log/app/foo_bar-1.log -stderr_logfile=/var/log/app/foo_bar-1.error.log -user=app -directory=/tmp/app -environment=PORT="5200" -[program:app-foo-bar-1] -command=./foo-bar -autostart=true -autorestart=true -stopsignal=QUIT -stdout_logfile=/var/log/app/foo-bar-1.log -stderr_logfile=/var/log/app/foo-bar-1.error.log -user=app -directory=/tmp/app -environment=PORT="5300" - -[group:app] -programs=app-alpha-1,app-bravo-1,app-foo_bar-1,app-foo-bar-1 diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/supervisord/app-alpha-2.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/supervisord/app-alpha-2.conf deleted file mode 100644 index 2160314..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/supervisord/app-alpha-2.conf +++ /dev/null @@ -1,24 +0,0 @@ - -[program:app-alpha-1] -command=./alpha -autostart=true -autorestart=true -stopsignal=QUIT -stdout_logfile=/var/log/app/alpha-1.log -stderr_logfile=/var/log/app/alpha-1.error.log -user=app -directory=/tmp/app -environment=PORT="5000" -[program:app-alpha-2] -command=./alpha -autostart=true -autorestart=true -stopsignal=QUIT -stdout_logfile=/var/log/app/alpha-2.log -stderr_logfile=/var/log/app/alpha-2.error.log -user=app -directory=/tmp/app -environment=PORT="5001" - -[group:app] -programs=app-alpha-1,app-alpha-2 diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha-1.service b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha-1.service deleted file mode 100644 index 8bdcabe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha-1.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -StopWhenUnneeded=true - -[Service] -User=app -WorkingDirectory=/tmp/app -Environment=PORT=5000 -ExecStart=/bin/bash -lc './alpha' -Restart=always -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=process diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha-2.service b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha-2.service deleted file mode 100644 index 7002da2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha-2.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -StopWhenUnneeded=true - -[Service] -User=app -WorkingDirectory=/tmp/app -Environment=PORT=5001 -ExecStart=/bin/bash -lc './alpha' -Restart=always -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=process diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha.target b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha.target deleted file mode 100644 index 0132531..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app-alpha.target +++ /dev/null @@ -1,3 +0,0 @@ -[Unit] -StopWhenUnneeded=true -Wants=app-alpha-1.service app-alpha-2.service diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app.target b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app.target deleted file mode 100644 index a65fd8a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/concurrency/app.target +++ /dev/null @@ -1,6 +0,0 @@ -[Unit] -StopWhenUnneeded=true -Wants=app-alpha.target - -[Install] -WantedBy=multi-user.target diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-alpha-1.service b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-alpha-1.service deleted file mode 100644 index 8bdcabe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-alpha-1.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -StopWhenUnneeded=true - -[Service] -User=app -WorkingDirectory=/tmp/app -Environment=PORT=5000 -ExecStart=/bin/bash -lc './alpha' -Restart=always -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=process diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-alpha.target b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-alpha.target deleted file mode 100644 index 971454c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-alpha.target +++ /dev/null @@ -1,3 +0,0 @@ -[Unit] -StopWhenUnneeded=true -Wants=app-alpha-1.service diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-bravo-1.service b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-bravo-1.service deleted file mode 100644 index b45eb56..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-bravo-1.service +++ /dev/null @@ -1,14 +0,0 @@ -[Unit] -StopWhenUnneeded=true - -[Service] -User=app -WorkingDirectory=/tmp/app -Environment=PORT=5100 -ExecStart=/bin/bash -lc './bravo' -Restart=always -StandardInput=null -StandardOutput=syslog -StandardError=syslog -SyslogIdentifier=%n -KillMode=process diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-bravo.target b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-bravo.target deleted file mode 100644 index dbbc713..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app-bravo.target +++ /dev/null @@ -1,3 +0,0 @@ -[Unit] -StopWhenUnneeded=true -Wants=app-bravo-1.service diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app.target b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app.target deleted file mode 100644 index 0af236e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/systemd/standard/app.target +++ /dev/null @@ -1,6 +0,0 @@ -[Unit] -StopWhenUnneeded=true -Wants=app-alpha.target app-bravo.target app-foo_bar.target app-foo-bar.target - -[Install] -WantedBy=multi-user.target diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha-1.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha-1.conf deleted file mode 100644 index c39f921..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha-1.conf +++ /dev/null @@ -1,11 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5000 - -setuid app - -chdir /tmp/app - -exec ./alpha diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha-2.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha-2.conf deleted file mode 100644 index 9a81529..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha-2.conf +++ /dev/null @@ -1,11 +0,0 @@ -start on starting app-alpha -stop on stopping app-alpha -respawn - -env PORT=5001 - -setuid app - -chdir /tmp/app - -exec ./alpha diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha.conf deleted file mode 100644 index 848119e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-alpha.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-bravo-1.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-bravo-1.conf deleted file mode 100644 index 4062040..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-bravo-1.conf +++ /dev/null @@ -1,11 +0,0 @@ -start on starting app-bravo -stop on stopping app-bravo -respawn - -env PORT=5100 - -setuid app - -chdir /tmp/app - -exec ./bravo diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-bravo.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-bravo.conf deleted file mode 100644 index 848119e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app-bravo.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on starting app -stop on stopping app diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app.conf b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app.conf deleted file mode 100644 index 7bf1666..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/resources/export/upstart/app.conf +++ /dev/null @@ -1,2 +0,0 @@ -start on runlevel [2345] -stop on runlevel [!2345] diff --git a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/spec_helper.rb b/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/spec_helper.rb deleted file mode 100644 index 3c510ed..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/foreman-0.74.0/spec/spec_helper.rb +++ /dev/null @@ -1,166 +0,0 @@ -require "codeclimate-test-reporter" -CodeClimate::TestReporter.start - -require "simplecov" -SimpleCov.start do - add_filter "/spec/" -end - -require "rspec" -require "timecop" -require "fakefs/safe" -require "fakefs/spec_helpers" - -$:.unshift File.expand_path("../../lib", __FILE__) - -def mock_export_error(message) - expect { yield }.to raise_error(Foreman::Export::Exception, message) -end - -def mock_error(subject, message) - mock_exit do - mock(subject).puts("ERROR: #{message}") - yield - end -end - -def make_pipe - IO.method(:pipe).arity.zero? ? IO.pipe : IO.pipe("BINARY") -end - -def foreman(args) - capture_stdout do - begin - Foreman::CLI.start(args.split(" ")) - rescue SystemExit - end - end -end - -def forked_foreman(args) - rd, wr = make_pipe - Process.spawn("bundle exec bin/foreman #{args}", :out => wr, :err => wr) - wr.close - rd.read -end - -def fork_and_capture(&blk) - rd, wr = make_pipe - pid = fork do - rd.close - wr.sync = true - $stdout.reopen wr - $stderr.reopen wr - blk.call - $stdout.flush - $stdout.close - end - wr.close - Process.wait pid - buffer = "" - until rd.eof? - buffer += rd.gets - end -end - -def fork_and_get_exitstatus(args) - pid = Process.spawn("bundle exec bin/foreman #{args}", :out => "/dev/null", :err => "/dev/null") - Process.wait(pid) - $?.exitstatus -end - -def mock_exit(&block) - expect(block).to raise_error(SystemExit) -end - -def write_foreman_config(app) - File.open("/etc/foreman/#{app}.conf", "w") do |file| - file.puts %{#{app}_processes="alpha bravo"} - file.puts %{#{app}_alpha="1"} - file.puts %{#{app}_bravo="2"} - end -end - -def write_procfile(procfile="Procfile", alpha_env="") - File.open(procfile, "w") do |file| - file.puts "alpha: ./alpha" + " #{alpha_env}".rstrip - file.puts "\n" - file.puts "bravo:\t./bravo" - file.puts "foo_bar:\t./foo_bar" - file.puts "foo-bar:\t./foo-bar" - end - File.expand_path(procfile) -end - -def write_env(env=".env", options={"FOO"=>"bar"}) - File.open(env, "w") do |file| - options.each do |key, val| - file.puts "#{key}=#{val}" - end - end -end - -def without_fakefs - FakeFS.deactivate! - ret = yield - FakeFS.activate! - ret -end - -def load_export_templates_into_fakefs(type) - without_fakefs do - Dir[File.expand_path("../../data/export/#{type}/**/*", __FILE__)].inject({}) do |hash, file| - next(hash) if File.directory?(file) - hash.update(file => File.read(file)) - end - end.each do |filename, contents| - FileUtils.mkdir_p File.dirname(filename) - File.open(filename, "w") do |f| - f.puts contents - end - end -end - -def resource_path(filename) - File.expand_path("../resources/#{filename}", __FILE__) -end - -def example_export_file(filename) - FakeFS.deactivate! - data = File.read(File.expand_path(resource_path("export/#{filename}"), __FILE__)) - FakeFS.activate! - data -end - -def preserving_env - old_env = ENV.to_hash - begin - yield - ensure - ENV.clear - ENV.update(old_env) - end -end - -def normalize_space(s) - s.gsub(/\n[\n\s]*/, "\n") -end - -def capture_stdout - old_stdout = $stdout.dup - rd, wr = make_pipe - $stdout = wr - yield - wr.close - rd.read -ensure - $stdout = old_stdout -end - -RSpec.configure do |config| - config.treat_symbols_as_metadata_keys_with_true_values = true - config.color = true - config.order = 'rand' - config.include FakeFS::SpecHelpers, :fakefs - config.mock_with :rr -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.document b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.document deleted file mode 100644 index 93e7dba..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.document +++ /dev/null @@ -1,17 +0,0 @@ -LICENSE -README -TODO -NEWS -LATEST -ChangeLog -ISSUES -HACKING -lib -ext/kgio/accept.c -ext/kgio/autopush.c -ext/kgio/connect.c -ext/kgio/kgio_ext.c -ext/kgio/poll.c -ext/kgio/read_write.c -ext/kgio/wait.c -ext/kgio/tryopen.c diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.gitignore b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.gitignore deleted file mode 100644 index 2368011..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -/local.mk -*.o -*.log -*.so -*.rbc -/.config -/InstalledFiles -/doc -/local.mk -/test/install-* -Makefile -log/ -pkg/ -/NEWS -/ChangeLog -/.manifest -/GIT-VERSION-FILE -/man -tags -TAGS -/LATEST -/tmp diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.wrongdoc.yml b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.wrongdoc.yml deleted file mode 100644 index be371f5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/.wrongdoc.yml +++ /dev/null @@ -1,6 +0,0 @@ ---- -cgit_url: http://bogomips.org/kgio.git -git_url: git://bogomips.org/kgio.git -rdoc_url: http://bogomips.org/kgio/ -public_email: kgio@librelist.org -private_email: kgio@bogomips.org diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/COPYING b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/COPYING deleted file mode 100644 index cca7fc2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/COPYING +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/GIT-VERSION-GEN b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/GIT-VERSION-GEN deleted file mode 100755 index 5cd7851..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/GIT-VERSION-GEN +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/sh - -GVF=GIT-VERSION-FILE -DEF_VER=v2.9.2 - -LF=' -' - -# First see if there is a version file (included in release tarballs), -# then try git-describe, then default. -if test -f version -then - VN=$(cat version) || VN="$DEF_VER" -elif test -d .git -o -f .git && - VN=$(git describe --abbrev=4 HEAD 2>/dev/null) && - case "$VN" in - *$LF*) (exit 1) ;; - v[0-9]*) - git update-index -q --refresh - test -z "$(git diff-index --name-only HEAD --)" || - VN="$VN-dirty" ;; - esac -then - VN=$(echo "$VN" | sed -e 's/-/./g'); -else - VN="$DEF_VER" -fi - -VN=$(expr "$VN" : v*'\(.*\)') - -if test -r $GVF -then - VC=$(sed -e 's/^GIT_VERSION = //' <$GVF) -else - VC=unset -fi -test "$VN" = "$VC" || { - echo >&2 "GIT_VERSION = $VN" - echo "GIT_VERSION = $VN" >$GVF -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/GNUmakefile b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/GNUmakefile deleted file mode 100644 index 89408d3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/GNUmakefile +++ /dev/null @@ -1,9 +0,0 @@ -all:: -RSYNC_DEST := bogomips.org:/srv/bogomips/kgio -rfproject := rainbows -rfpackage := kgio -include pkg.mk -ifneq ($(VERSION),) -release:: - $(RAKE) publish_news VERSION=$(VERSION) -endif diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/HACKING b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/HACKING deleted file mode 100644 index 5d485be..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/HACKING +++ /dev/null @@ -1,78 +0,0 @@ -= kgio Hacker's Guide - -=== Documentation - -We use the latest version of {wrongdoc}[http://bogomips.org/wrongdoc] as -much as possible. - -Please wrap documentation at 72 characters-per-line or less (long URLs -are exempt) so it is comfortably readable from terminals. - -When referencing mailing list posts, use -"http://mid.gmane.org/$MESSAGE_ID" if possible since the Message-ID -remains searchable even if Gmane becomes unavailable. - -=== Code Compatibility - -We target Ruby 1.8.6+, 1.9.1+ and Rubinius 1.1+ and their -respective C APIs. - -All of our C code should be compatible with all reasonably modern Unices -and should run on compilers supported by the versions of Ruby we target. - -We will NEVER directly support non-Free platforms under any circumstances. - -Our C code follows K&R indentation style (hard tabs, tabs are always 8 -characters wide) and NOT the indentation style of Matz Ruby. - -== Contributing - -Contributions are welcome in the form of patches, pull requests, code -review, testing, documentation, user support or any other feedback. The -{kgio mailing list}[mailto:kgio@librelist.org] is the -central coordination point for all user and developer feedback and bug -reports. - -=== Submitting Patches - -Follow conventions already established in the code and do not exceed 80 -characters per line. - -Inline patches (from "git format-patch -M") to the mailing list are -preferred because they allow code review and comments in the reply to -the patch. - -We will adhere to mostly the same conventions for patch submissions as -git itself. See the Documentation/SubmittingPatches document -distributed with git on on patch submission guidelines to follow. Just -don't email the git mailing list or maintainer with kgio patches :) - -== Running Development Versions - -It is easy to install the contents of your git working directory: - -Via RubyGems (RubyGems 1.3.5+ recommended for prerelease versions): - - gmake install-gem - -Without RubyGems (via setup.rb): - - gmake install - -It is not at all recommended to mix a RubyGems installation with an -installation done without RubyGems, however. - -=== Tests - -We use GNU make to run tests in parallel. test/unit/parallel didn't -exist for old versions of Ruby before 1.9.3. Users of GNU-based systems -(such as GNU/Linux) usually have GNU make installed as "make" instead of -"gmake". - -Running the entire test suite with 4 tests in parallel: - - gmake -j4 test - -Running just one unit test: - - gmake test/test_poll.rb diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ISSUES b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ISSUES deleted file mode 100644 index 63ad2df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ISSUES +++ /dev/null @@ -1,34 +0,0 @@ -= Issues - -The kgio {mailing list}[mailto:kgio@librelist.org] is the best -place to report bugs, submit patches and/or obtain support after you -have searched the mailing list archives and -{documentation}[http://bogomips.org/kgio]. - -* Do not {top post}[http://catb.org/jargon/html/T/top-post.html] in replies -* Quote only the relevant portions of the message you're replying to -* Do not send any HTML mail at all - -If your issue is of a sensitive nature or you're just shy in public, -then feel free to email us privately at mailto:kgio@bogomips.org -instead and your issue will be handled discreetly. - -If you don't get a response within a few days, we may have forgotten -about it so feel free to ask again. - -== Submitting Patches - -See the HACKING document (and additionally, the -Documentation/SubmittingPatches document distributed with git) on -guidelines for patch submission. - -== Mailing List Info - -* subscribe: send a message to the mailing list -* post: mailto:kgio@librelist.org -* private: mailto:kgio@bogomips.org - -== Mailing List Archives (coming soon) - -* http://bogomips.org/kgio/archives/ -* nntp://news.gmane.org/gmane.comp.lang.ruby.kgio.general diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/LICENSE b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/LICENSE deleted file mode 100644 index 9f5efcf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -kgio is copyrighted Free Software by all contributors, see logs in -revision control for names and email addresses of all of them. - -You can redistribute it and/or modify it under the terms of the GNU -Lesser General Public License (LGPL) as published by the Free Software -Foundation, version {2.1}[http://www.gnu.org/licenses/lgpl-2.1.txt] or -or {3}[http://www.gnu.org/licenses/lgpl-3.0.txt] (see link:COPYING). -The kgio project leader (Eric Wong) reserves the right to -relicense kgio under future versions of the LGPL. - -kgio is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with kgio; if not, write to the Free Software -Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/README b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/README deleted file mode 100644 index dede94f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/README +++ /dev/null @@ -1,64 +0,0 @@ -= kgio - kinder, gentler I/O for Ruby - -kgio provides non-blocking I/O methods for Ruby without raising -exceptions on EAGAIN and EINPROGRESS. It is intended for use with the -Unicorn and Rainbows! Rack servers, but may be used by other -applications (that run on Unix-like platforms). - -== Features - -* Can avoid expensive exceptions on common EAGAIN/EINPROGRESS errors, - returning :wait_readable or :wait_writable instead. - These exceptions got more expensive to hit under Ruby 1.9.2 - (but should be fixed in Ruby 1.9.3 to 1.9.1 performance levels) - -* Returns the unwritten portion of the string on partial writes, - making it ideal for buffering unwritten data. - -* May call any method defined to be "kgio_wait_writable" or - "kgio_wait_readable" methods to allow socket/pipe objects to make custom - callbacks (such as adding the file descriptor to a poll set and yielding - the current Fiber). - -* Uses - {accept4}[http://kernel.org/doc/man-pages/online/pages/man2/accept4.2.html] - on new GNU/Linux systems to avoid unnecessary fcntl() calls - -* Uses MSG_DONTWAIT on GNU/Linux to further avoid unnecessary fcntl() calls - -* Compatible with existing Ruby IO objects and Ruby threading. - -== Install - -The library consists of a C extension so you'll need a Unix-like system -with a C compiler and Ruby development libraries/headers. - -http://rubyforge.org/frs/?group_id=8977 - -You may also install it via RubyGems.org: - - gem install kgio - -You can get the latest source via git from the following locations -(these versions may not be stable): - - git://bogomips.org/kgio.git - git://repo.or.cz/kgio.git (mirror) - -You may browse the code from the web and download the latest snapshot -tarballs here: - -* http://bogomips.org/kgio.git (cgit) -* http://repo.or.cz/w/kgio.git (gitweb) - -See the HACKING guide on how to contribute and build prerelease gems -from git. - -== Contact - -All feedback (bug reports, user/development dicussion, patches, pull -requests) go to the mailing list/newsgroup. See the ISSUES document for -information on the {kgio mailing list}[mailto:kgio@librelist.org] - -For the latest on kgio releases, you may check our NEWS page (and -subscribe to our Atom feed). diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/Rakefile b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/Rakefile deleted file mode 100644 index cbeb7a0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/Rakefile +++ /dev/null @@ -1,32 +0,0 @@ -# -*- encoding: binary -*- -cgit_url = "http://bogomips.org/kgio.git" -git_url = 'git://bogomips.org/kgio.git' - -desc "post news article to rubyforge" -task :publish_news do - require 'rubyforge' - spec = Gem::Specification.load('kgio.gemspec') - tmp = Tempfile.new('rf-news') - _, subject, body = `git cat-file tag v#{spec.version}`.split(/\n\n/, 3) - tmp.puts subject - tmp.puts - tmp.puts spec.description.strip - tmp.puts "" - tmp.puts "* #{spec.homepage}" - tmp.puts "* #{spec.email}" - tmp.puts "* #{git_url}" - tmp.print "\nChanges:\n\n" - tmp.puts body - tmp.flush - system(ENV["VISUAL"], tmp.path) or abort "#{ENV["VISUAL"]} failed: #$?" - msg = File.readlines(tmp.path) - subject = msg.shift - blank = msg.shift - blank == "\n" or abort "no newline after subject!" - subject.strip! - body = msg.join("").strip! - - rf = RubyForge.new.configure - rf.login - rf.post_news('rainbows', subject, body) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/TODO b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/TODO deleted file mode 100644 index 5754660..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/TODO +++ /dev/null @@ -1 +0,0 @@ -* SSL/TLS support with SNI ({done}[http://bogomips.org/kgio-monkey/]) diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/.RUBYARCHDIR.time b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/.RUBYARCHDIR.time deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/accept.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/accept.c deleted file mode 100644 index c847c92..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/accept.c +++ /dev/null @@ -1,538 +0,0 @@ -/* ref: rubinius b2811f260de16d1e972462e27852470364608de5 */ -#define RSTRING_MODIFIED 1 - -#include "kgio.h" -#include "missing_accept4.h" -#include "sock_for_fd.h" -#include "my_fileno.h" -#include "nonblock.h" - -static VALUE localhost; -static VALUE cClientSocket; -static VALUE cKgio_Socket; -static VALUE mSocketMethods; -static VALUE iv_kgio_addr; - -#if defined(__linux__) && defined(KGIO_WITHOUT_GVL) -static int accept4_flags = SOCK_CLOEXEC; -#else /* ! linux */ -static int accept4_flags = SOCK_CLOEXEC | SOCK_NONBLOCK; -#endif /* ! linux */ - -struct accept_args { - int fd; - int flags; - struct sockaddr *addr; - socklen_t *addrlen; - VALUE accept_io; - VALUE accepted_class; -}; - -/* - * Sets the default class for newly accepted sockets. This is - * legacy behavior, kgio_accept and kgio_tryaccept now take optional - * class arguments to override this value. - */ -static VALUE set_accepted(VALUE klass, VALUE aclass) -{ - VALUE tmp; - - if (NIL_P(aclass)) - aclass = cKgio_Socket; - - tmp = rb_funcall(aclass, rb_intern("included_modules"), 0, 0); - tmp = rb_funcall(tmp, rb_intern("include?"), 1, mSocketMethods); - - if (tmp != Qtrue) - rb_raise(rb_eTypeError, - "class must include Kgio::SocketMethods"); - - cClientSocket = aclass; - - return aclass; -} - -/* - * Returns the default class for newly accepted sockets when kgio_accept - * or kgio_tryaccept are not passed arguments - */ -static VALUE get_accepted(VALUE klass) -{ - return cClientSocket; -} - -/* - * accept() wrapper that'll fall back on accept() if we were built on - * a system with accept4() but run on a system without accept4() - */ -static VALUE xaccept(void *ptr) -{ - struct accept_args *a = ptr; - int rv; - - rv = accept_fn(a->fd, a->addr, a->addrlen, a->flags); - if (rv < 0 && errno == ENOSYS && accept_fn != my_accept4) { - accept_fn = my_accept4; - rv = accept_fn(a->fd, a->addr, a->addrlen, a->flags); - } - - return (VALUE)rv; -} - -#ifdef KGIO_WITHOUT_GVL -# include -# include "blocking_io_region.h" -static int thread_accept(struct accept_args *a, int force_nonblock) -{ - if (force_nonblock) - set_nonblocking(a->fd); - return (int)rb_thread_io_blocking_region(xaccept, a, a->fd); -} - -#else /* ! KGIO_WITHOUT_GVL */ -# include -static int thread_accept(struct accept_args *a, int force_nonblock) -{ - int rv; - - /* always use non-blocking accept() under 1.8 for green threads */ - set_nonblocking(a->fd); - - /* created sockets are always non-blocking under 1.8, too */ - a->flags |= SOCK_NONBLOCK; - - TRAP_BEG; - rv = (int)xaccept(a); - TRAP_END; - return rv; -} -#endif /* ! KGIO_WITHOUT_GVL */ - -static void -prepare_accept(struct accept_args *a, VALUE self, int argc, const VALUE *argv) -{ - a->fd = my_fileno(self); - a->accept_io = self; - - switch (argc) { - case 2: - a->flags = NUM2INT(argv[1]); - a->accepted_class = NIL_P(argv[0]) ? cClientSocket : argv[0]; - return; - case 0: /* default, legacy behavior */ - a->flags = accept4_flags; - a->accepted_class = cClientSocket; - return; - case 1: - a->flags = accept4_flags; - a->accepted_class = NIL_P(argv[0]) ? cClientSocket : argv[0]; - return; - } - - rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc); -} - -static VALUE in_addr_set(VALUE io, struct sockaddr_storage *addr, socklen_t len) -{ - VALUE host; - int host_len, rc; - char *host_ptr; - - switch (addr->ss_family) { - case AF_INET: - host_len = (long)INET_ADDRSTRLEN; - break; - case AF_INET6: - host_len = (long)INET6_ADDRSTRLEN; - break; - default: - rb_raise(rb_eRuntimeError, - "unsupported address family: ss_family=%lu (socklen=%ld)", - (unsigned long)addr->ss_family, (long)len); - } - host = rb_str_new(NULL, host_len); - host_ptr = RSTRING_PTR(host); - rc = getnameinfo((struct sockaddr *)addr, len, - host_ptr, host_len, NULL, 0, NI_NUMERICHOST); - if (rc != 0) - rb_raise(rb_eRuntimeError, "getnameinfo: %s", gai_strerror(rc)); - rb_str_set_len(host, strlen(host_ptr)); - return rb_ivar_set(io, iv_kgio_addr, host); -} - -#if defined(__linux__) -# define post_accept kgio_autopush_accept -#else -# define post_accept(a,b) for(;0;) -#endif - -static VALUE -my_accept(struct accept_args *a, int force_nonblock) -{ - int client_fd; - VALUE client_io; - int retried = 0; - -retry: - client_fd = thread_accept(a, force_nonblock); - if (client_fd < 0) { - switch (errno) { - case EAGAIN: - if (force_nonblock) - return Qnil; - a->fd = my_fileno(a->accept_io); - errno = EAGAIN; - (void)rb_io_wait_readable(a->fd); - /* fall-through to EINTR case */ -#ifdef ECONNABORTED - case ECONNABORTED: -#endif /* ECONNABORTED */ -#ifdef EPROTO - case EPROTO: -#endif /* EPROTO */ - case EINTR: - /* raise IOError if closed during sleep */ - a->fd = my_fileno(a->accept_io); - goto retry; - case ENOMEM: - case EMFILE: - case ENFILE: -#ifdef ENOBUFS - case ENOBUFS: -#endif /* ENOBUFS */ - if (!retried) { - retried = 1; - errno = 0; - rb_gc(); - goto retry; - } - default: - rb_sys_fail("accept"); - } - } - client_io = sock_for_fd(a->accepted_class, client_fd); - post_accept(a->accept_io, client_io); - - if (a->addr) - in_addr_set(client_io, - (struct sockaddr_storage *)a->addr, *a->addrlen); - else - rb_ivar_set(client_io, iv_kgio_addr, localhost); - return client_io; -} - -/* - * call-seq: - * - * io.kgio_addr! => refreshes the given sock address - */ -static VALUE addr_bang(VALUE io) -{ - int fd = my_fileno(io); - struct sockaddr_storage addr; - socklen_t len = sizeof(struct sockaddr_storage); - - if (getpeername(fd, (struct sockaddr *)&addr, &len) != 0) - rb_sys_fail("getpeername"); - - if (addr.ss_family == AF_UNIX) - return rb_ivar_set(io, iv_kgio_addr, localhost); - - return in_addr_set(io, &addr, len); -} - -/* - * call-seq: - * - * server = Kgio::TCPServer.new('0.0.0.0', 80) - * server.kgio_tryaccept -> Kgio::Socket or nil - * server.kgio_tryaccept(klass = MySocket) -> MySocket or nil - * server.kgio_tryaccept(nil, flags) -> Kgio::Socket or nil - * - * Initiates a non-blocking accept and returns a generic Kgio::Socket - * object with the kgio_addr attribute set to the IP address of the - * connected client on success. - * - * Returns nil on EAGAIN, and raises on other errors. - * - * An optional +klass+ argument may be specified to override the - * Kgio::Socket-class on a successful return value. - * - * An optional +flags+ argument may also be specified. - * +flags+ is a bitmask that may contain any combination of: - * - * - Kgio::SOCK_CLOEXEC - close-on-exec flag (enabled by default) - * - Kgio::SOCK_NONBLOCK - non-blocking flag (unimportant) - */ -static VALUE tcp_tryaccept(int argc, VALUE *argv, VALUE self) -{ - struct sockaddr_storage addr; - socklen_t addrlen = sizeof(struct sockaddr_storage); - struct accept_args a; - - a.addr = (struct sockaddr *)&addr; - a.addrlen = &addrlen; - prepare_accept(&a, self, argc, argv); - return my_accept(&a, 1); -} - -/* - * call-seq: - * - * server = Kgio::TCPServer.new('0.0.0.0', 80) - * server.kgio_accept -> Kgio::Socket or nil - * server.kgio_tryaccept -> Kgio::Socket or nil - * server.kgio_tryaccept(klass = MySocket) -> MySocket or nil - * - * Initiates a blocking accept and returns a generic Kgio::Socket - * object with the kgio_addr attribute set to the IP address of - * the client on success. - * - * On Ruby implementations using native threads, this can use a blocking - * accept(2) (or accept4(2)) system call to avoid thundering herds. - * - * An optional +klass+ argument may be specified to override the - * Kgio::Socket-class on a successful return value. - * - * An optional +flags+ argument may also be specified. - * +flags+ is a bitmask that may contain any combination of: - * - * - Kgio::SOCK_CLOEXEC - close-on-exec flag (enabled by default) - * - Kgio::SOCK_NONBLOCK - non-blocking flag (unimportant) - */ -static VALUE tcp_accept(int argc, VALUE *argv, VALUE self) -{ - struct sockaddr_storage addr; - socklen_t addrlen = sizeof(struct sockaddr_storage); - struct accept_args a; - - a.addr = (struct sockaddr *)&addr; - a.addrlen = &addrlen; - prepare_accept(&a, self, argc, argv); - return my_accept(&a, 0); -} - -/* - * call-seq: - * - * server = Kgio::UNIXServer.new("/path/to/unix/socket") - * server.kgio_tryaccept -> Kgio::Socket or nil - * server.kgio_tryaccept(klass = MySocket) -> MySocket or nil - * server.kgio_tryaccept(nil, flags) -> Kgio::Socket or nil - * - * Initiates a non-blocking accept and returns a generic Kgio::Socket - * object with the kgio_addr attribute set (to the value of - * Kgio::LOCALHOST) on success. - * - * An optional +klass+ argument may be specified to override the - * Kgio::Socket-class on a successful return value. - * - * An optional +flags+ argument may also be specified. - * +flags+ is a bitmask that may contain any combination of: - * - * - Kgio::SOCK_CLOEXEC - close-on-exec flag (enabled by default) - * - Kgio::SOCK_NONBLOCK - non-blocking flag (unimportant) - */ -static VALUE unix_tryaccept(int argc, VALUE *argv, VALUE self) -{ - struct accept_args a; - - a.addr = NULL; - a.addrlen = NULL; - prepare_accept(&a, self, argc, argv); - return my_accept(&a, 1); -} - -/* - * call-seq: - * - * server = Kgio::UNIXServer.new("/path/to/unix/socket") - * server.kgio_accept -> Kgio::Socket or nil - * server.kgio_accept(klass = MySocket) -> MySocket or nil - * server.kgio_accept(nil, flags) -> Kgio::Socket or nil - * - * Initiates a blocking accept and returns a generic Kgio::Socket - * object with the kgio_addr attribute set (to the value of - * Kgio::LOCALHOST) on success. - * - * On Ruby implementations using native threads, this can use a blocking - * accept(2) (or accept4(2)) system call to avoid thundering herds. - * - * An optional +klass+ argument may be specified to override the - * Kgio::Socket-class on a successful return value. - * - * An optional +flags+ argument may also be specified. - * +flags+ is a bitmask that may contain any combination of: - * - * - Kgio::SOCK_CLOEXEC - close-on-exec flag (enabled by default) - * - Kgio::SOCK_NONBLOCK - non-blocking flag (unimportant) - */ -static VALUE unix_accept(int argc, VALUE *argv, VALUE self) -{ - struct accept_args a; - - a.addr = NULL; - a.addrlen = NULL; - prepare_accept(&a, self, argc, argv); - return my_accept(&a, 0); -} - -/* - * call-seq: - * - * Kgio.accept_cloexec? -> true or false - * - * Returns true if newly accepted Kgio::Sockets are created with the - * FD_CLOEXEC file descriptor flag, false if not. - * - * Deprecated, use the per-socket flags for kgio_*accept instead. - */ -static VALUE get_cloexec(VALUE mod) -{ - return (accept4_flags & SOCK_CLOEXEC) == SOCK_CLOEXEC ? Qtrue : Qfalse; -} - -/* - * - * call-seq: - * - * Kgio.accept_nonblock? -> true or false - * - * Returns true if newly accepted Kgio::Sockets are created with the - * O_NONBLOCK file status flag, false if not. - * - * Deprecated, use the per-socket flags for kgio_*accept instead. - */ -static VALUE get_nonblock(VALUE mod) -{ - return (accept4_flags & SOCK_NONBLOCK)==SOCK_NONBLOCK ? Qtrue : Qfalse; -} - -/* - * call-seq: - * - * Kgio.accept_cloexec = true - * Kgio.accept_cloexec = false - * - * Sets whether or not Kgio::Socket objects created by - * TCPServer#kgio_accept, - * TCPServer#kgio_tryaccept, - * UNIXServer#kgio_accept, - * and UNIXServer#kgio_tryaccept - * default to being created with the FD_CLOEXEC file descriptor flag. - * - * This is on by default, as there is little reason to deal to enable - * it for client sockets on a socket server. - * - * Deprecated, use the per-socket flags for kgio_*accept instead. - */ -static VALUE set_cloexec(VALUE mod, VALUE boolean) -{ - switch (TYPE(boolean)) { - case T_TRUE: - accept4_flags |= SOCK_CLOEXEC; - return boolean; - case T_FALSE: - accept4_flags &= ~SOCK_CLOEXEC; - return boolean; - } - rb_raise(rb_eTypeError, "not true or false"); - return Qnil; -} - -/* - * call-seq: - * - * Kgio.accept_nonblock = true - * Kgio.accept_nonblock = false - * - * Sets whether or not Kgio::Socket objects created by - * TCPServer#kgio_accept, - * TCPServer#kgio_tryaccept, - * UNIXServer#kgio_accept, - * and UNIXServer#kgio_tryaccept - * are created with the O_NONBLOCK file status flag. - * - * This defaults to +false+ for GNU/Linux where MSG_DONTWAIT is - * available (and on newer GNU/Linux, accept4() may also set - * the non-blocking flag. This defaults to +true+ on non-GNU/Linux - * systems. - * - * This is always true on Ruby implementations using user-space threads. - * - * Deprecated, use the per-socket flags for kgio_*accept instead. - */ -static VALUE set_nonblock(VALUE mod, VALUE boolean) -{ - switch (TYPE(boolean)) { - case T_TRUE: - accept4_flags |= SOCK_NONBLOCK; - return boolean; - case T_FALSE: - accept4_flags &= ~SOCK_NONBLOCK; - return boolean; - } - rb_raise(rb_eTypeError, "not true or false"); - return Qnil; -} - -void init_kgio_accept(void) -{ - VALUE cUNIXServer, cTCPServer; - VALUE mKgio = rb_define_module("Kgio"); - - /* - * Maps to the SOCK_NONBLOCK constant in Linux for setting - * the non-blocking flag on newly accepted sockets. This is - * usually unnecessary as sockets are made non-blocking - * whenever non-blocking methods are used. - */ - rb_define_const(mKgio, "SOCK_NONBLOCK", INT2NUM(SOCK_NONBLOCK)); - - /* - * Maps to the SOCK_CLOEXEC constant in Linux for setting - * the close-on-exec flag on newly accepted descriptors. This - * is enabled by default, and there is usually no reason to - * disable close-on-exec for accepted sockets. - */ - rb_define_const(mKgio, "SOCK_CLOEXEC", INT2NUM(SOCK_CLOEXEC)); - - localhost = rb_const_get(mKgio, rb_intern("LOCALHOST")); - cKgio_Socket = rb_const_get(mKgio, rb_intern("Socket")); - cClientSocket = cKgio_Socket; - mSocketMethods = rb_const_get(mKgio, rb_intern("SocketMethods")); - - rb_define_method(mSocketMethods, "kgio_addr!", addr_bang, 0); - - rb_define_singleton_method(mKgio, "accept_cloexec?", get_cloexec, 0); - rb_define_singleton_method(mKgio, "accept_cloexec=", set_cloexec, 1); - rb_define_singleton_method(mKgio, "accept_nonblock?", get_nonblock, 0); - rb_define_singleton_method(mKgio, "accept_nonblock=", set_nonblock, 1); - rb_define_singleton_method(mKgio, "accept_class=", set_accepted, 1); - rb_define_singleton_method(mKgio, "accept_class", get_accepted, 0); - - /* - * Document-class: Kgio::UNIXServer - * - * Kgio::UNIXServer should be used in place of the plain UNIXServer - * when kgio_accept and kgio_tryaccept methods are needed. - */ - cUNIXServer = rb_const_get(rb_cObject, rb_intern("UNIXServer")); - cUNIXServer = rb_define_class_under(mKgio, "UNIXServer", cUNIXServer); - rb_define_method(cUNIXServer, "kgio_tryaccept", unix_tryaccept, -1); - rb_define_method(cUNIXServer, "kgio_accept", unix_accept, -1); - - /* - * Document-class: Kgio::TCPServer - * - * Kgio::TCPServer should be used in place of the plain TCPServer - * when kgio_accept and kgio_tryaccept methods are needed. - */ - cTCPServer = rb_const_get(rb_cObject, rb_intern("TCPServer")); - cTCPServer = rb_define_class_under(mKgio, "TCPServer", cTCPServer); - - rb_define_method(cTCPServer, "kgio_tryaccept", tcp_tryaccept, -1); - rb_define_method(cTCPServer, "kgio_accept", tcp_accept, -1); - init_sock_for_fd(); - iv_kgio_addr = rb_intern("@kgio_addr"); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/ancient_ruby.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/ancient_ruby.h deleted file mode 100644 index fb0a80b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/ancient_ruby.h +++ /dev/null @@ -1,24 +0,0 @@ -#ifndef MISSING_ANCIENT_RUBY_H -#define MISSING_ANCIENT_RUBY_H - -#ifndef HAVE_RB_STR_SET_LEN -static void my_str_set_len(VALUE str, long len) -{ - RSTRING(str)->len = len; - RSTRING(str)->ptr[len] = '\0'; -} -#define rb_str_set_len(str,len) my_str_set_len((str),(len)) -#endif /* ! HAVE_RB_STR_SET_LEN */ - -#ifndef RSTRING_PTR -# define RSTRING_PTR(s) (RSTRING(s)->ptr) -#endif /* !defined(RSTRING_PTR) */ -#ifndef RSTRING_LEN -# define RSTRING_LEN(s) (RSTRING(s)->len) -#endif /* !defined(RSTRING_LEN) */ - -#ifndef RARRAY_LEN -# define RARRAY_LEN(s) (RARRAY(s)->len) -#endif /* !defined(RARRAY_LEN) */ - -#endif /* MISSING_ANCIENT_RUBY_H */ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/autopush.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/autopush.c deleted file mode 100644 index 74576e8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/autopush.c +++ /dev/null @@ -1,247 +0,0 @@ -/* - * We use a very basic strategy to use TCP_CORK semantics optimally - * in most TCP servers: On corked sockets, we will uncork on recv() - * if there was a previous send(). Otherwise we do not fiddle - * with TCP_CORK at all. - * - * Under Linux, we can rely on TCP_CORK being inherited in an - * accept()-ed client socket so we can avoid syscalls for each - * accept()-ed client if we know the accept() socket corks. - * - * This module does NOTHING for client TCP sockets, we only deal - * with accept()-ed sockets right now. - */ - -#include "kgio.h" -#include "my_fileno.h" -#include - -/* - * As of FreeBSD 4.5, TCP_NOPUSH == TCP_CORK - * ref: http://dotat.at/writing/nopush.html - * We won't care for older FreeBSD since nobody runs Ruby on them... - */ -#ifdef TCP_CORK -# define KGIO_NOPUSH TCP_CORK -#elif defined(TCP_NOPUSH) -# define KGIO_NOPUSH TCP_NOPUSH -#endif - -#ifdef KGIO_NOPUSH -static ID id_autopush_state; -static int enabled = 1; - -enum autopush_state { - AUTOPUSH_STATE_ACCEPTOR_IGNORE = -1, - AUTOPUSH_STATE_IGNORE = 0, - AUTOPUSH_STATE_WRITER = 1, - AUTOPUSH_STATE_WRITTEN = 2, - AUTOPUSH_STATE_ACCEPTOR = 3 -}; - -#if defined(R_CAST) && \ - defined(HAVE_TYPE_STRUCT_RFILE) && \ - defined(HAVE_TYPE_STRUCT_ROBJECT) && \ - ((SIZEOF_STRUCT_RFILE + SIZEOF_INT) <= (SIZEOF_STRUCT_ROBJECT)) - -struct AutopushSocket { - struct RFile rfile; - enum autopush_state autopush_state; -}; - -static enum autopush_state state_get(VALUE io) -{ - return ((struct AutopushSocket *)(io))->autopush_state; -} - -static void state_set(VALUE io, enum autopush_state state) -{ - ((struct AutopushSocket *)(io))->autopush_state = state; -} -#else -static enum autopush_state state_get(VALUE io) -{ - VALUE val; - - if (rb_ivar_defined(io, id_autopush_state) == Qfalse) - return AUTOPUSH_STATE_IGNORE; - val = rb_ivar_get(io, id_autopush_state); - - return (enum autopush_state)NUM2INT(val); -} - -static void state_set(VALUE io, enum autopush_state state) -{ - rb_ivar_set(io, id_autopush_state, INT2NUM(state)); -} -#endif /* IVAR fallback */ - -static enum autopush_state detect_acceptor_state(VALUE io); -static void push_pending_data(VALUE io); - -/* - * call-seq: - * Kgio.autopush? -> true or false - * - * Returns whether or not autopush is enabled. - * - * Only available on systems with TCP_CORK (Linux) or - * TCP_NOPUSH (FreeBSD, and maybe other *BSDs). - */ -static VALUE s_get_autopush(VALUE self) -{ - return enabled ? Qtrue : Qfalse; -} - -/* - * call-seq: - * Kgio.autopush = true - * Kgio.autopush = false - * - * Enables or disables autopush for sockets created with kgio_accept - * and kgio_tryaccept methods. Autopush relies on TCP_CORK/TCP_NOPUSH - * being enabled on the listen socket. - * - * Only available on systems with TCP_CORK (Linux) or - * TCP_NOPUSH (FreeBSD, and maybe other *BSDs). - */ -static VALUE s_set_autopush(VALUE self, VALUE val) -{ - enabled = RTEST(val); - - return val; -} - -/* - * call-seq: - * - * io.kgio_autopush? -> true or false - * - * Returns the current autopush state of the Kgio::SocketMethods-enabled - * socket. - * - * Only available on systems with TCP_CORK (Linux) or - * TCP_NOPUSH (FreeBSD, and maybe other *BSDs). - */ -static VALUE autopush_get(VALUE io) -{ - return state_get(io) <= 0 ? Qfalse : Qtrue; -} - -/* - * call-seq: - * - * io.kgio_autopush = true - * io.kgio_autopush = false - * - * Enables or disables autopush on any given Kgio::SocketMethods-capable - * IO object. This does NOT enable or disable TCP_NOPUSH/TCP_CORK right - * away, that must be done with IO.setsockopt - * - * Only available on systems with TCP_CORK (Linux) or - * TCP_NOPUSH (FreeBSD, and maybe other *BSDs). - */ -static VALUE autopush_set(VALUE io, VALUE vbool) -{ - if (RTEST(vbool)) - state_set(io, AUTOPUSH_STATE_WRITER); - else - state_set(io, AUTOPUSH_STATE_IGNORE); - return vbool; -} - -void init_kgio_autopush(void) -{ - VALUE mKgio = rb_define_module("Kgio"); - VALUE tmp; - - rb_define_singleton_method(mKgio, "autopush?", s_get_autopush, 0); - rb_define_singleton_method(mKgio, "autopush=", s_set_autopush, 1); - - tmp = rb_define_module_under(mKgio, "SocketMethods"); - rb_define_method(tmp, "kgio_autopush=", autopush_set, 1); - rb_define_method(tmp, "kgio_autopush?", autopush_get, 0); - - id_autopush_state = rb_intern("@kgio_autopush_state"); -} - -/* - * called after a successful write, just mark that we've put something - * in the skb and will need to uncork on the next write. - */ -void kgio_autopush_send(VALUE io) -{ - if (state_get(io) == AUTOPUSH_STATE_WRITER) - state_set(io, AUTOPUSH_STATE_WRITTEN); -} - -/* called on successful accept() */ -void kgio_autopush_accept(VALUE accept_io, VALUE client_io) -{ - enum autopush_state acceptor_state; - - if (!enabled) - return; - acceptor_state = state_get(accept_io); - if (acceptor_state == AUTOPUSH_STATE_IGNORE) - acceptor_state = detect_acceptor_state(accept_io); - if (acceptor_state == AUTOPUSH_STATE_ACCEPTOR) - state_set(client_io, AUTOPUSH_STATE_WRITER); - else - state_set(client_io, AUTOPUSH_STATE_IGNORE); -} - -void kgio_autopush_recv(VALUE io) -{ - if (enabled && (state_get(io) == AUTOPUSH_STATE_WRITTEN)) { - push_pending_data(io); - state_set(io, AUTOPUSH_STATE_WRITER); - } -} - -static enum autopush_state detect_acceptor_state(VALUE io) -{ - int corked = 0; - int fd = my_fileno(io); - socklen_t optlen = sizeof(int); - enum autopush_state state; - - if (getsockopt(fd, IPPROTO_TCP, KGIO_NOPUSH, &corked, &optlen) != 0) { - if (errno != EOPNOTSUPP) - rb_sys_fail("getsockopt(TCP_CORK/TCP_NOPUSH)"); - errno = 0; - state = AUTOPUSH_STATE_ACCEPTOR_IGNORE; - } else if (corked) { - state = AUTOPUSH_STATE_ACCEPTOR; - } else { - state = AUTOPUSH_STATE_ACCEPTOR_IGNORE; - } - state_set(io, state); - - return state; -} - -/* - * checks to see if we've written anything since the last recv() - * If we have, uncork the socket and immediately recork it. - */ -static void push_pending_data(VALUE io) -{ - int optval = 0; - const socklen_t optlen = sizeof(int); - const int fd = my_fileno(io); - - if (setsockopt(fd, IPPROTO_TCP, KGIO_NOPUSH, &optval, optlen) != 0) - rb_sys_fail("setsockopt(TCP_CORK/TCP_NOPUSH, 0)"); - /* immediately recork */ - optval = 1; - if (setsockopt(fd, IPPROTO_TCP, KGIO_NOPUSH, &optval, optlen) != 0) - rb_sys_fail("setsockopt(TCP_CORK/TCP_NOPUSH, 1)"); -} -#else /* !KGIO_NOPUSH */ -void kgio_autopush_recv(VALUE io){} -void kgio_autopush_send(VALUE io){} -void init_kgio_autopush(void) -{ -} -#endif /* ! KGIO_NOPUSH */ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/blocking_io_region.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/blocking_io_region.h deleted file mode 100644 index db76eac..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/blocking_io_region.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef KGIO_WITHOUT_GVL -# if defined(HAVE_RB_THREAD_IO_BLOCKING_REGION) -/* temporary API for Ruby 1.9.3 */ -VALUE rb_thread_io_blocking_region(rb_blocking_function_t *, void *, int); -# elif defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL) -# define rb_thread_io_blocking_region(fn,data,fd) \ - rb_thread_call_without_gvl((fn),(data),RUBY_UBF_IO,0) -# elif defined(HAVE_RB_THREAD_BLOCKING_REGION) -# define rb_thread_io_blocking_region(fn,data,fd) \ - rb_thread_blocking_region((fn),(data),RUBY_UBF_IO,0) -# endif -#endif diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/broken_system_compat.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/broken_system_compat.h deleted file mode 100644 index e67a56c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/broken_system_compat.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * this header includes functions to support broken systems - * without clock_gettime() or CLOCK_MONOTONIC - */ - -#ifndef HAVE_TYPE_CLOCKID_T -typedef int clockid_t; -#endif - -#ifndef HAVE_CLOCK_GETTIME -# ifndef CLOCK_REALTIME -# define CLOCK_REALTIME 0 /* whatever */ -# endif -static int fake_clock_gettime(clockid_t clk_id, struct timespec *res) -{ - struct timeval tv; - int r = gettimeofday(&tv, NULL); - - assert(0 == r && "gettimeofday() broke!?"); - res->tv_sec = tv.tv_sec; - res->tv_nsec = tv.tv_usec * 1000; - - return r; -} -# define clock_gettime fake_clock_gettime -#endif /* broken systems w/o clock_gettime() */ - -/* - * UGH - * CLOCK_MONOTONIC is not guaranteed to be a macro, either - */ -#ifndef CLOCK_MONOTONIC -# if (!defined(_POSIX_MONOTONIC_CLOCK) || !defined(HAVE_CLOCK_MONOTONIC)) -# define CLOCK_MONOTONIC CLOCK_REALTIME -# endif -#endif - -/* - * Availability of a monotonic clock needs to be detected at runtime - * since we could've been built on a different system than we're run - * under. - */ -static clockid_t hopefully_CLOCK_MONOTONIC; - -static int check_clock(void) -{ - struct timespec now; - - hopefully_CLOCK_MONOTONIC = CLOCK_MONOTONIC; - - /* we can't check this reliably at compile time */ - if (clock_gettime(CLOCK_MONOTONIC, &now) == 0) - return 1; - - if (clock_gettime(CLOCK_REALTIME, &now) == 0) { - hopefully_CLOCK_MONOTONIC = CLOCK_REALTIME; - rb_warn("CLOCK_MONOTONIC not available, " - "falling back to CLOCK_REALTIME"); - return 2; - } - return -1; -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/connect.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/connect.c deleted file mode 100644 index 19cfa8f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/connect.c +++ /dev/null @@ -1,413 +0,0 @@ -/* We do not modify RSTRING in this file, so RSTRING_MODIFIED is not needed */ -#include "kgio.h" -#include "my_fileno.h" -#include "sock_for_fd.h" -#include "blocking_io_region.h" - -static void close_fail(int fd, const char *msg) -{ - int saved_errno = errno; - (void)close(fd); - errno = saved_errno; - rb_sys_fail(msg); -} - -static int MY_SOCK_STREAM = -#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC) -# ifdef HAVE_RB_FD_FIX_CLOEXEC - (SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC) -# else - (SOCK_STREAM|SOCK_NONBLOCK) -# endif -#else - SOCK_STREAM -#endif /* ! SOCK_NONBLOCK */ -; - -/* do not set close-on-exec by default on Ruby <2.0.0 */ -#ifndef HAVE_RB_FD_FIX_CLOEXEC -# define rb_fd_fix_cloexec(fd) for (;0;) -#endif /* HAVE_RB_FD_FIX_CLOEXEC */ - -/* try to use SOCK_NONBLOCK and SOCK_CLOEXEC */ -static int my_socket(int domain) -{ - int fd; - -retry: - fd = socket(domain, MY_SOCK_STREAM, 0); - - if (fd < 0) { - switch (errno) { - case EMFILE: - case ENFILE: -#ifdef ENOBUFS - case ENOBUFS: -#endif /* ENOBUFS */ - errno = 0; - rb_gc(); - fd = socket(domain, MY_SOCK_STREAM, 0); - break; - case EINVAL: - if (MY_SOCK_STREAM != SOCK_STREAM) { - MY_SOCK_STREAM = SOCK_STREAM; - goto retry; - } - } - if (fd < 0) - rb_sys_fail("socket"); - } - - if (MY_SOCK_STREAM == SOCK_STREAM) { - if (fcntl(fd, F_SETFL, O_RDWR | O_NONBLOCK) < 0) - close_fail(fd, "fcntl(F_SETFL, O_RDWR | O_NONBLOCK)"); - rb_fd_fix_cloexec(fd); - } - - return fd; -} - -static VALUE -my_connect(VALUE klass, int io_wait, int domain, - const void *addr, socklen_t addrlen) -{ - int fd = my_socket(domain); - - if (connect(fd, addr, addrlen) < 0) { - if (errno == EINPROGRESS) { - VALUE io = sock_for_fd(klass, fd); - - if (io_wait) { - errno = EAGAIN; - (void)kgio_call_wait_writable(io); - } - return io; - } - close_fail(fd, "connect"); - } - return sock_for_fd(klass, fd); -} - -static void -tcp_getaddr(struct addrinfo *hints, struct sockaddr_storage *addr, - VALUE ip, VALUE port) -{ - int rc; - struct addrinfo *res; - const char *ipname = StringValuePtr(ip); - char ipport[6]; - unsigned uport; - - if (TYPE(port) != T_FIXNUM) - rb_raise(rb_eTypeError, "port must be a non-negative integer"); - uport = FIX2UINT(port); - - rc = snprintf(ipport, sizeof(ipport), "%u", uport); - if (rc >= (int)sizeof(ipport) || rc <= 0) - rb_raise(rb_eArgError, "invalid TCP port: %u", uport); - memset(hints, 0, sizeof(struct addrinfo)); - hints->ai_family = AF_UNSPEC; - hints->ai_socktype = SOCK_STREAM; - hints->ai_protocol = IPPROTO_TCP; - /* disallow non-deterministic DNS lookups */ - hints->ai_flags = AI_NUMERICHOST; - - rc = getaddrinfo(ipname, ipport, hints, &res); - if (rc != 0) - rb_raise(rb_eArgError, "getaddrinfo(%s:%s): %s", - ipname, ipport, gai_strerror(rc)); - - /* copy needed data and free ASAP to avoid needing rb_ensure */ - hints->ai_family = res->ai_family; - hints->ai_addrlen = res->ai_addrlen; - memcpy(addr, res->ai_addr, res->ai_addrlen); - freeaddrinfo(res); -} - -static VALUE tcp_connect(VALUE klass, VALUE ip, VALUE port, int io_wait) -{ - struct addrinfo hints; - struct sockaddr_storage addr; - - tcp_getaddr(&hints, &addr, ip, port); - - return my_connect(klass, io_wait, hints.ai_family, - &addr, hints.ai_addrlen); -} - -static const struct sockaddr *sockaddr_from(socklen_t *addrlen, VALUE addr) -{ - if (TYPE(addr) == T_STRING) { - *addrlen = (socklen_t)RSTRING_LEN(addr); - return (const struct sockaddr *)(RSTRING_PTR(addr)); - } - rb_raise(rb_eTypeError, "invalid address"); - return NULL; -} - -#if defined(MSG_FASTOPEN) && defined(KGIO_WITHOUT_GVL) -#ifndef HAVE_RB_STR_SUBSEQ -#define rb_str_subseq rb_str_substr -#endif -struct tfo_args { - int fd; - const void *buf; - size_t buflen; - const struct sockaddr *addr; - socklen_t addrlen; -}; - -static VALUE tfo_sendto(void *_a) -{ - struct tfo_args *a = _a; - ssize_t w; - - w = sendto(a->fd, a->buf, a->buflen, MSG_FASTOPEN, a->addr, a->addrlen); - return (VALUE)w; -} - -/* - * call-seq: - * - * s = Kgio::Socket.new(:INET, :STREAM) - * addr = Socket.pack_sockaddr_in(80, "example.com") - * s.kgio_fastopen("hello world", addr) -> nil - * - * Starts a TCP connection using TCP Fast Open. This uses a blocking - * sendto() syscall and is only available on Ruby 1.9 or later. - * This raises exceptions (including Errno::EINPROGRESS/Errno::EAGAIN) - * on errors. Using this is only recommended for blocking sockets. - * - * Timeouts may be set with setsockopt: - * - * s.setsockopt(:SOCKET, :SNDTIMEO, [1,0].pack("l_l_")) - */ -static VALUE fastopen(VALUE sock, VALUE buf, VALUE addr) -{ - struct tfo_args a; - VALUE str = (TYPE(buf) == T_STRING) ? buf : rb_obj_as_string(buf); - ssize_t w; - - a.fd = my_fileno(sock); - a.buf = RSTRING_PTR(str); - a.buflen = (size_t)RSTRING_LEN(str); - a.addr = sockaddr_from(&a.addrlen, addr); - - /* n.b. rb_thread_blocking_region preserves errno */ - w = (ssize_t)rb_thread_io_blocking_region(tfo_sendto, &a, a.fd); - if (w < 0) - rb_sys_fail("sendto"); - if ((size_t)w == a.buflen) - return Qnil; - - return rb_str_subseq(str, w, a.buflen - w); -} -#endif /* MSG_FASTOPEN */ - -/* - * call-seq: - * - * Kgio::TCPSocket.new('127.0.0.1', 80) -> socket - * - * Creates a new Kgio::TCPSocket object and initiates a - * non-blocking connection. - * - * This may block and call any method defined to +kgio_wait_writable+ - * for the class. - * - * Unlike the TCPSocket.new in Ruby, this does NOT perform DNS - * lookups (which is subject to a different set of timeouts and - * best handled elsewhere). - */ -static VALUE kgio_tcp_connect(VALUE klass, VALUE ip, VALUE port) -{ - return tcp_connect(klass, ip, port, 1); -} - -/* - * call-seq: - * - * Kgio::TCPSocket.start('127.0.0.1', 80) -> socket - * - * Creates a new Kgio::TCPSocket object and initiates a - * non-blocking connection. The caller should select/poll - * on the socket for writability before attempting to write - * or optimistically attempt a write and handle :wait_writable - * or Errno::EAGAIN. - * - * Unlike the TCPSocket.new in Ruby, this does NOT perform DNS - * lookups (which is subject to a different set of timeouts and - * best handled elsewhere). - */ -static VALUE kgio_tcp_start(VALUE klass, VALUE ip, VALUE port) -{ - return tcp_connect(klass, ip, port, 0); -} - -static VALUE unix_connect(VALUE klass, VALUE path, int io_wait) -{ - struct sockaddr_un addr = { 0 }; - long len; - - StringValue(path); - len = RSTRING_LEN(path); - if ((long)sizeof(addr.sun_path) <= len) - rb_raise(rb_eArgError, - "too long unix socket path (max: %dbytes)", - (int)sizeof(addr.sun_path)-1); - - memcpy(addr.sun_path, RSTRING_PTR(path), len); - addr.sun_family = AF_UNIX; - - return my_connect(klass, io_wait, PF_UNIX, &addr, sizeof(addr)); -} - -/* - * call-seq: - * - * Kgio::UNIXSocket.new("/path/to/unix/socket") -> socket - * - * Creates a new Kgio::UNIXSocket object and initiates a - * non-blocking connection. - * - * This may block and call any method defined to +kgio_wait_writable+ - * for the class. - */ -static VALUE kgio_unix_connect(VALUE klass, VALUE path) -{ - return unix_connect(klass, path, 1); -} - -/* - * call-seq: - * - * Kgio::UNIXSocket.start("/path/to/unix/socket") -> socket - * - * Creates a new Kgio::UNIXSocket object and initiates a - * non-blocking connection. The caller should select/poll - * on the socket for writability before attempting to write - * or optimistically attempt a write and handle :wait_writable - * or Errno::EAGAIN. - */ -static VALUE kgio_unix_start(VALUE klass, VALUE path) -{ - return unix_connect(klass, path, 0); -} - -static VALUE stream_connect(VALUE klass, VALUE addr, int io_wait) -{ - int domain; - socklen_t addrlen; - const struct sockaddr *sockaddr = sockaddr_from(&addrlen, addr); - - switch (((const struct sockaddr_storage *)(sockaddr))->ss_family) { - case AF_UNIX: domain = PF_UNIX; break; - case AF_INET: domain = PF_INET; break; - case AF_INET6: domain = PF_INET6; break; - default: - rb_raise(rb_eArgError, "invalid address family"); - } - - return my_connect(klass, io_wait, domain, sockaddr, addrlen); -} - -/* call-seq: - * - * addr = Socket.pack_sockaddr_in(80, 'example.com') - * Kgio::Socket.connect(addr) -> socket - * - * addr = Socket.pack_sockaddr_un("/path/to/unix/socket") - * Kgio::Socket.connect(addr) -> socket - * - * Creates a generic Kgio::Socket object and initiates a - * non-blocking connection. - * - * This may block and call any method defined to +kgio_wait_writable+ - * for the class. - */ -static VALUE kgio_connect(VALUE klass, VALUE addr) -{ - return stream_connect(klass, addr, 1); -} - -/* - * If passed one argument, this is identical to Kgio::Socket.connect. - * If passed two or three arguments, it uses its superclass method: - * - * Socket.new(domain, socktype [, protocol ]) - */ -static VALUE kgio_new(int argc, VALUE *argv, VALUE klass) -{ - if (argc == 1) - /* backwards compat, the only way for kgio <= 2.7.4 */ - return stream_connect(klass, argv[0], 1); - - return rb_call_super(argc, argv); -} - -/* call-seq: - * - * addr = Socket.pack_sockaddr_in(80, 'example.com') - * Kgio::Socket.start(addr) -> socket - * - * addr = Socket.pack_sockaddr_un("/path/to/unix/socket") - * Kgio::Socket.start(addr) -> socket - * - * Creates a generic Kgio::Socket object and initiates a - * non-blocking connection. The caller should select/poll - * on the socket for writability before attempting to write - * or optimistically attempt a write and handle :wait_writable - * or Errno::EAGAIN. - */ -static VALUE kgio_start(VALUE klass, VALUE addr) -{ - return stream_connect(klass, addr, 0); -} - -void init_kgio_connect(void) -{ - VALUE mKgio = rb_define_module("Kgio"); - VALUE cSocket = rb_const_get(rb_cObject, rb_intern("Socket")); - VALUE mSocketMethods = rb_const_get(mKgio, rb_intern("SocketMethods")); - VALUE cKgio_Socket, cTCPSocket, cUNIXSocket; - - /* - * Document-class: Kgio::Socket - * - * A generic socket class with Kgio::SocketMethods included. - * This is returned by all Kgio methods that accept(2) a connected - * stream socket. - */ - cKgio_Socket = rb_define_class_under(mKgio, "Socket", cSocket); - rb_include_module(cKgio_Socket, mSocketMethods); - rb_define_singleton_method(cKgio_Socket, "new", kgio_new, -1); - rb_define_singleton_method(cKgio_Socket, "connect", kgio_connect, 1); - rb_define_singleton_method(cKgio_Socket, "start", kgio_start, 1); -#if defined(MSG_FASTOPEN) && defined(KGIO_WITHOUT_GVL) - rb_define_method(cKgio_Socket, "kgio_fastopen", fastopen, 2); -#endif - /* - * Document-class: Kgio::TCPSocket - * - * Kgio::TCPSocket should be used in place of the plain TCPSocket - * when kgio_* methods are needed. - */ - cTCPSocket = rb_const_get(rb_cObject, rb_intern("TCPSocket")); - cTCPSocket = rb_define_class_under(mKgio, "TCPSocket", cTCPSocket); - rb_include_module(cTCPSocket, mSocketMethods); - rb_define_singleton_method(cTCPSocket, "new", kgio_tcp_connect, 2); - rb_define_singleton_method(cTCPSocket, "start", kgio_tcp_start, 2); - - /* - * Document-class: Kgio::UNIXSocket - * - * Kgio::UNIXSocket should be used in place of the plain UNIXSocket - * when kgio_* methods are needed. - */ - cUNIXSocket = rb_const_get(rb_cObject, rb_intern("UNIXSocket")); - cUNIXSocket = rb_define_class_under(mKgio, "UNIXSocket", cUNIXSocket); - rb_include_module(cUNIXSocket, mSocketMethods); - rb_define_singleton_method(cUNIXSocket, "new", kgio_unix_connect, 1); - rb_define_singleton_method(cUNIXSocket, "start", kgio_unix_start, 1); - init_sock_for_fd(); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/extconf.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/extconf.rb deleted file mode 100644 index 44888dd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/extconf.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'mkmf' -$CPPFLAGS << ' -D_GNU_SOURCE' -$CPPFLAGS << ' -DPOSIX_C_SOURCE=1' -$CPPFLAGS += '-D_POSIX_C_SOURCE=200112L' -unless have_macro('CLOCK_MONOTONIC', 'time.h') - have_func('CLOCK_MONOTONIC', 'time.h') -end -have_type('clockid_t', 'time.h') -have_library('rt', 'clock_gettime', 'time.h') - -# taken from ext/socket/extconf.rb in ruby/trunk: -# OpenSolaris: -have_library("nsl", "t_open") -have_library("socket", "socket") - -have_func("poll", "poll.h") -have_func("getaddrinfo", %w(sys/types.h sys/socket.h netdb.h)) or - abort "getaddrinfo required" -have_func("getnameinfo", %w(sys/types.h sys/socket.h netdb.h)) or - abort "getnameinfo required" -have_type("struct sockaddr_storage", %w(sys/types.h sys/socket.h)) or - abort "struct sockaddr_storage required" -have_func('accept4', %w(sys/socket.h)) -have_header("sys/select.h") - -have_func("writev", "sys/uio.h") - -if have_header('ruby/io.h') - rubyio = %w(ruby.h ruby/io.h) - have_struct_member("rb_io_t", "fd", rubyio) - have_struct_member("rb_io_t", "mode", rubyio) - have_struct_member("rb_io_t", "pathv", rubyio) -else - rubyio = %w(ruby.h rubyio.h) - rb_io_t = have_type("OpenFile", rubyio) ? "OpenFile" : "rb_io_t" - have_struct_member(rb_io_t, "f", rubyio) - have_struct_member(rb_io_t, "f2", rubyio) - have_struct_member(rb_io_t, "mode", rubyio) - have_struct_member(rb_io_t, "path", rubyio) - have_func('rb_fdopen') -end -have_type("struct RFile", rubyio) and check_sizeof("struct RFile", rubyio) -have_type("struct RObject") and check_sizeof("struct RObject") -check_sizeof("int") -have_func('rb_io_ascii8bit_binmode') -have_func('rb_update_max_fd') -have_func('rb_fd_fix_cloexec') -have_func('rb_cloexec_open') -have_header('ruby/thread.h') -have_func('rb_thread_call_without_gvl', %w{ruby/thread.h}) -have_func('rb_thread_blocking_region') -have_func('rb_thread_io_blocking_region') -have_func('rb_str_set_len') -have_func('rb_time_interval') -have_func('rb_wait_for_single_fd') -have_func('rb_str_subseq') -have_func('rb_ary_subseq') - -create_makefile('kgio_ext') diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio.h deleted file mode 100644 index 7c992fb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio.h +++ /dev/null @@ -1,105 +0,0 @@ -#ifndef KGIO_H -#define KGIO_H - -#include -#ifdef HAVE_RUBY_IO_H -# include -#else -# include -#endif -#ifdef HAVE_RUBY_THREAD_H -# include -#endif -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "ancient_ruby.h" - -void init_kgio_wait(void); -void init_kgio_read(void); -void init_kgio_write(void); -void init_kgio_writev(void); -void init_kgio_accept(void); -void init_kgio_connect(void); -void init_kgio_autopush(void); -void init_kgio_poll(void); -void init_kgio_tryopen(void); - -void kgio_autopush_accept(VALUE, VALUE); -void kgio_autopush_recv(VALUE); -void kgio_autopush_send(VALUE); - -VALUE kgio_call_wait_writable(VALUE io); -VALUE kgio_call_wait_readable(VALUE io); -#if defined(HAVE_RB_THREAD_CALL_WITHOUT_GVL) && defined(HAVE_RUBY_THREAD_H) -# define KGIO_WITHOUT_GVL(fn,data1,ubf,data2) \ - rb_thread_call_without_gvl((fn),(data1),(ubf),(data2)) -#elif defined(HAVE_RB_THREAD_BLOCKING_REGION) -typedef VALUE(*kgio_blocking_fn_t)(void*); -# define KGIO_WITHOUT_GVL(fn,data1,ubf,data2) \ - rb_thread_blocking_region((kgio_blocking_fn_t)(fn),(data1),(ubf),(data2)) -#endif /* HAVE_RB_THREAD_CALL_WITHOUT_GVL || HAVE_RB_THREAD_BLOCKING_REGION */ - -#if defined(KGIO_WITHOUT_GVL) && defined(HAVE_POLL) -# define USE_KGIO_POLL -#endif /* USE_KGIO_POLL */ - -#ifndef HAVE_RB_UPDATE_MAX_FD -# define rb_update_max_fd(fd) for (;0;) -#endif - -/* - * 2012/12/13 - Linux 3.7 was released on 2012/12/10 with TFO. - * Headers distributed with glibc will take some time to catch up and - * be officially released. Most GNU/Linux distros will take a few months - * to a year longer. "Enterprise" distros will probably take 5-7 years. - * So keep these until 2017 at least... - */ -#ifdef __linux__ -# ifndef MSG_FASTOPEN -# define MSG_FASTOPEN 0x20000000 /* for clients */ -# endif -# ifndef TCP_FASTOPEN -# define TCP_FASTOPEN 23 /* for listeners */ -# endif - /* we _may_ have TFO support */ -# define KGIO_TFO_MAYBE (1) -#else /* rely entirely on standard system headers */ -# define KGIO_TFO_MAYBE (0) -#endif - -extern unsigned kgio_tfo; -NORETURN(void kgio_raise_empty_bt(VALUE, const char *)); -NORETURN(void kgio_wr_sys_fail(const char *)); -NORETURN(void kgio_rd_sys_fail(const char *)); - -/* - * we know MSG_DONTWAIT works properly on all stream sockets under Linux - * we can define this macro for other platforms as people care and - * notice. - */ -# if defined(__linux__) -# define USE_MSG_DONTWAIT -# endif - -#ifdef USE_MSG_DONTWAIT -/* we don't need these variants, we call kgio_autopush_send/recv directly */ -static inline void kgio_autopush_write(VALUE io) { } -#else -static inline void kgio_autopush_write(VALUE io) { kgio_autopush_send(io); } -#endif - -/* prefer rb_str_subseq because we don't use negative offsets */ -#ifndef HAVE_RB_STR_SUBSEQ -#define rb_str_subseq rb_str_substr -#endif - -#endif /* KGIO_H */ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio_ext.bundle b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio_ext.bundle deleted file mode 100755 index 48342ab..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio_ext.bundle and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio_ext.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio_ext.c deleted file mode 100644 index 8829eae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/kgio_ext.c +++ /dev/null @@ -1,101 +0,0 @@ -#include "kgio.h" -#include -#include -/* true if TCP Fast Open is usable */ -unsigned kgio_tfo; -static VALUE eErrno_EPIPE, eErrno_ECONNRESET; -static ID id_set_backtrace; - -static void tfo_maybe(void) -{ - VALUE mKgio = rb_define_module("Kgio"); - - /* Deal with the case where system headers have not caught up */ - if (KGIO_TFO_MAYBE) { - /* Ensure Linux 3.7 or later for TCP_FASTOPEN */ - struct utsname buf; - unsigned maj, min; - - if (uname(&buf) != 0) - rb_sys_fail("uname"); - if (sscanf(buf.release, "%u.%u", &maj, &min) != 2) - return; - if (maj < 3 || (maj == 3 && min < 7)) - return; - } - - /* - * KGIO_TFO_MAYBE will be false if a distro backports TFO - * to a pre-3.7 kernel, but includes the necessary constants - * in system headers - */ -#if defined(MSG_FASTOPEN) && defined(TCP_FASTOPEN) - rb_define_const(mKgio, "TCP_FASTOPEN", INT2NUM(TCP_FASTOPEN)); - rb_define_const(mKgio, "MSG_FASTOPEN", INT2NUM(MSG_FASTOPEN)); - kgio_tfo = 1; -#endif -} - -void kgio_raise_empty_bt(VALUE err, const char *msg) -{ - VALUE exc = rb_exc_new2(err, msg); - VALUE bt = rb_ary_new(); - - rb_funcall(exc, id_set_backtrace, 1, bt); - rb_exc_raise(exc); -} - -void kgio_wr_sys_fail(const char *msg) -{ - switch (errno) { - case EPIPE: - errno = 0; - kgio_raise_empty_bt(eErrno_EPIPE, msg); - case ECONNRESET: - errno = 0; - kgio_raise_empty_bt(eErrno_ECONNRESET, msg); - } - rb_sys_fail(msg); -} - -void kgio_rd_sys_fail(const char *msg) -{ - if (errno == ECONNRESET) { - errno = 0; - kgio_raise_empty_bt(eErrno_ECONNRESET, msg); - } - rb_sys_fail(msg); -} - -void Init_kgio_ext(void) -{ - VALUE mKgio = rb_define_module("Kgio"); - VALUE mPipeMethods = rb_define_module_under(mKgio, "PipeMethods"); - VALUE mSocketMethods = rb_define_module_under(mKgio, "SocketMethods"); - VALUE mWaiters = rb_define_module_under(mKgio, "DefaultWaiters"); - - id_set_backtrace = rb_intern("set_backtrace"); - eErrno_EPIPE = rb_const_get(rb_mErrno, rb_intern("EPIPE")); - eErrno_ECONNRESET = rb_const_get(rb_mErrno, rb_intern("ECONNRESET")); - - /* - * Returns the client IP address of the socket as a string - * (e.g. "127.0.0.1" or "::1"). - * This is always the value of the Kgio::LOCALHOST constant - * for UNIX domain sockets. - */ - rb_define_attr(mSocketMethods, "kgio_addr", 1, 1); - rb_include_module(mPipeMethods, mWaiters); - rb_include_module(mSocketMethods, mWaiters); - - tfo_maybe(); - init_kgio_wait(); - init_kgio_read(); - init_kgio_write(); - init_kgio_writev(); - init_kgio_connect(); - init_kgio_accept(); - init_kgio_autopush(); - init_kgio_poll(); - init_kgio_tryopen(); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/missing_accept4.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/missing_accept4.h deleted file mode 100644 index 3e9ec67..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/missing_accept4.h +++ /dev/null @@ -1,59 +0,0 @@ -#if !defined(HAVE_ACCEPT4) || !defined(SOCK_CLOEXEC) || !defined(SOCK_NONBLOCK) -# ifndef _GNU_SOURCE -# define _GNU_SOURCE -# endif -# include -# include -# ifndef SOCK_CLOEXEC -# if (02000000 == O_NONBLOCK) -# define SOCK_CLOEXEC 1 -# define SOCK_NONBLOCK 2 -# else -# define SOCK_CLOEXEC 02000000 -# define SOCK_NONBLOCK O_NONBLOCK -# endif -# endif -#endif /* !HAVE_ACCEPT4 */ - -/* accept4() is currently a Linux-only goodie */ -static int -my_accept4(int sockfd, struct sockaddr *addr, socklen_t *addrlen, int flags) -{ - int fd = accept(sockfd, addr, addrlen); - - if (fd >= 0) { - if ((flags & SOCK_CLOEXEC) == SOCK_CLOEXEC) - (void)fcntl(fd, F_SETFD, FD_CLOEXEC); - - /* - * Some systems inherit O_NONBLOCK across accept(). - * We also expect our users to use MSG_DONTWAIT under - * Linux, so fcntl() is completely unnecessary - * in most cases... - */ - if ((flags & SOCK_NONBLOCK) == SOCK_NONBLOCK) { - int fl = fcntl(fd, F_GETFL); - - /* - * unconditional, OSX 10.4 (and maybe other *BSDs) - * F_GETFL returns a false O_NONBLOCK with TCP sockets - * (but not UNIX sockets) [ruby-talk:274079] - */ - (void)fcntl(fd, F_SETFL, fl | O_NONBLOCK); - } - - /* - * nothing we can do about fcntl() errors in this wrapper - * function, let the user (Ruby) code figure it out - */ - errno = 0; - } - return fd; -} - -typedef int accept_fn_t(int, struct sockaddr *, socklen_t *, int); -#ifdef HAVE_ACCEPT4 -static accept_fn_t *accept_fn = accept4; -#else -static accept_fn_t *accept_fn = my_accept4; -#endif diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/my_fileno.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/my_fileno.h deleted file mode 100644 index bdf1a5f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/my_fileno.h +++ /dev/null @@ -1,36 +0,0 @@ -#include -#ifdef HAVE_RUBY_IO_H -# include -#else -# include -# include -#endif - -#if ! HAVE_RB_IO_T -# define rb_io_t OpenFile -#endif - -#ifdef GetReadFile -# define FPTR_TO_FD(fptr) (fileno(GetReadFile(fptr))) -#else -# if !HAVE_RB_IO_T || (RUBY_VERSION_MAJOR == 1 && RUBY_VERSION_MINOR == 8) -# define FPTR_TO_FD(fptr) fileno(fptr->f) -# else -# define FPTR_TO_FD(fptr) fptr->fd -# endif -#endif - -static int my_fileno(VALUE io) -{ - rb_io_t *fptr; - int fd; - - if (TYPE(io) != T_FILE) - io = rb_convert_type(io, T_FILE, "IO", "to_io"); - GetOpenFile(io, fptr); - fd = FPTR_TO_FD(fptr); - - if (fd < 0) - rb_raise(rb_eIOError, "closed stream"); - return fd; -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/nonblock.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/nonblock.h deleted file mode 100644 index 2d9a13a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/nonblock.h +++ /dev/null @@ -1,19 +0,0 @@ -#include -#include -#include -static void set_nonblocking(int fd) -{ - int flags = fcntl(fd, F_GETFL); - - /* - * do not check < 0 here, one day we may have enough FD flags - * to require negative bit - */ - if (flags == -1) - rb_sys_fail("fcntl(F_GETFL)"); - if ((flags & O_NONBLOCK) == O_NONBLOCK) - return; - flags = fcntl(fd, F_SETFL, flags | O_NONBLOCK); - if (flags < 0) - rb_sys_fail("fcntl(F_SETFL)"); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/poll.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/poll.c deleted file mode 100644 index 41bebf6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/poll.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kgio.h" -#if defined(USE_KGIO_POLL) -#include "my_fileno.h" -#include -#include "broken_system_compat.h" -#include -#include -#ifdef HAVE_RUBY_ST_H -# include -#else -# include -#endif - -static VALUE sym_wait_readable, sym_wait_writable; -static ID id_clear; - -struct poll_args { - struct pollfd *fds; - nfds_t nfds; - int timeout; - VALUE ios; - st_table *fd_to_io; - struct timespec start; -}; - -static int interrupted(void) -{ - switch (errno) { - case EINTR: -#ifdef ERESTART - case ERESTART: -#endif - return 1; - } - return 0; -} - -static int retryable(struct poll_args *a) -{ - struct timespec ts; - - if (a->timeout < 0) - return 1; - - clock_gettime(hopefully_CLOCK_MONOTONIC, &ts); - - ts.tv_sec -= a->start.tv_sec; - ts.tv_nsec -= a->start.tv_nsec; - if (ts.tv_nsec < 0) { - ts.tv_sec--; - ts.tv_nsec += 1000000000; - } - a->timeout -= ts.tv_sec * 1000; - a->timeout -= ts.tv_nsec / 1000000; - if (a->timeout < 0) - a->timeout = 0; - return 1; -} - -static int num2timeout(VALUE timeout) -{ - switch (TYPE(timeout)) { - case T_NIL: return -1; - case T_FIXNUM: return FIX2INT(timeout); - case T_BIGNUM: return NUM2INT(timeout); - } - rb_raise(rb_eTypeError, "timeout must be integer or nil"); - return 0; -} - -static VALUE poll_free(VALUE args) -{ - struct poll_args *a = (struct poll_args *)args; - - if (a->fds) - xfree(a->fds); - if (a->fd_to_io) - st_free_table(a->fd_to_io); - - return Qnil; -} - -static short value2events(VALUE event) -{ - if (event == sym_wait_readable) return POLLIN; - if (event == sym_wait_writable) return POLLOUT; - if (TYPE(event) == T_FIXNUM) return (short)FIX2INT(event); - rb_raise(rb_eArgError, "unrecognized event"); -} - -static int io_to_pollfd_i(VALUE key, VALUE value, VALUE args) -{ - struct poll_args *a = (struct poll_args *)args; - struct pollfd *pollfd = &a->fds[a->nfds++]; - - pollfd->fd = my_fileno(key); - pollfd->events = value2events(value); - st_insert(a->fd_to_io, (st_data_t)pollfd->fd, (st_data_t)key); - return ST_CONTINUE; -} - -static void hash2pollfds(struct poll_args *a) -{ - a->nfds = 0; - a->fds = xmalloc(sizeof(struct pollfd) * RHASH_SIZE(a->ios)); - a->fd_to_io = st_init_numtable(); - rb_hash_foreach(a->ios, io_to_pollfd_i, (VALUE)a); -} - -static void * nogvl_poll(void *ptr) -{ - struct poll_args *a = ptr; - long n; - - if (a->timeout > 0) - clock_gettime(hopefully_CLOCK_MONOTONIC, &a->start); - - n = poll(a->fds, a->nfds, a->timeout); - return (void *)n; -} - -static VALUE poll_result(int nr, struct poll_args *a) -{ - struct pollfd *fds = a->fds; - VALUE io; - int rc; - - if ((nfds_t)nr != a->nfds) - rb_funcall(a->ios, id_clear, 0); - for (; nr > 0; fds++) { - if (fds->revents == 0) - continue; - --nr; - rc = st_lookup(a->fd_to_io, (st_data_t)fds->fd, &io); - assert(rc == 1 && "fd => IO mapping failed"); - rb_hash_aset(a->ios, io, INT2FIX((int)fds->revents)); - } - return a->ios; -} - -static VALUE do_poll(VALUE args) -{ - struct poll_args *a = (struct poll_args *)args; - long nr; - - Check_Type(a->ios, T_HASH); - -retry: - hash2pollfds(a); - nr = (long)KGIO_WITHOUT_GVL(nogvl_poll, a, RUBY_UBF_IO, NULL); - if (nr < 0) { - if (interrupted()) { - if (retryable(a)) { - poll_free(args); - goto retry; - } - return Qnil; - } - rb_sys_fail("poll"); - } - if (nr == 0) return Qnil; - - return poll_result(nr, a); -} - -/* - * call-seq: - * - * Kgio.poll({ $stdin => :wait_readable }, 100) -> hash or nil - * Kgio.poll({ $stdin => Kgio::POLLIN }, 100) -> hash or nil - * - * Accepts an input hash with IO objects to wait for as the key and - * the events to wait for as its value. The events may either be - * +:wait_readable+ or +:wait_writable+ symbols or a Fixnum mask of - * Kgio::POLL* constants: - * - * Kgio::POLLIN - there is data to read - * Kgio::POLLPRI - there is urgent data to read - * Kgio::POLLOUT - writing will not block - * Kgio::POLLRDHUP - peer has shutdown writes (Linux 2.6.17+ only) - * - * Timeout is specified in Integer milliseconds just like the underlying - * poll(2), not in seconds like IO.select. A nil timeout means to wait - * forever. It must be an Integer or nil. - * - * Kgio.poll modifies and returns its input hash on success with the - * IO-like object as the key and an Integer mask of events as the hash - * value. It can return any of the events specified in the input - * above, along with the following events: - * - * Kgio::POLLERR - error condition occurred on the descriptor - * Kgio::POLLHUP - hang up - * Kgio::POLLNVAL - invalid request (bad file descriptor) - * - * This method is only available under Ruby 1.9 or any other - * implementations that uses native threads and rb_thread_blocking_region() - */ -static VALUE s_poll(int argc, VALUE *argv, VALUE self) -{ - VALUE timeout; - struct poll_args a; - - rb_scan_args(argc, argv, "11", &a.ios, &timeout); - a.timeout = num2timeout(timeout); - a.fds = NULL; - a.fd_to_io = NULL; - - return rb_ensure(do_poll, (VALUE)&a, poll_free, (VALUE)&a); -} - -void init_kgio_poll(void) -{ - VALUE mKgio = rb_define_module("Kgio"); - - if (check_clock() < 0) - return; - rb_define_singleton_method(mKgio, "poll", s_poll, -1); - - sym_wait_readable = ID2SYM(rb_intern("wait_readable")); - sym_wait_writable = ID2SYM(rb_intern("wait_writable")); - id_clear = rb_intern("clear"); - -#define c(x) rb_define_const(mKgio,#x,INT2NUM((int)x)) - -/* standard types */ - - c(POLLIN); - c(POLLPRI); - c(POLLOUT); - -#ifdef POLLRDHUP - c(POLLRDHUP); -#endif - -/* outputs */ - c(POLLERR); - c(POLLHUP); - c(POLLNVAL); -} -#else /* ! USE_KGIO_POLL */ -void init_kgio_poll(void) -{ -} -#endif /* ! USE_KGIO_POLL */ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/read.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/read.c deleted file mode 100644 index 472a592..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/read.c +++ /dev/null @@ -1,328 +0,0 @@ -/* ref: rubinius b2811f260de16d1e972462e27852470364608de5 */ -#define RSTRING_MODIFIED 1 -#include "kgio.h" -#include "my_fileno.h" -#include "nonblock.h" -static VALUE sym_wait_readable; - -#ifdef USE_MSG_DONTWAIT -static const int peek_flags = MSG_DONTWAIT|MSG_PEEK; - -/* we don't need these variants, we call kgio_autopush_recv directly */ -static inline void kgio_autopush_read(VALUE io) { } - -#else -static const int peek_flags = MSG_PEEK; -static inline void kgio_autopush_read(VALUE io) { kgio_autopush_recv(io); } -#endif - -struct rd_args { - VALUE io; - VALUE buf; - char *ptr; - long len; - int fd; -}; - -NORETURN(static void my_eof_error(void)); - -static void my_eof_error(void) -{ - kgio_raise_empty_bt(rb_eEOFError, "end of file reached"); -} - -static void prepare_read(struct rd_args *a, int argc, VALUE *argv, VALUE io) -{ - VALUE length; - - a->io = io; - a->fd = my_fileno(io); - rb_scan_args(argc, argv, "11", &length, &a->buf); - a->len = NUM2LONG(length); - if (NIL_P(a->buf)) { - a->buf = rb_str_new(NULL, a->len); - } else { - StringValue(a->buf); - rb_str_modify(a->buf); - rb_str_resize(a->buf, a->len); - } - a->ptr = RSTRING_PTR(a->buf); -} - -static int read_check(struct rd_args *a, long n, const char *msg, int io_wait) -{ - if (n < 0) { - if (errno == EINTR) { - a->fd = my_fileno(a->io); - return -1; - } - rb_str_set_len(a->buf, 0); - if (errno == EAGAIN) { - if (io_wait) { - (void)kgio_call_wait_readable(a->io); - - /* buf may be modified in other thread/fiber */ - rb_str_modify(a->buf); - rb_str_resize(a->buf, a->len); - a->ptr = RSTRING_PTR(a->buf); - return -1; - } else { - a->buf = sym_wait_readable; - return 0; - } - } - kgio_rd_sys_fail(msg); - } - rb_str_set_len(a->buf, n); - if (n == 0) - a->buf = Qnil; - return 0; -} - -static VALUE my_read(int io_wait, int argc, VALUE *argv, VALUE io) -{ - struct rd_args a; - long n; - - prepare_read(&a, argc, argv, io); - kgio_autopush_read(io); - - if (a.len > 0) { - set_nonblocking(a.fd); -retry: - n = (long)read(a.fd, a.ptr, a.len); - if (read_check(&a, n, "read", io_wait) != 0) - goto retry; - } - return a.buf; -} - -/* - * call-seq: - * - * io.kgio_read(maxlen) -> buffer - * io.kgio_read(maxlen, buffer) -> buffer - * - * Reads at most maxlen bytes from the stream socket. Returns with a - * newly allocated buffer, or may reuse an existing buffer if supplied. - * - * This may block and call any method defined to +kgio_wait_readable+ - * for the class. - * - * Returns nil on EOF. - * - * This behaves like read(2) and IO#readpartial, NOT fread(3) or - * IO#read which possess read-in-full behavior. - */ -static VALUE kgio_read(int argc, VALUE *argv, VALUE io) -{ - return my_read(1, argc, argv, io); -} - -/* - * Same as Kgio::PipeMethods#kgio_read, except EOFError is raised - * on EOF without a backtrace. This method is intended as a - * drop-in replacement for places where IO#readpartial is used, and - * may be aliased as such. - */ -static VALUE kgio_read_bang(int argc, VALUE *argv, VALUE io) -{ - VALUE rv = my_read(1, argc, argv, io); - - if (NIL_P(rv)) my_eof_error(); - return rv; -} - -/* - * call-seq: - * - * io.kgio_tryread(maxlen) -> buffer - * io.kgio_tryread(maxlen, buffer) -> buffer - * - * Reads at most maxlen bytes from the stream socket. Returns with a - * newly allocated buffer, or may reuse an existing buffer if supplied. - * - * Returns nil on EOF. - * - * Returns :wait_readable if EAGAIN is encountered. - */ -static VALUE kgio_tryread(int argc, VALUE *argv, VALUE io) -{ - return my_read(0, argc, argv, io); -} - -#ifdef USE_MSG_DONTWAIT -static VALUE my_recv(int io_wait, int argc, VALUE *argv, VALUE io) -{ - struct rd_args a; - long n; - - prepare_read(&a, argc, argv, io); - kgio_autopush_recv(io); - - if (a.len > 0) { -retry: - n = (long)recv(a.fd, a.ptr, a.len, MSG_DONTWAIT); - if (read_check(&a, n, "recv", io_wait) != 0) - goto retry; - } - return a.buf; -} - -/* - * This method may be optimized on some systems (e.g. GNU/Linux) to use - * MSG_DONTWAIT to avoid explicitly setting the O_NONBLOCK flag via fcntl. - * Otherwise this is the same as Kgio::PipeMethods#kgio_read - */ -static VALUE kgio_recv(int argc, VALUE *argv, VALUE io) -{ - return my_recv(1, argc, argv, io); -} - -/* - * Same as Kgio::SocketMethods#kgio_read, except EOFError is raised - * on EOF without a backtrace - */ -static VALUE kgio_recv_bang(int argc, VALUE *argv, VALUE io) -{ - VALUE rv = my_recv(1, argc, argv, io); - - if (NIL_P(rv)) my_eof_error(); - return rv; -} - -/* - * This method may be optimized on some systems (e.g. GNU/Linux) to use - * MSG_DONTWAIT to avoid explicitly setting the O_NONBLOCK flag via fcntl. - * Otherwise this is the same as Kgio::PipeMethods#kgio_tryread - */ -static VALUE kgio_tryrecv(int argc, VALUE *argv, VALUE io) -{ - return my_recv(0, argc, argv, io); -} -#else /* ! USE_MSG_DONTWAIT */ -# define kgio_recv kgio_read -# define kgio_recv_bang kgio_read_bang -# define kgio_tryrecv kgio_tryread -#endif /* USE_MSG_DONTWAIT */ - -static VALUE my_peek(int io_wait, int argc, VALUE *argv, VALUE io) -{ - struct rd_args a; - long n; - - prepare_read(&a, argc, argv, io); - kgio_autopush_recv(io); - - if (a.len > 0) { - if (peek_flags == MSG_PEEK) - set_nonblocking(a.fd); -retry: - n = (long)recv(a.fd, a.ptr, a.len, peek_flags); - if (read_check(&a, n, "recv(MSG_PEEK)", io_wait) != 0) - goto retry; - } - return a.buf; -} - -/* - * call-seq: - * - * socket.kgio_trypeek(maxlen) -> buffer - * socket.kgio_trypeek(maxlen, buffer) -> buffer - * - * Like kgio_tryread, except it uses MSG_PEEK so it does not drain the - * socket buffer. A subsequent read of any type (including another peek) - * will return the same data. - */ -static VALUE kgio_trypeek(int argc, VALUE *argv, VALUE io) -{ - return my_peek(0, argc, argv, io); -} - -/* - * call-seq: - * - * socket.kgio_peek(maxlen) -> buffer - * socket.kgio_peek(maxlen, buffer) -> buffer - * - * Like kgio_read, except it uses MSG_PEEK so it does not drain the - * socket buffer. A subsequent read of any type (including another peek) - * will return the same data. - */ -static VALUE kgio_peek(int argc, VALUE *argv, VALUE io) -{ - return my_peek(1, argc, argv, io); -} - -/* - * call-seq: - * - * Kgio.trypeek(socket, maxlen) -> buffer - * Kgio.trypeek(socket, maxlen, buffer) -> buffer - * - * Like Kgio.tryread, except it uses MSG_PEEK so it does not drain the - * socket buffer. This can only be used on sockets and not pipe objects. - * Maybe used in place of SocketMethods#kgio_trypeek for non-Kgio objects - */ -static VALUE s_trypeek(int argc, VALUE *argv, VALUE mod) -{ - if (argc <= 1) - rb_raise(rb_eArgError, "wrong number of arguments"); - return my_peek(0, argc - 1, &argv[1], argv[0]); -} - -/* - * call-seq: - * - * Kgio.tryread(io, maxlen) -> buffer - * Kgio.tryread(io, maxlen, buffer) -> buffer - * - * Returns nil on EOF. - * Returns :wait_readable if EAGAIN is encountered. - * - * Maybe used in place of PipeMethods#kgio_tryread for non-Kgio objects - */ -static VALUE s_tryread(int argc, VALUE *argv, VALUE mod) -{ - if (argc <= 1) - rb_raise(rb_eArgError, "wrong number of arguments"); - return my_read(0, argc - 1, &argv[1], argv[0]); -} - -void init_kgio_read(void) -{ - VALUE mPipeMethods, mSocketMethods; - VALUE mKgio = rb_define_module("Kgio"); - - sym_wait_readable = ID2SYM(rb_intern("wait_readable")); - - rb_define_singleton_method(mKgio, "tryread", s_tryread, -1); - rb_define_singleton_method(mKgio, "trypeek", s_trypeek, -1); - - /* - * Document-module: Kgio::PipeMethods - * - * This module may be used used to create classes that respond to - * various Kgio methods for reading and writing. This is included - * in Kgio::Pipe by default. - */ - mPipeMethods = rb_define_module_under(mKgio, "PipeMethods"); - rb_define_method(mPipeMethods, "kgio_read", kgio_read, -1); - rb_define_method(mPipeMethods, "kgio_read!", kgio_read_bang, -1); - rb_define_method(mPipeMethods, "kgio_tryread", kgio_tryread, -1); - - /* - * Document-module: Kgio::SocketMethods - * - * This method behaves like Kgio::PipeMethods, but contains - * optimizations for sockets on certain operating systems - * (e.g. GNU/Linux). - */ - mSocketMethods = rb_define_module_under(mKgio, "SocketMethods"); - rb_define_method(mSocketMethods, "kgio_read", kgio_recv, -1); - rb_define_method(mSocketMethods, "kgio_read!", kgio_recv_bang, -1); - rb_define_method(mSocketMethods, "kgio_tryread", kgio_tryrecv, -1); - rb_define_method(mSocketMethods, "kgio_trypeek", kgio_trypeek, -1); - rb_define_method(mSocketMethods, "kgio_peek", kgio_peek, -1); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/set_file_path.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/set_file_path.h deleted file mode 100644 index 46603f1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/set_file_path.h +++ /dev/null @@ -1,27 +0,0 @@ -/* We do not modify RSTRING in this file, so RSTRING_MODIFIED is not needed */ -#if defined(HAVE_RB_IO_T) && \ - defined(HAVE_TYPE_STRUCT_RFILE) && \ - defined(HAVE_ST_PATHV) -/* MRI 1.9 */ -static void set_file_path(VALUE io, VALUE path) -{ - rb_io_t *fptr = RFILE(io)->fptr; - fptr->pathv = rb_str_new4(path); -} -#elif defined(HAVE_TYPE_OPENFILE) && \ - defined(HAVE_TYPE_STRUCT_RFILE) && \ - defined(HAVE_ST_PATH) -/* MRI 1.8 */ -#include "util.h" -static void set_file_path(VALUE io, VALUE path) -{ - OpenFile *fptr = RFILE(io)->fptr; - fptr->path = ruby_strdup(RSTRING_PTR(path)); -} -#else -/* Rubinius */ -static void set_file_path(VALUE io, VALUE path) -{ - rb_iv_set(io, "@path", rb_str_new4(path)); -} -#endif diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/sock_for_fd.h b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/sock_for_fd.h deleted file mode 100644 index 55f9ccb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/sock_for_fd.h +++ /dev/null @@ -1,71 +0,0 @@ -#ifndef SOCK_FOR_FD_H -#define SOCK_FOR_FD_H -#include -#ifdef HAVE_RUBY_IO_H -# include -#else -# include -# include -#endif - -#if defined(MakeOpenFile) && \ - defined(HAVE_RB_IO_T) && (HAVE_RB_IO_T == 1) && \ - defined(HAVE_RB_IO_ASCII8BIT_BINMODE) && \ - defined(HAVE_ST_FD) && \ - defined(HAVE_ST_MODE) -# define SOCK_FOR_FD (19) -# define FMODE_NOREVLOOKUP 0x100 -#elif defined(MakeOpenFile) && \ - (defined(OpenFile) || defined(HAVE_RB_IO_T)) && \ - defined(HAVE_RB_FDOPEN) && \ - defined(HAVE_ST_F) && \ - defined(HAVE_ST_F2) && \ - defined(HAVE_ST_MODE) -# define SOCK_FOR_FD (18) -#else -# define SOCK_FOR_FD (-1) -#endif - -#if SOCK_FOR_FD == 19 /* modeled after ext/socket/init.c */ -static VALUE sock_for_fd(VALUE klass, int fd) -{ - VALUE sock; - rb_io_t *fp; - - rb_update_max_fd(fd); /* 1.9.3+ API */ - sock = rb_obj_alloc(klass); - MakeOpenFile(sock, fp); - fp->fd = fd; - fp->mode = FMODE_READWRITE|FMODE_DUPLEX|FMODE_NOREVLOOKUP; - rb_io_ascii8bit_binmode(sock); - rb_io_synchronized(fp); - return sock; -} -#elif SOCK_FOR_FD == 18 /* modeled after init_sock() in ext/socket/socket.c */ -static VALUE sock_for_fd(VALUE klass, int fd) -{ - VALUE sock = rb_obj_alloc(klass); - OpenFile *fp; - - MakeOpenFile(sock, fp); - fp->f = rb_fdopen(fd, "r"); - fp->f2 = rb_fdopen(fd, "w"); - fp->mode = FMODE_READWRITE; - rb_io_synchronized(fp); - return sock; -} -#else /* Rubinius, et al. */ -static ID id_for_fd; -static VALUE sock_for_fd(VALUE klass, int fd) -{ - return rb_funcall(klass, id_for_fd, 1, INT2NUM(fd)); -} -static void init_sock_for_fd(void) -{ - id_for_fd = rb_intern("for_fd"); -} -#endif /* sock_for_fd */ -#if SOCK_FOR_FD > 0 -# define init_sock_for_fd() for (;0;) -#endif -#endif /* SOCK_FOR_FD_H */ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/tryopen.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/tryopen.c deleted file mode 100644 index 20f3f6d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/tryopen.c +++ /dev/null @@ -1,197 +0,0 @@ -/* We do not modify RSTRING in this file, so RSTRING_MODIFIED is not needed */ -#include -#ifdef HAVE_RUBY_IO_H -# include -#else -# include -#endif - -#ifdef HAVE_RUBY_ST_H -# include -#else -# include -#endif - -#include -#include -#include -#include -#include "set_file_path.h" -#include "ancient_ruby.h" -#include "kgio.h" - -static ID id_for_fd, id_to_path, id_path; -static st_table *errno2sym; - -struct open_args { - const char *pathname; - int flags; - mode_t mode; -}; - -#ifndef HAVE_RB_CLOEXEC_OPEN -# define rb_cloexec_open(p,f,m) open((p),(f),(m)) -#endif - -static void * nogvl_open(void *ptr) -{ - struct open_args *o = ptr; - long fd = (long)rb_cloexec_open(o->pathname, o->flags, o->mode); - - return (void *)fd; -} - -#ifndef KGIO_WITHOUT_GVL -# define RUBY_UBF_IO ((void *)(-1)) -# include "rubysig.h" -typedef void my_unblock_function_t(void *); -typedef void *my_blocking_function_t(void *); -static void * my_thread_blocking_region( - my_blocking_function_t *fn, void *data1, - my_unblock_function_t *ubf, void *data2) -{ - void *rv; - - TRAP_BEG; /* for FIFO */ - rv = fn(data1); - TRAP_END; - - return rv; -} -#define KGIO_WITHOUT_GVL(fn,data1,ubf,data2) \ - my_thread_blocking_region((fn),(data1),(ubf),(data2)) -#endif /* ! KGIO_WITHOUT_GVL */ - -/* - * call-seq: - * - * Kgio::File.tryopen(filename, [, mode [, perm]]) -> Kgio::File or Symbol - * - * Returns a Kgio::File object on a successful open. +filename+ is a - * path to any file on the filesystem. If specified, +mode+ is a bitmask - * of flags (see IO.sysopen) and +perm+ should be an octal number. - * - * This does not raise errors for most failures, but installs returns a - * Ruby symbol for the constant in the Errno::* namespace. - * - * Common error symbols are: - * - * - :ENOENT - * - :EACCES - * - * See your open(2) manpage for more information on open(2) errors. - */ -static VALUE s_tryopen(int argc, VALUE *argv, VALUE klass) -{ - long fd; - VALUE pathname, flags, mode; - struct open_args o; - int retried = 0; - VALUE rv; - - rb_scan_args(argc, argv, "12", &pathname, &flags, &mode); - if (rb_respond_to(pathname, id_to_path)) - pathname = rb_funcall(pathname, id_to_path, 0); - o.pathname = StringValueCStr(pathname); - - switch (TYPE(flags)) { - case T_NIL: o.flags = O_RDONLY; break; - case T_FIXNUM: o.flags = FIX2INT(flags); break; - case T_BIGNUM: o.flags = NUM2INT(flags); break; - default: rb_raise(rb_eArgError, "flags must be an Integer"); - } - switch (TYPE(mode)) { - case T_NIL: o.mode = 0666; break; - case T_FIXNUM: o.mode = FIX2INT(mode); break; - case T_BIGNUM: o.mode = NUM2INT(mode); break; - default: rb_raise(rb_eArgError, "mode must be an Integer"); - } - -retry: - fd = (long)KGIO_WITHOUT_GVL(nogvl_open, &o, RUBY_UBF_IO, 0); - if (fd < 0) { - if (errno == EMFILE || errno == ENFILE || errno == ENOMEM) { - rb_gc(); - if (retried) - rb_sys_fail(o.pathname); - retried = 1; - goto retry; - } - if (fd < 0) { - int saved_errno = errno; - - if (!st_lookup(errno2sym, (st_data_t)errno, &rv)) { - errno = saved_errno; - rb_sys_fail(o.pathname); - } - return rv; - } - } - rv = rb_funcall(klass, id_for_fd, 1, LONG2FIX(fd)); - set_file_path(rv, pathname); - return rv; -} - -void init_kgio_tryopen(void) -{ - VALUE mKgio = rb_define_module("Kgio"); - VALUE mPipeMethods = rb_const_get(mKgio, rb_intern("PipeMethods")); - VALUE cFile; - VALUE tmp; - long i, len; - - id_path = rb_intern("path"); - id_for_fd = rb_intern("for_fd"); - id_to_path = rb_intern("to_path"); - - /* - * Document-class: Kgio::File - * - * This subclass of the core File class adds the "tryopen" singleton - * method for opening files. A single "tryopen" and check for the - * return value may be used to avoid unnecessary stat(2) syscalls - * or File.open exceptions when checking for the existence of a file - * and opening it. - */ - cFile = rb_define_class_under(mKgio, "File", rb_cFile); - rb_define_singleton_method(cFile, "tryopen", s_tryopen, -1); - rb_include_module(cFile, mPipeMethods); - - if (!rb_funcall(cFile, rb_intern("method_defined?"), 1, - ID2SYM(id_to_path))) - rb_define_alias(cFile, "to_path", "path"); - - errno2sym = st_init_numtable(); - tmp = rb_funcall(rb_mErrno, rb_intern("constants"), 0); - len = RARRAY_LEN(tmp); - for (i = 0; i < len; i++) { - VALUE error; - VALUE err = rb_ary_entry(tmp, i); - ID const_id; - - switch (TYPE(err)) { - case T_SYMBOL: const_id = SYM2ID(err); break; - case T_STRING: const_id = rb_intern(RSTRING_PTR(err)); break; - default: { - VALUE i = rb_inspect(err); - const char *s = RSTRING_PTR(i); - - rb_bug("constant not a symbol or string: %s", s); - RB_GC_GUARD(i); - } - } - - error = rb_const_get(rb_mErrno, const_id); - if ((TYPE(error) != T_CLASS) || - !rb_const_defined(error, rb_intern("Errno"))) - continue; - - error = rb_const_get(error, rb_intern("Errno")); - switch (TYPE(error)) { - case T_FIXNUM: - case T_BIGNUM: - st_insert(errno2sym, (st_data_t)NUM2INT(error), - ID2SYM(const_id)); - } - } -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/wait.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/wait.c deleted file mode 100644 index 7bdf0a1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/wait.c +++ /dev/null @@ -1,126 +0,0 @@ -#include "kgio.h" -#include "my_fileno.h" -static ID id_wait_rd, id_wait_wr; - -#if defined(HAVE_RB_TIME_INTERVAL) && defined(HAVE_RB_WAIT_FOR_SINGLE_FD) -static int kgio_timedwait(VALUE self, VALUE timeout, int write_p) -{ - struct timeval tv = rb_time_interval(timeout); - int events = write_p ? RB_WAITFD_OUT : RB_WAITFD_IN; - - return rb_wait_for_single_fd(my_fileno(self), events, &tv); -} -#else /* ! (HAVE_RB_TIME_INTERVAL && HAVE_RB_WAIT_FOR_SINGLE_FD) */ -static int kgio_timedwait(VALUE self, VALUE timeout, int write_p) -{ - VALUE argv[4]; - VALUE set = rb_ary_new3(1, self); - - argv[0] = write_p ? Qnil : set; - argv[1] = write_p ? set : Qnil; - argv[2] = Qnil; - argv[3] = timeout; - - set = rb_funcall2(rb_cIO, rb_intern("select"), 4, argv); - return NIL_P(set) ? 0 : 1; -} -#endif /* ! (HAVE_RB_TIME_INTERVAL && HAVE_RB_WAIT_FOR_SINGLE_FD) */ - -static int kgio_wait(int argc, VALUE *argv, VALUE self, int write_p) -{ - int fd; - VALUE timeout; - - if (rb_scan_args(argc, argv, "01", &timeout) == 1 && !NIL_P(timeout)) - return kgio_timedwait(self, timeout, write_p); - - fd = my_fileno(self); - errno = EAGAIN; - write_p ? rb_io_wait_writable(fd) : rb_io_wait_readable(fd); - return 1; -} - -/* - * call-seq: - * - * io.kgio_wait_readable -> IO - * io.kgio_wait_readable(timeout) -> IO or nil - * - * Blocks the running Thread indefinitely until the IO object is readable - * or if +timeout+ expires. If +timeout+ is specified and expires, +nil+ - * is returned. - * - * This method is automatically called (without timeout argument) by default - * whenever kgio_read needs to block on input. - * - * Users of alternative threading/fiber libraries are - * encouraged to override this method in their subclasses or modules to - * work with their threading/blocking methods. - */ -static VALUE kgio_wait_readable(int argc, VALUE *argv, VALUE self) -{ - int r = kgio_wait(argc, argv, self, 0); - - if (r < 0) rb_sys_fail("kgio_wait_readable"); - return r == 0 ? Qnil : self; -} - -/* - * call-seq: - * - * io.kgio_wait_writable -> IO - * io.kgio_wait_writable(timeout) -> IO or nil - * - * Blocks the running Thread indefinitely until the IO object is writable - * or if +timeout+ expires. If +timeout+ is specified and expires, +nil+ - * is returned. - * - * This method is automatically called (without timeout argument) by default - * whenever kgio_write needs to block on output. - * - * Users of alternative threading/fiber libraries are - * encouraged to override this method in their subclasses or modules to - * work with their threading/blocking methods. - */ -static VALUE kgio_wait_writable(int argc, VALUE *argv, VALUE self) -{ - int r = kgio_wait(argc, argv, self, 1); - - if (r < 0) rb_sys_fail("kgio_wait_writable"); - return r == 0 ? Qnil : self; -} - -VALUE kgio_call_wait_writable(VALUE io) -{ - return rb_funcall(io, id_wait_wr, 0, 0); -} - -VALUE kgio_call_wait_readable(VALUE io) -{ - return rb_funcall(io, id_wait_rd, 0, 0); -} - -void init_kgio_wait(void) -{ - VALUE mKgio = rb_define_module("Kgio"); - - /* - * Document-module: Kgio::DefaultWaiters - * - * This module contains default kgio_wait_readable and - * kgio_wait_writable methods that block indefinitely (in a - * thread-safe manner) until an IO object is read or writable. - * This module is included in the Kgio::PipeMethods and - * Kgio::SocketMethods modules used by all bundled IO-derived - * objects. - */ - VALUE mWaiters = rb_define_module_under(mKgio, "DefaultWaiters"); - - id_wait_rd = rb_intern("kgio_wait_readable"); - id_wait_wr = rb_intern("kgio_wait_writable"); - - rb_define_method(mWaiters, "kgio_wait_readable", - kgio_wait_readable, -1); - rb_define_method(mWaiters, "kgio_wait_writable", - kgio_wait_writable, -1); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/write.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/write.c deleted file mode 100644 index cdf97b1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/write.c +++ /dev/null @@ -1,262 +0,0 @@ -/* we do not modify RSTRING pointers here */ -#include "kgio.h" -#include "my_fileno.h" -#include "nonblock.h" -static VALUE sym_wait_writable; - -struct wr_args { - VALUE io; - VALUE buf; - const char *ptr; - long len; - int fd; - int flags; -}; - -static void prepare_write(struct wr_args *a, VALUE io, VALUE str) -{ - a->buf = (TYPE(str) == T_STRING) ? str : rb_obj_as_string(str); - a->ptr = RSTRING_PTR(a->buf); - a->len = RSTRING_LEN(a->buf); - a->io = io; - a->fd = my_fileno(io); -} - -static int write_check(struct wr_args *a, long n, const char *msg, int io_wait) -{ - if (a->len == n) { -done: - a->buf = Qnil; - } else if (n < 0) { - if (errno == EINTR) { - a->fd = my_fileno(a->io); - return -1; - } - if (errno == EAGAIN) { - long written = RSTRING_LEN(a->buf) - a->len; - - if (io_wait) { - (void)kgio_call_wait_writable(a->io); - - /* buf may be modified in other thread/fiber */ - a->len = RSTRING_LEN(a->buf) - written; - if (a->len <= 0) - goto done; - a->ptr = RSTRING_PTR(a->buf) + written; - return -1; - } else if (written > 0) { - a->buf = rb_str_subseq(a->buf, written, a->len); - } else { - a->buf = sym_wait_writable; - } - return 0; - } - kgio_wr_sys_fail(msg); - } else { - assert(n >= 0 && n < a->len && "write/send syscall broken?"); - a->ptr += n; - a->len -= n; - return -1; - } - return 0; -} - -static VALUE my_write(VALUE io, VALUE str, int io_wait) -{ - struct wr_args a; - long n; - - prepare_write(&a, io, str); - set_nonblocking(a.fd); -retry: - n = (long)write(a.fd, a.ptr, a.len); - if (write_check(&a, n, "write", io_wait) != 0) - goto retry; - if (TYPE(a.buf) != T_SYMBOL) - kgio_autopush_write(io); - return a.buf; -} - -/* - * call-seq: - * - * io.kgio_write(str) -> nil - * - * Returns nil when the write completes. - * - * This may block and call any method defined to +kgio_wait_writable+ - * for the class. - */ -static VALUE kgio_write(VALUE io, VALUE str) -{ - return my_write(io, str, 1); -} - -/* - * call-seq: - * - * io.kgio_trywrite(str) -> nil, String or :wait_writable - * - * Returns nil if the write was completed in full. - * - * Returns a String containing the unwritten portion if EAGAIN - * was encountered, but some portion was successfully written. - * - * Returns :wait_writable if EAGAIN is encountered and nothing - * was written. - */ -static VALUE kgio_trywrite(VALUE io, VALUE str) -{ - return my_write(io, str, 0); -} - -#ifdef USE_MSG_DONTWAIT -/* - * This method behaves like Kgio::PipeMethods#kgio_write, except - * it will use send(2) with the MSG_DONTWAIT flag on sockets to - * avoid unnecessary calls to fcntl(2). - */ -static VALUE my_send(VALUE io, VALUE str, int io_wait) -{ - struct wr_args a; - long n; - - prepare_write(&a, io, str); -retry: - n = (long)send(a.fd, a.ptr, a.len, MSG_DONTWAIT); - if (write_check(&a, n, "send", io_wait) != 0) - goto retry; - if (TYPE(a.buf) != T_SYMBOL) - kgio_autopush_send(io); - return a.buf; -} - -/* - * This method may be optimized on some systems (e.g. GNU/Linux) to use - * MSG_DONTWAIT to avoid explicitly setting the O_NONBLOCK flag via fcntl. - * Otherwise this is the same as Kgio::PipeMethods#kgio_write - */ -static VALUE kgio_send(VALUE io, VALUE str) -{ - return my_send(io, str, 1); -} - -/* - * This method may be optimized on some systems (e.g. GNU/Linux) to use - * MSG_DONTWAIT to avoid explicitly setting the O_NONBLOCK flag via fcntl. - * Otherwise this is the same as Kgio::PipeMethods#kgio_trywrite - */ -static VALUE kgio_trysend(VALUE io, VALUE str) -{ - return my_send(io, str, 0); -} -#else /* ! USE_MSG_DONTWAIT */ -# define kgio_send kgio_write -# define kgio_trysend kgio_trywrite -#endif /* ! USE_MSG_DONTWAIT */ - -#if defined(KGIO_WITHOUT_GVL) -# include "blocking_io_region.h" -#ifdef MSG_DONTWAIT /* Linux only */ -# define MY_MSG_DONTWAIT (MSG_DONTWAIT) -#else -# define MY_MSG_DONTWAIT (0) -#endif - -static VALUE nogvl_send(void *ptr) -{ - struct wr_args *a = ptr; - - return (VALUE)send(a->fd, a->ptr, a->len, a->flags); -} -/* - * call-seq: - * - * io.kgio_syssend(str, flags) -> nil, String or :wait_writable - * - * Returns nil if the write was completed in full. - * - * Returns a String containing the unwritten portion if EAGAIN - * was encountered, but some portion was successfully written. - * - * Returns :wait_writable if EAGAIN is encountered and nothing - * was written. - * - * This method is only available on Ruby 1.9.3 or later. - */ -static VALUE kgio_syssend(VALUE io, VALUE str, VALUE flags) -{ - struct wr_args a; - long n; - - a.flags = NUM2INT(flags); - prepare_write(&a, io, str); - if (a.flags & MY_MSG_DONTWAIT) { - do { - n = (long)send(a.fd, a.ptr, a.len, a.flags); - } while (write_check(&a, n, "send", 0) != 0); - } else { - do { - n = (long)rb_thread_io_blocking_region( - nogvl_send, &a, a.fd); - } while (write_check(&a, n, "send", 0) != 0); - } - return a.buf; -} -#endif /* HAVE_RB_THREAD_IO_BLOCKING_REGION */ - -/* - * call-seq: - * - * Kgio.trywrite(io, str) -> nil, String or :wait_writable - * - * Returns nil if the write was completed in full. - * - * Returns a String containing the unwritten portion if EAGAIN - * was encountered, but some portion was successfully written. - * - * Returns :wait_writable if EAGAIN is encountered and nothing - * was written. - * - * Maybe used in place of PipeMethods#kgio_trywrite for non-Kgio objects - */ -static VALUE s_trywrite(VALUE mod, VALUE io, VALUE str) -{ - return my_write(io, str, 0); -} - -void init_kgio_write(void) -{ - VALUE mPipeMethods, mSocketMethods; - VALUE mKgio = rb_define_module("Kgio"); - - sym_wait_writable = ID2SYM(rb_intern("wait_writable")); - - rb_define_singleton_method(mKgio, "trywrite", s_trywrite, 2); - - /* - * Document-module: Kgio::PipeMethods - * - * This module may be used used to create classes that respond to - * various Kgio methods for reading and writing. This is included - * in Kgio::Pipe by default. - */ - mPipeMethods = rb_define_module_under(mKgio, "PipeMethods"); - rb_define_method(mPipeMethods, "kgio_write", kgio_write, 1); - rb_define_method(mPipeMethods, "kgio_trywrite", kgio_trywrite, 1); - - /* - * Document-module: Kgio::SocketMethods - * - * This method behaves like Kgio::PipeMethods, but contains - * optimizations for sockets on certain operating systems - * (e.g. GNU/Linux). - */ - mSocketMethods = rb_define_module_under(mKgio, "SocketMethods"); - rb_define_method(mSocketMethods, "kgio_write", kgio_send, 1); - rb_define_method(mSocketMethods, "kgio_trywrite", kgio_trysend, 1); - -#if defined(KGIO_WITHOUT_GVL) - rb_define_method(mSocketMethods, "kgio_syssend", kgio_syssend, 2); -#endif -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/writev.c b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/writev.c deleted file mode 100644 index aafc6d8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/ext/kgio/writev.c +++ /dev/null @@ -1,328 +0,0 @@ -/* - * we're currently too lazy to use rb_ensure to free an allocation, so we - * the abuse rb_str_* API for a temporary buffer - */ -#define RSTRING_MODIFIED 1 - -#include "kgio.h" -#include "my_fileno.h" -#include "nonblock.h" -#ifdef HAVE_WRITEV -# include -# define USE_WRITEV 1 -#else -# define USE_WRITEV 0 -static ssize_t assert_writev(int fd, void* iov, int len) -{ - assert(0 && "you should not try to call writev"); - return -1; -} -# define writev assert_writev -#endif - -#ifndef HAVE_RB_ARY_SUBSEQ -static inline VALUE my_ary_subseq(VALUE ary, long idx, long len) -{ - VALUE args[2] = { LONG2FIX(idx), LONG2FIX(len) }; - - return rb_ary_aref(2, args, ary); -} -#define rb_ary_subseq my_ary_subseq -#endif - -static VALUE sym_wait_writable; - -#ifndef HAVE_WRITEV -#define iovec my_iovec -struct my_iovec { - void *iov_base; - size_t iov_len; -}; -#endif - -/* tests for choosing following constants were done on Linux 3.0 x86_64 - * (Ubuntu 12.04) Core i3 i3-2330M slowed to 1600MHz - * testing script https://gist.github.com/2850641 - * fill free to make more thorough testing and choose better value - */ - -/* test shows that its meaningless to set WRITEV_MEMLIMIT more that 1M - * even when tcp_wmem set to relatively high value (2M) (in fact, it becomes - * even slower). 512K performs a bit better in average case. */ -#define WRITEV_MEMLIMIT (512*1024) -/* same test shows that custom_writev is faster than glibc writev when - * average string is smaller than ~500 bytes and slower when average strings - * is greater then ~600 bytes. 512 bytes were choosen cause current compilers - * turns x/512 into x>>9 */ -#define WRITEV_IMPL_THRESHOLD 512 - -static unsigned int iov_max = 1024; /* this could be overriden in init */ - -struct wrv_args { - VALUE io; - VALUE buf; - VALUE vec_buf; /* FIXME: this requires RSTRING_MODIFY for rbx */ - struct iovec *vec; - unsigned long iov_cnt; - size_t batch_len; - int something_written; - int fd; -}; - -static ssize_t custom_writev(int fd, const struct iovec *vec, unsigned int iov_cnt, size_t total_len) -{ - unsigned int i; - ssize_t result; - char *buf, *curbuf; - const struct iovec *curvec = vec; - - /* we do not want to use ruby's xmalloc because - * it can fire GC, and we'll free buffer shortly anyway */ - curbuf = buf = malloc(total_len); - if (buf == NULL) return -1; - - for (i = 0; i < iov_cnt; i++, curvec++) { - memcpy(curbuf, curvec->iov_base, curvec->iov_len); - curbuf += curvec->iov_len; - } - - result = write(fd, buf, total_len); - - /* well, it seems that `free` could not change errno - * but lets save it anyway */ - i = errno; - free(buf); - errno = i; - - return result; -} - -static void prepare_writev(struct wrv_args *a, VALUE io, VALUE ary) -{ - a->io = io; - a->fd = my_fileno(io); - a->something_written = 0; - - if (TYPE(ary) == T_ARRAY) - /* rb_ary_subseq will not copy array unless it modified */ - a->buf = rb_ary_subseq(ary, 0, RARRAY_LEN(ary)); - else - a->buf = rb_Array(ary); - - a->vec_buf = rb_str_new(0, 0); - a->vec = NULL; -} - -static void fill_iovec(struct wrv_args *a) -{ - unsigned long i; - struct iovec *curvec; - - a->iov_cnt = RARRAY_LEN(a->buf); - a->batch_len = 0; - if (a->iov_cnt == 0) return; - if (a->iov_cnt > iov_max) a->iov_cnt = iov_max; - rb_str_resize(a->vec_buf, sizeof(struct iovec) * a->iov_cnt); - curvec = a->vec = (struct iovec*)RSTRING_PTR(a->vec_buf); - - for (i=0; i < a->iov_cnt; i++, curvec++) { - VALUE str = rb_ary_entry(a->buf, i); - long str_len, next_len; - - if (TYPE(str) != T_STRING) { - str = rb_obj_as_string(str); - rb_ary_store(a->buf, i, str); - } - - str_len = RSTRING_LEN(str); - - /* lets limit total memory to write, - * but always take first string */ - next_len = a->batch_len + str_len; - if (i && next_len > WRITEV_MEMLIMIT) { - a->iov_cnt = i; - break; - } - a->batch_len = next_len; - - curvec->iov_base = RSTRING_PTR(str); - curvec->iov_len = str_len; - } -} - -static long trim_writev_buffer(struct wrv_args *a, long n) -{ - long i; - long ary_len = RARRAY_LEN(a->buf); - - if (n == (long)a->batch_len) { - i = a->iov_cnt; - n = 0; - } else { - for (i = 0; n && i < ary_len; i++) { - VALUE entry = rb_ary_entry(a->buf, i); - n -= RSTRING_LEN(entry); - if (n < 0) break; - } - } - - /* all done */ - if (i == ary_len) { - assert(n == 0 && "writev system call is broken"); - a->buf = Qnil; - return 0; - } - - /* partially done, remove fully-written buffers */ - if (i > 0) - a->buf = rb_ary_subseq(a->buf, i, ary_len - i); - - /* setup+replace partially written buffer */ - if (n < 0) { - VALUE str = rb_ary_entry(a->buf, 0); - long str_len = RSTRING_LEN(str); - str = rb_str_subseq(str, str_len + n, -n); - rb_ary_store(a->buf, 0, str); - } - return RARRAY_LEN(a->buf); -} - -static int writev_check(struct wrv_args *a, long n, const char *msg, int io_wait) -{ - if (n >= 0) { - if (n > 0) a->something_written = 1; - return trim_writev_buffer(a, n); - } else if (n < 0) { - if (errno == EINTR) { - a->fd = my_fileno(a->io); - return -1; - } - if (errno == EAGAIN) { - if (io_wait) { - (void)kgio_call_wait_writable(a->io); - return -1; - } else if (!a->something_written) { - a->buf = sym_wait_writable; - } - return 0; - } - kgio_wr_sys_fail(msg); - } - return 0; -} - -static VALUE my_writev(VALUE io, VALUE ary, int io_wait) -{ - struct wrv_args a; - long n; - - prepare_writev(&a, io, ary); - set_nonblocking(a.fd); - - do { - fill_iovec(&a); - if (a.iov_cnt == 0) - n = 0; - else if (a.iov_cnt == 1) - n = (long)write(a.fd, a.vec[0].iov_base, - a.vec[0].iov_len); - /* for big strings use library function */ - else if (USE_WRITEV && - ((a.batch_len / WRITEV_IMPL_THRESHOLD) > a.iov_cnt)) - n = (long)writev(a.fd, a.vec, a.iov_cnt); - else - n = (long)custom_writev(a.fd, a.vec, a.iov_cnt, - a.batch_len); - } while (writev_check(&a, n, "writev", io_wait) != 0); - rb_str_resize(a.vec_buf, 0); - - if (TYPE(a.buf) != T_SYMBOL) - kgio_autopush_write(io); - return a.buf; -} - -/* - * call-seq: - * - * io.kgio_writev(array) -> nil - * - * Returns nil when the write completes. - * - * This may block and call any method defined to +kgio_wait_writable+ - * for the class. - * - * Note: it uses +Array()+ semantic for converting argument, so that - * it will succeed if you pass something else. - */ -static VALUE kgio_writev(VALUE io, VALUE ary) -{ - return my_writev(io, ary, 1); -} - -/* - * call-seq: - * - * io.kgio_trywritev(array) -> nil, Array or :wait_writable - * - * Returns nil if the write was completed in full. - * - * Returns an Array of strings containing the unwritten portion - * if EAGAIN was encountered, but some portion was successfully written. - * - * Returns :wait_writable if EAGAIN is encountered and nothing - * was written. - * - * Note: it uses +Array()+ semantic for converting argument, so that - * it will succeed if you pass something else. - */ -static VALUE kgio_trywritev(VALUE io, VALUE ary) -{ - return my_writev(io, ary, 0); -} - -/* - * call-seq: - * - * Kgio.trywritev(io, array) -> nil, Array or :wait_writable - * - * Returns nil if the write was completed in full. - * - * Returns a Array of strings containing the unwritten portion if EAGAIN - * was encountered, but some portion was successfully written. - * - * Returns :wait_writable if EAGAIN is encountered and nothing - * was written. - * - * Maybe used in place of PipeMethods#kgio_trywritev for non-Kgio objects - */ -static VALUE s_trywritev(VALUE mod, VALUE io, VALUE ary) -{ - return kgio_trywritev(io, ary); -} - -void init_kgio_writev(void) -{ -#ifdef IOV_MAX - unsigned int sys_iov_max = IOV_MAX; -#else - unsigned int sys_iov_max = sysconf(_SC_IOV_MAX); -#endif - - VALUE mPipeMethods, mSocketMethods; - VALUE mKgio = rb_define_module("Kgio"); - - if (sys_iov_max < iov_max) - iov_max = sys_iov_max; - - sym_wait_writable = ID2SYM(rb_intern("wait_writable")); - - rb_define_singleton_method(mKgio, "trywritev", s_trywritev, 2); - - mPipeMethods = rb_define_module_under(mKgio, "PipeMethods"); - rb_define_method(mPipeMethods, "kgio_writev", kgio_writev, 1); - rb_define_method(mPipeMethods, "kgio_trywritev", kgio_trywritev, 1); - - mSocketMethods = rb_define_module_under(mKgio, "SocketMethods"); - rb_define_method(mSocketMethods, "kgio_writev", kgio_writev, 1); - rb_define_method(mSocketMethods, "kgio_trywritev", kgio_trywritev, 1); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/kgio.gemspec b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/kgio.gemspec deleted file mode 100644 index ff6a48e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/kgio.gemspec +++ /dev/null @@ -1,29 +0,0 @@ -ENV["VERSION"] or abort "VERSION= must be specified" -manifest = File.readlines('.manifest').map! { |x| x.chomp! } -require 'wrongdoc' -extend Wrongdoc::Gemspec -name, summary, title = readme_metadata - -Gem::Specification.new do |s| - s.name = %q{kgio} - s.version = ENV["VERSION"].dup - s.homepage = Wrongdoc.config[:rdoc_url] - s.authors = ["#{name} hackers"] - s.date = Time.now.utc.strftime('%Y-%m-%d') - s.description = readme_description - s.email = %q{kgio@librelist.org} - s.extra_rdoc_files = extra_rdoc_files(manifest) - s.files = manifest - s.rdoc_options = rdoc_options - s.rubyforge_project = %q{rainbows} - s.summary = summary - s.test_files = Dir['test/test_*.rb'] - s.extensions = %w(ext/kgio/extconf.rb) - - # development dependencies commented out for folks stuck on - # old Ruby/RubyGems versions - # s.add_development_dependency('wrongdoc', '~> 1.5') - # s.add_development_dependency('strace_me', '~> 1.0') # Linux only - - # s.license = %w(LGPL) # disabled for compatibility with older RubyGems -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/lib/kgio.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/lib/kgio.rb deleted file mode 100644 index 5de431b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/lib/kgio.rb +++ /dev/null @@ -1,38 +0,0 @@ -# -*- encoding: binary -*- -require 'socket' - -# See the {README}[link:index.html] -module Kgio - - # The IPv4 address of UNIX domain sockets, useful for creating - # Rack (and CGI) servers that also serve HTTP traffic over - # UNIX domain sockets. - LOCALHOST = '127.0.0.1' - - # Kgio::PipeMethods#kgio_tryread and Kgio::SocketMethods#kgio_tryread will - # return :wait_readable when waiting for a read is required. - WaitReadable = :wait_readable - - # PipeMethods#kgio_trywrite and SocketMethods#kgio_trywrite will return - # :wait_writable when waiting for a read is required. - WaitWritable = :wait_writable -end - -require 'kgio_ext' - -# use Kgio::Pipe.popen and Kgio::Pipe.new instead of IO.popen -# and IO.pipe to get PipeMethods#kgio_read and PipeMethod#kgio_write -# methods. -class Kgio::Pipe < IO - include Kgio::PipeMethods - class << self - - # call-seq: - # - # rd, wr = Kgio::Pipe.new - # - # This creates a new pipe(7) with Kgio::Pipe objects that respond - # to PipeMethods#kgio_read and PipeMethod#kgio_write - alias new pipe - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/lib/kgio_ext.bundle b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/lib/kgio_ext.bundle deleted file mode 100755 index 48342ab..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/lib/kgio_ext.bundle and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/pkg.mk b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/pkg.mk deleted file mode 100644 index 4cd5bef..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/pkg.mk +++ /dev/null @@ -1,175 +0,0 @@ -RUBY = ruby -RAKE = rake -RSYNC = rsync -WRONGDOC = wrongdoc - -GIT-VERSION-FILE: .FORCE-GIT-VERSION-FILE - @./GIT-VERSION-GEN --include GIT-VERSION-FILE --include local.mk -DLEXT := $(shell $(RUBY) -rrbconfig -e 'puts RbConfig::CONFIG["DLEXT"]') -RUBY_VERSION := $(shell $(RUBY) -e 'puts RUBY_VERSION') -RUBY_ENGINE := $(shell $(RUBY) -e 'puts((RUBY_ENGINE rescue "ruby"))') -lib := lib - -ifeq ($(shell test -f script/isolate_for_tests && echo t),t) -isolate_libs := tmp/isolate/$(RUBY_ENGINE)-$(RUBY_VERSION)/isolate.mk -$(isolate_libs): script/isolate_for_tests - @$(RUBY) script/isolate_for_tests --include $(isolate_libs) -lib := $(lib):$(ISOLATE_LIBS) -endif - -ext := $(firstword $(wildcard ext/*)) -ifneq ($(ext),) -ext_pfx := tmp/ext/$(RUBY_ENGINE)-$(RUBY_VERSION) -ext_h := $(wildcard $(ext)/*/*.h $(ext)/*.h) -ext_src := $(wildcard $(ext)/*.c $(ext_h)) -ext_pfx_src := $(addprefix $(ext_pfx)/,$(ext_src)) -ext_d := $(ext_pfx)/$(ext)/.d -$(ext)/extconf.rb: $(wildcard $(ext)/*.h) - @>> $@ -$(ext_d): - @mkdir -p $(@D) - @> $@ -$(ext_pfx)/$(ext)/%: $(ext)/% $(ext_d) - install -m 644 $< $@ -$(ext_pfx)/$(ext)/Makefile: $(ext)/extconf.rb $(ext_d) $(ext_h) - $(RM) -f $(@D)/*.o - cd $(@D) && $(RUBY) $(CURDIR)/$(ext)/extconf.rb -ext_sfx := _ext.$(DLEXT) -ext_dl := $(ext_pfx)/$(ext)/$(notdir $(ext)_ext.$(DLEXT)) -$(ext_dl): $(ext_src) $(ext_pfx_src) $(ext_pfx)/$(ext)/Makefile - @echo $^ == $@ - $(MAKE) -C $(@D) -lib := $(lib):$(ext_pfx)/$(ext) -build: $(ext_dl) -else -build: -endif - -pkg_extra += GIT-VERSION-FILE NEWS ChangeLog LATEST -ChangeLog: GIT-VERSION-FILE .wrongdoc.yml - $(WRONGDOC) prepare -NEWS LATEST: ChangeLog - -manifest: - $(RM) .manifest - $(MAKE) .manifest - -.manifest: $(pkg_extra) - (git ls-files && for i in $@ $(pkg_extra); do echo $$i; done) | \ - LC_ALL=C sort > $@+ - cmp $@+ $@ || mv $@+ $@ - $(RM) $@+ - -doc:: .document .wrongdoc.yml $(pkg_extra) - -find lib -type f -name '*.rbc' -exec rm -f '{}' ';' - -find ext -type f -name '*.rbc' -exec rm -f '{}' ';' - $(RM) -r doc - $(WRONGDOC) all - install -m644 COPYING doc/COPYING - install -m644 $(shell LC_ALL=C grep '^[A-Z]' .document) doc/ - -ifneq ($(VERSION),) -pkggem := pkg/$(rfpackage)-$(VERSION).gem -pkgtgz := pkg/$(rfpackage)-$(VERSION).tgz -release_notes := release_notes-$(VERSION) -release_changes := release_changes-$(VERSION) - -release-notes: $(release_notes) -release-changes: $(release_changes) -$(release_changes): - $(WRONGDOC) release_changes > $@+ - $(VISUAL) $@+ && test -s $@+ && mv $@+ $@ -$(release_notes): - $(WRONGDOC) release_notes > $@+ - $(VISUAL) $@+ && test -s $@+ && mv $@+ $@ - -# ensures we're actually on the tagged $(VERSION), only used for release -verify: - test x"$(shell umask)" = x0022 - git rev-parse --verify refs/tags/v$(VERSION)^{} - git diff-index --quiet HEAD^0 - test $$(git rev-parse --verify HEAD^0) = \ - $$(git rev-parse --verify refs/tags/v$(VERSION)^{}) - -fix-perms: - -git ls-tree -r HEAD | awk '/^100644 / {print $$NF}' | xargs chmod 644 - -git ls-tree -r HEAD | awk '/^100755 / {print $$NF}' | xargs chmod 755 - -gem: $(pkggem) - -install-gem: $(pkggem) - gem install $(CURDIR)/$< - -$(pkggem): manifest fix-perms - gem build $(rfpackage).gemspec - mkdir -p pkg - mv $(@F) $@ - -$(pkgtgz): distdir = $(basename $@) -$(pkgtgz): HEAD = v$(VERSION) -$(pkgtgz): manifest fix-perms - @test -n "$(distdir)" - $(RM) -r $(distdir) - mkdir -p $(distdir) - tar cf - $$(cat .manifest) | (cd $(distdir) && tar xf -) - cd pkg && tar cf - $(basename $(@F)) | gzip -9 > $(@F)+ - mv $@+ $@ - -package: $(pkgtgz) $(pkggem) - -test-release:: verify package $(release_notes) $(release_changes) - # make tgz release on RubyForge - @echo rubyforge add_release -f \ - -n $(release_notes) -a $(release_changes) \ - $(rfproject) $(rfpackage) $(VERSION) $(pkgtgz) - @echo gem push $(pkggem) - @echo rubyforge add_file \ - $(rfproject) $(rfpackage) $(VERSION) $(pkggem) -release:: verify package $(release_notes) $(release_changes) - # make tgz release on RubyForge - rubyforge add_release -f -n $(release_notes) -a $(release_changes) \ - $(rfproject) $(rfpackage) $(VERSION) $(pkgtgz) - # push gem to RubyGems.org - gem push $(pkggem) - # in case of gem downloads from RubyForge releases page - rubyforge add_file \ - $(rfproject) $(rfpackage) $(VERSION) $(pkggem) -else -gem install-gem: GIT-VERSION-FILE - $(MAKE) $@ VERSION=$(GIT_VERSION) -endif - -all:: test -test_units := $(wildcard test/test_*.rb) -test: test-unit -test-unit: $(test_units) -$(test_units): build - $(RUBY) -I $(lib) $@ $(RUBY_TEST_OPTS) - -# this requires GNU coreutils variants -ifneq ($(RSYNC_DEST),) -publish_doc: - -git set-file-times - $(MAKE) doc - find doc/images -type f | \ - TZ=UTC xargs touch -d '1970-01-01 00:00:06' doc/rdoc.css - $(MAKE) doc_gz - $(RSYNC) -av doc/ $(RSYNC_DEST)/ - git ls-files | xargs touch -endif - -# Create gzip variants of the same timestamp as the original so nginx -# "gzip_static on" can serve the gzipped versions directly. -doc_gz: docs = $(shell find doc -type f ! -regex '^.*\.\(gif\|jpg\|png\|gz\)$$') -doc_gz: - for i in $(docs); do \ - gzip --rsyncable -9 < $$i > $$i.gz; touch -r $$i $$i.gz; done -check-warnings: - @(for i in $$(git ls-files '*.rb'| grep -v '^setup\.rb$$'); \ - do $(RUBY) -d -W2 -c $$i; done) | grep -v '^Syntax OK$$' || : - -.PHONY: all .FORCE-GIT-VERSION-FILE doc test $(test_units) manifest -.PHONY: check-warnings diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/setup.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/setup.rb deleted file mode 100644 index 5eb5006..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/setup.rb +++ /dev/null @@ -1,1586 +0,0 @@ -# -*- encoding: binary -*- -# -# setup.rb -# -# Copyright (c) 2000-2005 Minero Aoki -# -# This program is free software. -# You can distribute/modify this program under the terms of -# the GNU LGPL, Lesser General Public License version 2.1. -# - -unless Enumerable.method_defined?(:map) # Ruby 1.4.6 - module Enumerable - alias map collect - end -end - -unless File.respond_to?(:read) # Ruby 1.6 - def File.read(fname) - open(fname) {|f| - return f.read - } - end -end - -unless Errno.const_defined?(:ENOTEMPTY) # Windows? - module Errno - class ENOTEMPTY - # We do not raise this exception, implementation is not needed. - end - end -end - -def File.binread(fname) - open(fname, 'rb') {|f| - return f.read - } -end - -# for corrupted Windows' stat(2) -def File.dir?(path) - File.directory?((path[-1,1] == '/') ? path : path + '/') -end - - -class ConfigTable - - include Enumerable - - def initialize(rbconfig) - @rbconfig = rbconfig - @items = [] - @table = {} - # options - @install_prefix = nil - @config_opt = nil - @verbose = true - @no_harm = false - end - - attr_accessor :install_prefix - attr_accessor :config_opt - - attr_writer :verbose - - def verbose? - @verbose - end - - attr_writer :no_harm - - def no_harm? - @no_harm - end - - def [](key) - lookup(key).resolve(self) - end - - def []=(key, val) - lookup(key).set val - end - - def names - @items.map {|i| i.name } - end - - def each(&block) - @items.each(&block) - end - - def key?(name) - @table.key?(name) - end - - def lookup(name) - @table[name] or setup_rb_error "no such config item: #{name}" - end - - def add(item) - @items.push item - @table[item.name] = item - end - - def remove(name) - item = lookup(name) - @items.delete_if {|i| i.name == name } - @table.delete_if {|name, i| i.name == name } - item - end - - def load_script(path, inst = nil) - if File.file?(path) - MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path - end - end - - def savefile - '.config' - end - - def load_savefile - begin - File.foreach(savefile()) do |line| - k, v = *line.split(/=/, 2) - self[k] = v.strip - end - rescue Errno::ENOENT - setup_rb_error $!.message + "\n#{File.basename($0)} config first" - end - end - - def save - @items.each {|i| i.value } - File.open(savefile(), 'w') {|f| - @items.each do |i| - f.printf "%s=%s\n", i.name, i.value if i.value? and i.value - end - } - end - - def load_standard_entries - standard_entries(@rbconfig).each do |ent| - add ent - end - end - - def standard_entries(rbconfig) - c = rbconfig - - rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) - - major = c['MAJOR'].to_i - minor = c['MINOR'].to_i - teeny = c['TEENY'].to_i - version = "#{major}.#{minor}" - - # ruby ver. >= 1.4.4? - newpath_p = ((major >= 2) or - ((major == 1) and - ((minor >= 5) or - ((minor == 4) and (teeny >= 4))))) - - if c['rubylibdir'] - # V > 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = c['rubylibdir'] - librubyverarch = c['archdir'] - siteruby = c['sitedir'] - siterubyver = c['sitelibdir'] - siterubyverarch = c['sitearchdir'] - elsif newpath_p - # 1.4.4 <= V <= 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = c['sitedir'] - siterubyver = "$siteruby/#{version}" - siterubyverarch = "$siterubyver/#{c['arch']}" - else - # V < 1.4.4 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" - siterubyver = siteruby - siterubyverarch = "$siterubyver/#{c['arch']}" - end - parameterize = lambda {|path| - path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') - } - - if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } - makeprog = arg.sub(/'/, '').split(/=/, 2)[1] - else - makeprog = 'make' - end - - [ - ExecItem.new('installdirs', 'std/site/home', - 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ - {|val, table| - case val - when 'std' - table['rbdir'] = '$librubyver' - table['sodir'] = '$librubyverarch' - when 'site' - table['rbdir'] = '$siterubyver' - table['sodir'] = '$siterubyverarch' - when 'home' - setup_rb_error '$HOME was not set' unless ENV['HOME'] - table['prefix'] = ENV['HOME'] - table['rbdir'] = '$libdir/ruby' - table['sodir'] = '$libdir/ruby' - end - }, - PathItem.new('prefix', 'path', c['prefix'], - 'path prefix of target environment'), - PathItem.new('bindir', 'path', parameterize.call(c['bindir']), - 'the directory for commands'), - PathItem.new('libdir', 'path', parameterize.call(c['libdir']), - 'the directory for libraries'), - PathItem.new('datadir', 'path', parameterize.call(c['datadir']), - 'the directory for shared data'), - PathItem.new('mandir', 'path', parameterize.call(c['mandir']), - 'the directory for man pages'), - PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), - 'the directory for system configuration files'), - PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), - 'the directory for local state data'), - PathItem.new('libruby', 'path', libruby, - 'the directory for ruby libraries'), - PathItem.new('librubyver', 'path', librubyver, - 'the directory for standard ruby libraries'), - PathItem.new('librubyverarch', 'path', librubyverarch, - 'the directory for standard ruby extensions'), - PathItem.new('siteruby', 'path', siteruby, - 'the directory for version-independent aux ruby libraries'), - PathItem.new('siterubyver', 'path', siterubyver, - 'the directory for aux ruby libraries'), - PathItem.new('siterubyverarch', 'path', siterubyverarch, - 'the directory for aux ruby binaries'), - PathItem.new('rbdir', 'path', '$siterubyver', - 'the directory for ruby scripts'), - PathItem.new('sodir', 'path', '$siterubyverarch', - 'the directory for ruby extentions'), - PathItem.new('rubypath', 'path', rubypath, - 'the path to set to #! line'), - ProgramItem.new('rubyprog', 'name', rubypath, - 'the ruby program using for installation'), - ProgramItem.new('makeprog', 'name', makeprog, - 'the make program to compile ruby extentions'), - SelectItem.new('shebang', 'all/ruby/never', 'ruby', - 'shebang line (#!) editing mode'), - BoolItem.new('without-ext', 'yes/no', 'no', - 'does not compile/install ruby extentions') - ] - end - private :standard_entries - - def load_multipackage_entries - multipackage_entries().each do |ent| - add ent - end - end - - def multipackage_entries - [ - PackageSelectionItem.new('with', 'name,name...', '', 'ALL', - 'package names that you want to install'), - PackageSelectionItem.new('without', 'name,name...', '', 'NONE', - 'package names that you do not want to install') - ] - end - private :multipackage_entries - - ALIASES = { - 'std-ruby' => 'librubyver', - 'stdruby' => 'librubyver', - 'rubylibdir' => 'librubyver', - 'archdir' => 'librubyverarch', - 'site-ruby-common' => 'siteruby', # For backward compatibility - 'site-ruby' => 'siterubyver', # For backward compatibility - 'bin-dir' => 'bindir', - 'bin-dir' => 'bindir', - 'rb-dir' => 'rbdir', - 'so-dir' => 'sodir', - 'data-dir' => 'datadir', - 'ruby-path' => 'rubypath', - 'ruby-prog' => 'rubyprog', - 'ruby' => 'rubyprog', - 'make-prog' => 'makeprog', - 'make' => 'makeprog' - } - - def fixup - ALIASES.each do |ali, name| - @table[ali] = @table[name] - end - @items.freeze - @table.freeze - @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ - end - - def parse_opt(opt) - m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" - m.to_a[1,2] - end - - def dllext - @rbconfig['DLEXT'] - end - - def value_config?(name) - lookup(name).value? - end - - class Item - def initialize(name, template, default, desc) - @name = name.freeze - @template = template - @value = default - @default = default - @description = desc - end - - attr_reader :name - attr_reader :description - - attr_accessor :default - alias help_default default - - def help_opt - "--#{@name}=#{@template}" - end - - def value? - true - end - - def value - @value - end - - def resolve(table) - @value.gsub(%r<\$([^/]+)>) { table[$1] } - end - - def set(val) - @value = check(val) - end - - private - - def check(val) - setup_rb_error "config: --#{name} requires argument" unless val - val - end - end - - class BoolItem < Item - def config_type - 'bool' - end - - def help_opt - "--#{@name}" - end - - private - - def check(val) - return 'yes' unless val - case val - when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' - when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' - else - setup_rb_error "config: --#{@name} accepts only yes/no for argument" - end - end - end - - class PathItem < Item - def config_type - 'path' - end - - private - - def check(path) - setup_rb_error "config: --#{@name} requires argument" unless path - path[0,1] == '$' ? path : File.expand_path(path) - end - end - - class ProgramItem < Item - def config_type - 'program' - end - end - - class SelectItem < Item - def initialize(name, selection, default, desc) - super - @ok = selection.split('/') - end - - def config_type - 'select' - end - - private - - def check(val) - unless @ok.include?(val.strip) - setup_rb_error "config: use --#{@name}=#{@template} (#{val})" - end - val.strip - end - end - - class ExecItem < Item - def initialize(name, selection, desc, &block) - super name, selection, nil, desc - @ok = selection.split('/') - @action = block - end - - def config_type - 'exec' - end - - def value? - false - end - - def resolve(table) - setup_rb_error "$#{name()} wrongly used as option value" - end - - undef set - - def evaluate(val, table) - v = val.strip.downcase - unless @ok.include?(v) - setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" - end - @action.call v, table - end - end - - class PackageSelectionItem < Item - def initialize(name, template, default, help_default, desc) - super name, template, default, desc - @help_default = help_default - end - - attr_reader :help_default - - def config_type - 'package' - end - - private - - def check(val) - unless File.dir?("packages/#{val}") - setup_rb_error "config: no such package: #{val}" - end - val - end - end - - class MetaConfigEnvironment - def initialize(config, installer) - @config = config - @installer = installer - end - - def config_names - @config.names - end - - def config?(name) - @config.key?(name) - end - - def bool_config?(name) - @config.lookup(name).config_type == 'bool' - end - - def path_config?(name) - @config.lookup(name).config_type == 'path' - end - - def value_config?(name) - @config.lookup(name).config_type != 'exec' - end - - def add_config(item) - @config.add item - end - - def add_bool_config(name, default, desc) - @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) - end - - def add_path_config(name, default, desc) - @config.add PathItem.new(name, 'path', default, desc) - end - - def set_config_default(name, default) - @config.lookup(name).default = default - end - - def remove_config(name) - @config.remove(name) - end - - # For only multipackage - def packages - raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer - @installer.packages - end - - # For only multipackage - def declare_packages(list) - raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer - @installer.packages = list - end - end - -end # class ConfigTable - - -# This module requires: #verbose?, #no_harm? -module FileOperations - - def mkdir_p(dirname, prefix = nil) - dirname = prefix + File.expand_path(dirname) if prefix - $stderr.puts "mkdir -p #{dirname}" if verbose? - return if no_harm? - - # Does not check '/', it's too abnormal. - dirs = File.expand_path(dirname).split(%r<(?=/)>) - if /\A[a-z]:\z/i =~ dirs[0] - disk = dirs.shift - dirs[0] = disk + dirs[0] - end - dirs.each_index do |idx| - path = dirs[0..idx].join('') - Dir.mkdir path unless File.dir?(path) - end - end - - def rm_f(path) - $stderr.puts "rm -f #{path}" if verbose? - return if no_harm? - force_remove_file path - end - - def rm_rf(path) - $stderr.puts "rm -rf #{path}" if verbose? - return if no_harm? - remove_tree path - end - - def remove_tree(path) - if File.symlink?(path) - remove_file path - elsif File.dir?(path) - remove_tree0 path - else - force_remove_file path - end - end - - def remove_tree0(path) - Dir.foreach(path) do |ent| - next if ent == '.' - next if ent == '..' - entpath = "#{path}/#{ent}" - if File.symlink?(entpath) - remove_file entpath - elsif File.dir?(entpath) - remove_tree0 entpath - else - force_remove_file entpath - end - end - begin - Dir.rmdir path - rescue Errno::ENOTEMPTY - # directory may not be empty - end - end - - def move_file(src, dest) - force_remove_file dest - begin - File.rename src, dest - rescue - File.open(dest, 'wb') {|f| - f.write File.binread(src) - } - File.chmod File.stat(src).mode, dest - File.unlink src - end - end - - def force_remove_file(path) - begin - remove_file path - rescue - end - end - - def remove_file(path) - File.chmod 0777, path - File.unlink path - end - - def install(from, dest, mode, prefix = nil) - $stderr.puts "install #{from} #{dest}" if verbose? - return if no_harm? - - realdest = prefix ? prefix + File.expand_path(dest) : dest - realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) - str = File.binread(from) - if diff?(str, realdest) - verbose_off { - rm_f realdest if File.exist?(realdest) - } - File.open(realdest, 'wb') {|f| - f.write str - } - File.chmod mode, realdest - - File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| - if prefix - f.puts realdest.sub(prefix, '') - else - f.puts realdest - end - } - end - end - - def diff?(new_content, path) - return true unless File.exist?(path) - new_content != File.binread(path) - end - - def command(*args) - $stderr.puts args.join(' ') if verbose? - system(*args) or raise RuntimeError, - "system(#{args.map{|a| a.inspect }.join(' ')}) failed" - end - - def ruby(*args) - command config('rubyprog'), *args - end - - def make(task = nil) - command(*[config('makeprog'), task].compact) - end - - def extdir?(dir) - File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") - end - - def files_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.file?("#{dir}/#{ent}") } - } - end - - DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) - - def directories_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT - } - end - -end - - -# This module requires: #srcdir_root, #objdir_root, #relpath -module HookScriptAPI - - def get_config(key) - @config[key] - end - - alias config get_config - - # obsolete: use metaconfig to change configuration - def set_config(key, val) - @config[key] = val - end - - # - # srcdir/objdir (works only in the package directory) - # - - def curr_srcdir - "#{srcdir_root()}/#{relpath()}" - end - - def curr_objdir - "#{objdir_root()}/#{relpath()}" - end - - def srcfile(path) - "#{curr_srcdir()}/#{path}" - end - - def srcexist?(path) - File.exist?(srcfile(path)) - end - - def srcdirectory?(path) - File.dir?(srcfile(path)) - end - - def srcfile?(path) - File.file?(srcfile(path)) - end - - def srcentries(path = '.') - Dir.open("#{curr_srcdir()}/#{path}") {|d| - return d.to_a - %w(. ..) - } - end - - def srcfiles(path = '.') - srcentries(path).select {|fname| - File.file?(File.join(curr_srcdir(), path, fname)) - } - end - - def srcdirectories(path = '.') - srcentries(path).select {|fname| - File.dir?(File.join(curr_srcdir(), path, fname)) - } - end - -end - - -class ToplevelInstaller - - Version = '3.4.1' - Copyright = 'Copyright (c) 2000-2005 Minero Aoki' - - TASKS = [ - [ 'all', 'do config, setup, then install' ], - [ 'config', 'saves your configurations' ], - [ 'show', 'shows current configuration' ], - [ 'setup', 'compiles ruby extentions and others' ], - [ 'install', 'installs files' ], - [ 'test', 'run all tests in test/' ], - [ 'clean', "does `make clean' for each extention" ], - [ 'distclean',"does `make distclean' for each extention" ] - ] - - def ToplevelInstaller.invoke - config = ConfigTable.new(load_rbconfig()) - config.load_standard_entries - config.load_multipackage_entries if multipackage? - config.fixup - klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) - klass.new(File.dirname($0), config).invoke - end - - def ToplevelInstaller.multipackage? - File.dir?(File.dirname($0) + '/packages') - end - - def ToplevelInstaller.load_rbconfig - if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } - ARGV.delete(arg) - load File.expand_path(arg.split(/=/, 2)[1]) - $".push 'rbconfig.rb' - else - require 'rbconfig' - end - ::Config::CONFIG - end - - def initialize(ardir_root, config) - @ardir = File.expand_path(ardir_root) - @config = config - # cache - @valid_task_re = nil - end - - def config(key) - @config[key] - end - - def inspect - "#<#{self.class} #{__id__()}>" - end - - def invoke - run_metaconfigs - case task = parsearg_global() - when nil, 'all' - parsearg_config - init_installers - exec_config - exec_setup - exec_install - else - case task - when 'config', 'test' - ; - when 'clean', 'distclean' - @config.load_savefile if File.exist?(@config.savefile) - else - @config.load_savefile - end - __send__ "parsearg_#{task}" - init_installers - __send__ "exec_#{task}" - end - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig" - end - - def init_installers - @installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - # - # Hook Script API bases - # - - def srcdir_root - @ardir - end - - def objdir_root - '.' - end - - def relpath - '.' - end - - # - # Option Parsing - # - - def parsearg_global - while arg = ARGV.shift - case arg - when /\A\w+\z/ - setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) - return arg - when '-q', '--quiet' - @config.verbose = false - when '--verbose' - @config.verbose = true - when '--help' - print_usage $stdout - exit 0 - when '--version' - puts "#{File.basename($0)} version #{Version}" - exit 0 - when '--copyright' - puts Copyright - exit 0 - else - setup_rb_error "unknown global option '#{arg}'" - end - end - nil - end - - def valid_task?(t) - valid_task_re() =~ t - end - - def valid_task_re - @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ - end - - def parsearg_no_options - unless ARGV.empty? - task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) - setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" - end - end - - alias parsearg_show parsearg_no_options - alias parsearg_setup parsearg_no_options - alias parsearg_test parsearg_no_options - alias parsearg_clean parsearg_no_options - alias parsearg_distclean parsearg_no_options - - def parsearg_config - evalopt = [] - set = [] - @config.config_opt = [] - while i = ARGV.shift - if /\A--?\z/ =~ i - @config.config_opt = ARGV.dup - break - end - name, value = *@config.parse_opt(i) - if @config.value_config?(name) - @config[name] = value - else - evalopt.push [name, value] - end - set.push name - end - evalopt.each do |name, value| - @config.lookup(name).evaluate value, @config - end - # Check if configuration is valid - set.each do |n| - @config[n] if @config.value_config?(n) - end - end - - def parsearg_install - @config.no_harm = false - @config.install_prefix = '' - while a = ARGV.shift - case a - when '--no-harm' - @config.no_harm = true - when /\A--prefix=/ - path = a.split(/=/, 2)[1] - path = File.expand_path(path) unless path[0,1] == '/' - @config.install_prefix = path - else - setup_rb_error "install: unknown option #{a}" - end - end - end - - def print_usage(out) - out.puts 'Typical Installation Procedure:' - out.puts " $ ruby #{File.basename $0} config" - out.puts " $ ruby #{File.basename $0} setup" - out.puts " # ruby #{File.basename $0} install (may require root privilege)" - out.puts - out.puts 'Detailed Usage:' - out.puts " ruby #{File.basename $0} " - out.puts " ruby #{File.basename $0} [] []" - - fmt = " %-24s %s\n" - out.puts - out.puts 'Global options:' - out.printf fmt, '-q,--quiet', 'suppress message outputs' - out.printf fmt, ' --verbose', 'output messages verbosely' - out.printf fmt, ' --help', 'print this message' - out.printf fmt, ' --version', 'print version and quit' - out.printf fmt, ' --copyright', 'print copyright and quit' - out.puts - out.puts 'Tasks:' - TASKS.each do |name, desc| - out.printf fmt, name, desc - end - - fmt = " %-24s %s [%s]\n" - out.puts - out.puts 'Options for CONFIG or ALL:' - @config.each do |item| - out.printf fmt, item.help_opt, item.description, item.help_default - end - out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" - out.puts - out.puts 'Options for INSTALL:' - out.printf fmt, '--no-harm', 'only display what to do if given', 'off' - out.printf fmt, '--prefix=path', 'install path prefix', '' - out.puts - end - - # - # Task Handlers - # - - def exec_config - @installer.exec_config - @config.save # must be final - end - - def exec_setup - @installer.exec_setup - end - - def exec_install - @installer.exec_install - end - - def exec_test - @installer.exec_test - end - - def exec_show - @config.each do |i| - printf "%-20s %s\n", i.name, i.value if i.value? - end - end - - def exec_clean - @installer.exec_clean - end - - def exec_distclean - @installer.exec_distclean - end - -end # class ToplevelInstaller - - -class ToplevelInstallerMulti < ToplevelInstaller - - include FileOperations - - def initialize(ardir_root, config) - super - @packages = directories_of("#{@ardir}/packages") - raise 'no package exists' if @packages.empty? - @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig", self - @packages.each do |name| - @config.load_script "#{@ardir}/packages/#{name}/metaconfig" - end - end - - attr_reader :packages - - def packages=(list) - raise 'package list is empty' if list.empty? - list.each do |name| - raise "directory packages/#{name} does not exist"\ - unless File.dir?("#{@ardir}/packages/#{name}") - end - @packages = list - end - - def init_installers - @installers = {} - @packages.each do |pack| - @installers[pack] = Installer.new(@config, - "#{@ardir}/packages/#{pack}", - "packages/#{pack}") - end - with = extract_selection(config('with')) - without = extract_selection(config('without')) - @selected = @installers.keys.select {|name| - (with.empty? or with.include?(name)) \ - and not without.include?(name) - } - end - - def extract_selection(list) - a = list.split(/,/) - a.each do |name| - setup_rb_error "no such package: #{name}" unless @installers.key?(name) - end - a - end - - def print_usage(f) - super - f.puts 'Inluded packages:' - f.puts ' ' + @packages.sort.join(' ') - f.puts - end - - # - # Task Handlers - # - - def exec_config - run_hook 'pre-config' - each_selected_installers {|inst| inst.exec_config } - run_hook 'post-config' - @config.save # must be final - end - - def exec_setup - run_hook 'pre-setup' - each_selected_installers {|inst| inst.exec_setup } - run_hook 'post-setup' - end - - def exec_install - run_hook 'pre-install' - each_selected_installers {|inst| inst.exec_install } - run_hook 'post-install' - end - - def exec_test - run_hook 'pre-test' - each_selected_installers {|inst| inst.exec_test } - run_hook 'post-test' - end - - def exec_clean - rm_f @config.savefile - run_hook 'pre-clean' - each_selected_installers {|inst| inst.exec_clean } - run_hook 'post-clean' - end - - def exec_distclean - rm_f @config.savefile - run_hook 'pre-distclean' - each_selected_installers {|inst| inst.exec_distclean } - run_hook 'post-distclean' - end - - # - # lib - # - - def each_selected_installers - Dir.mkdir 'packages' unless File.dir?('packages') - @selected.each do |pack| - $stderr.puts "Processing the package `#{pack}' ..." if verbose? - Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") - Dir.chdir "packages/#{pack}" - yield @installers[pack] - Dir.chdir '../..' - end - end - - def run_hook(id) - @root_installer.run_hook id - end - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - -end # class ToplevelInstallerMulti - - -class Installer - - FILETYPES = %w( bin lib ext data conf man ) - - include FileOperations - include HookScriptAPI - - def initialize(config, srcroot, objroot) - @config = config - @srcdir = File.expand_path(srcroot) - @objdir = File.expand_path(objroot) - @currdir = '.' - end - - def inspect - "#<#{self.class} #{File.basename(@srcdir)}>" - end - - def noop(rel) - end - - # - # Hook Script API base methods - # - - def srcdir_root - @srcdir - end - - def objdir_root - @objdir - end - - def relpath - @currdir - end - - # - # Config Access - # - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - - def verbose_off - begin - save, @config.verbose = @config.verbose?, false - yield - ensure - @config.verbose = save - end - end - - # - # TASK config - # - - def exec_config - exec_task_traverse 'config' - end - - alias config_dir_bin noop - alias config_dir_lib noop - - def config_dir_ext(rel) - extconf if extdir?(curr_srcdir()) - end - - alias config_dir_data noop - alias config_dir_conf noop - alias config_dir_man noop - - def extconf - ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt - end - - # - # TASK setup - # - - def exec_setup - exec_task_traverse 'setup' - end - - def setup_dir_bin(rel) - files_of(curr_srcdir()).each do |fname| - update_shebang_line "#{curr_srcdir()}/#{fname}" - end - end - - alias setup_dir_lib noop - - def setup_dir_ext(rel) - make if extdir?(curr_srcdir()) - end - - alias setup_dir_data noop - alias setup_dir_conf noop - alias setup_dir_man noop - - def update_shebang_line(path) - return if no_harm? - return if config('shebang') == 'never' - old = Shebang.load(path) - if old - $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 - new = new_shebang(old) - return if new.to_s == old.to_s - else - return unless config('shebang') == 'all' - new = Shebang.new(config('rubypath')) - end - $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? - open_atomic_writer(path) {|output| - File.open(path, 'rb') {|f| - f.gets if old # discard - output.puts new.to_s - output.print f.read - } - } - end - - def new_shebang(old) - if /\Aruby/ =~ File.basename(old.cmd) - Shebang.new(config('rubypath'), old.args) - elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' - Shebang.new(config('rubypath'), old.args[1..-1]) - else - return old unless config('shebang') == 'all' - Shebang.new(config('rubypath')) - end - end - - def open_atomic_writer(path, &block) - tmpfile = File.basename(path) + '.tmp' - begin - File.open(tmpfile, 'wb', &block) - File.rename tmpfile, File.basename(path) - ensure - File.unlink tmpfile if File.exist?(tmpfile) - end - end - - class Shebang - def Shebang.load(path) - line = nil - File.open(path) {|f| - line = f.gets - } - return nil unless /\A#!/ =~ line - parse(line) - end - - def Shebang.parse(line) - cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') - new(cmd, args) - end - - def initialize(cmd, args = []) - @cmd = cmd - @args = args - end - - attr_reader :cmd - attr_reader :args - - def to_s - "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") - end - end - - # - # TASK install - # - - def exec_install - rm_f 'InstalledFiles' - exec_task_traverse 'install' - end - - def install_dir_bin(rel) - install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 - end - - def install_dir_lib(rel) - install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 - end - - def install_dir_ext(rel) - return unless extdir?(curr_srcdir()) - install_files rubyextentions('.'), - "#{config('sodir')}/#{File.dirname(rel)}", - 0555 - end - - def install_dir_data(rel) - install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 - end - - def install_dir_conf(rel) - # FIXME: should not remove current config files - # (rename previous file to .old/.org) - install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 - end - - def install_dir_man(rel) - install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 - end - - def install_files(list, dest, mode) - mkdir_p dest, @config.install_prefix - list.each do |fname| - install fname, dest, mode, @config.install_prefix - end - end - - def libfiles - glob_reject(%w(*.y *.output), targetfiles()) - end - - def rubyextentions(dir) - ents = glob_select("*.#{@config.dllext}", targetfiles()) - if ents.empty? - setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" - end - ents - end - - def targetfiles - mapdir(existfiles() - hookfiles()) - end - - def mapdir(ents) - ents.map {|ent| - if File.exist?(ent) - then ent # objdir - else "#{curr_srcdir()}/#{ent}" # srcdir - end - } - end - - # picked up many entries from cvs-1.11.1/src/ignore.c - JUNK_FILES = %w( - core RCSLOG tags TAGS .make.state - .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb - *~ *.old *.bak *.BAK *.orig *.rej _$* *$ - - *.org *.in .* - ) - - def existfiles - glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) - end - - def hookfiles - %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| - %w( config setup install clean ).map {|t| sprintf(fmt, t) } - }.flatten - end - - def glob_select(pat, ents) - re = globs2re([pat]) - ents.select {|ent| re =~ ent } - end - - def glob_reject(pats, ents) - re = globs2re(pats) - ents.reject {|ent| re =~ ent } - end - - GLOB2REGEX = { - '.' => '\.', - '$' => '\$', - '#' => '\#', - '*' => '.*' - } - - def globs2re(pats) - /\A(?:#{ - pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') - })\z/ - end - - # - # TASK test - # - - TESTDIR = 'test' - - def exec_test - unless File.directory?('test') - $stderr.puts 'no test in this package' if verbose? - return - end - $stderr.puts 'Running tests...' if verbose? - begin - require 'test/unit' - rescue LoadError - setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' - end - runner = Test::Unit::AutoRunner.new(true) - runner.to_run << TESTDIR - runner.run - end - - # - # TASK clean - # - - def exec_clean - exec_task_traverse 'clean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias clean_dir_bin noop - alias clean_dir_lib noop - alias clean_dir_data noop - alias clean_dir_conf noop - alias clean_dir_man noop - - def clean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'clean' if File.file?('Makefile') - end - - # - # TASK distclean - # - - def exec_distclean - exec_task_traverse 'distclean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias distclean_dir_bin noop - alias distclean_dir_lib noop - - def distclean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'distclean' if File.file?('Makefile') - end - - alias distclean_dir_data noop - alias distclean_dir_conf noop - alias distclean_dir_man noop - - # - # Traversing - # - - def exec_task_traverse(task) - run_hook "pre-#{task}" - FILETYPES.each do |type| - if type == 'ext' and config('without-ext') == 'yes' - $stderr.puts 'skipping ext/* by user option' if verbose? - next - end - traverse task, type, "#{task}_dir_#{type}" - end - run_hook "post-#{task}" - end - - def traverse(task, rel, mid) - dive_into(rel) { - run_hook "pre-#{task}" - __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') - directories_of(curr_srcdir()).each do |d| - traverse task, "#{rel}/#{d}", mid - end - run_hook "post-#{task}" - } - end - - def dive_into(rel) - return unless File.dir?("#{@srcdir}/#{rel}") - - dir = File.basename(rel) - Dir.mkdir dir unless File.dir?(dir) - prevdir = Dir.pwd - Dir.chdir dir - $stderr.puts '---> ' + rel if verbose? - @currdir = rel - yield - Dir.chdir prevdir - $stderr.puts '<--- ' + rel if verbose? - @currdir = File.dirname(rel) - end - - def run_hook(id) - path = [ "#{curr_srcdir()}/#{id}", - "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } - return unless path - begin - instance_eval File.read(path), path, 1 - rescue - raise if $DEBUG - setup_rb_error "hook #{path} failed:\n" + $!.message - end - end - -end # class Installer - - -class SetupError < StandardError; end - -def setup_rb_error(msg) - raise SetupError, msg -end - -if $0 == __FILE__ - begin - ToplevelInstaller.invoke - rescue SetupError - raise if $DEBUG - $stderr.puts $!.message - $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." - exit 1 - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/lib_read_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/lib_read_write.rb deleted file mode 100644 index cac87b7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/lib_read_write.rb +++ /dev/null @@ -1,483 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'io/nonblock' -require 'digest/sha1' -require 'fileutils' -$-w = true -require 'kgio' - -module LibReadWriteTest - RANDOM_BLOB = File.open("/dev/urandom") { |fp| fp.read(10 * 1024 * 1024) } - - def teardown - @rd.close if defined?(@rd) && ! @rd.closed? - @wr.close if defined?(@wr) && ! @wr.closed? - FileUtils.remove_entry_secure(@tmpdir) if defined?(@tmpdir) - end - - def test_write_empty - assert_nil @wr.kgio_write("") - end - - def test_trywrite_empty - assert_nil @wr.kgio_trywrite("") - end - - def test_writev_empty - assert_nil @wr.kgio_writev([]) - end - - def test_trywritev_empty - assert_nil @wr.kgio_trywritev([]) - end - - def test_read_zero - assert_equal "", @rd.kgio_read(0) - buf = "foo" - assert_equal buf.object_id, @rd.kgio_read(0, buf).object_id - assert_equal "", buf - end - - def test_read_shared - a = "." * 0x1000 - b = a.dup - @wr.syswrite "a" - assert_equal "a", @rd.kgio_read(0x1000, a) - assert_equal "a", a - assert_equal "." * 0x1000, b - end - - def test_read_shared_2 - a = "." * 0x1000 - b = a.dup - @wr.syswrite "a" - assert_equal "a", @rd.kgio_read(0x1000, b) - assert_equal "a", b - assert_equal "." * 0x1000, a - end - - def test_tryread_zero - assert_equal "", @rd.kgio_tryread(0) - buf = "foo" - assert_equal buf.object_id, @rd.kgio_tryread(0, buf).object_id - assert_equal "", buf - end - - def test_tryread_shared - a = "." * 0x1000 - b = a.dup - @wr.syswrite("a") - IO.select([@rd]) # this seems needed on FreeBSD 9.0 - assert_equal "a", @rd.kgio_tryread(0x1000, b) - assert_equal "a", b - assert_equal "." * 0x1000, a - end - - def test_tryread_shared_2 - a = "." * 0x1000 - b = a.dup - @wr.syswrite("a") - IO.select([@rd]) # this seems needed on FreeBSD 9.0 - assert_equal "a", @rd.kgio_tryread(0x1000, a) - assert_equal "a", a - assert_equal "." * 0x1000, b - end - - def test_read_eof - @wr.close - assert_nil @rd.kgio_read(5) - end - - def test_read_bang_eof - @wr.close - begin - @rd.kgio_read!(5) - assert false, "should never get here (line:#{__LINE__})" - rescue EOFError => e - assert_equal [], e.backtrace - end - end - - def test_tryread_eof - @wr.close - IO.select([@rd]) # this seems needed on FreeBSD 9.0 - assert_nil @rd.kgio_tryread(5) - end - - def test_write_closed - @rd.close - begin - loop { @wr.kgio_write "HI" } - rescue Errno::EPIPE, Errno::ECONNRESET => e - assert_equal [], e.backtrace - return - end - assert false, "should never get here (line:#{__LINE__})" - end - - def test_trywrite_closed - @rd.close - begin - loop { @wr.kgio_trywrite "HI" } - rescue Errno::EPIPE, Errno::ECONNRESET => e - assert_equal [], e.backtrace - return - end - assert false, "should never get here (line:#{__LINE__})" - end - - def test_writev_closed - @rd.close - begin - loop { @wr.kgio_writev ["HI"] } - rescue Errno::EPIPE, Errno::ECONNRESET => e - assert_equal [], e.backtrace - return - end - assert false, "should never get here (line:#{__LINE__})" - end - - def test_trywritev_closed - @rd.close - begin - loop { @wr.kgio_trywritev ["HI"] } - rescue Errno::EPIPE, Errno::ECONNRESET => e - assert_equal [], e.backtrace - return - end - assert false, "should never get here (line:#{__LINE__})" - end - - def test_trywrite_full - buf = "\302\251" * 1024 * 1024 - buf2 = "" - dig = Digest::SHA1.new - t = Thread.new do - sleep 1 - nr = 0 - begin - dig.update(@rd.readpartial(4096, buf2)) - nr += buf2.size - rescue EOFError - break - rescue => e - end while true - dig.hexdigest - end - 50.times do - wr = buf - begin - rv = @wr.kgio_trywrite(wr) - case rv - when String - wr = rv - when :wait_readable - assert false, "should never get here line=#{__LINE__}" - when :wait_writable - IO.select(nil, [ @wr ]) - else - wr = false - end - end while wr - end - @wr.close - t.join - assert_equal '8ff79d8115f9fe38d18be858c66aa08a1cc27a66', t.value - end - - def test_trywritev_full - buf = ["\302\251" * 128] * 8 * 1024 - buf2 = "" - dig = Digest::SHA1.new - t = Thread.new do - sleep 1 - nr = 0 - begin - dig.update(@rd.readpartial(4096, buf2)) - nr += buf2.size - rescue EOFError - break - rescue => e - end while true - dig.hexdigest - end - 50.times do - wr = buf - begin - rv = @wr.kgio_trywritev(wr) - case rv - when Array - wr = rv - when :wait_readable - assert false, "should never get here line=#{__LINE__}" - when :wait_writable - IO.select(nil, [ @wr ]) - else - wr = false - end - end while wr - end - @wr.close - t.join - assert_equal '8ff79d8115f9fe38d18be858c66aa08a1cc27a66', t.value - end - - def test_write_conv - assert_equal nil, @wr.kgio_write(10) - assert_equal "10", @rd.kgio_read(2) - end - - def test_trywrite_conv - assert_equal nil, @wr.kgio_trywrite(10) - IO.select([@rd]) # this seems needed on FreeBSD 9.0 - assert_equal "10", @rd.kgio_tryread(2) - end - - def test_tryread_empty - assert_equal :wait_readable, @rd.kgio_tryread(1) - end - - def test_read_too_much - assert_equal nil, @wr.kgio_write("hi") - assert_equal "hi", @rd.kgio_read(4) - end - - def test_tryread_too_much - assert_equal nil, @wr.kgio_trywrite("hi") - assert_equal @rd, @rd.kgio_wait_readable - assert_equal "hi", @rd.kgio_tryread(4) - end - - def test_read_short - assert_equal nil, @wr.kgio_write("hi") - assert_equal "h", @rd.kgio_read(1) - assert_equal "i", @rd.kgio_read(1) - end - - def test_tryread_short - assert_equal nil, @wr.kgio_trywrite("hi") - IO.select([@rd]) # this seems needed on FreeBSD 9.0 - assert_equal "h", @rd.kgio_tryread(1) - assert_equal "i", @rd.kgio_tryread(1) - end - - def test_read_extra_buf - tmp = "" - tmp_object_id = tmp.object_id - assert_equal nil, @wr.kgio_write("hi") - rv = @rd.kgio_read(2, tmp) - assert_equal "hi", rv - assert_equal rv.object_id, tmp.object_id - assert_equal tmp_object_id, rv.object_id - end - - def test_trywrite_return_wait_writable - tmp = [] - tmp << @wr.kgio_trywrite("HI") until tmp[-1] == :wait_writable - assert :wait_writable === tmp[-1] - assert(!(:wait_readable === tmp[-1])) - assert_equal :wait_writable, tmp.pop - assert tmp.size > 0 - penultimate = tmp.pop - assert(penultimate == "I" || penultimate == nil) - assert tmp.size > 0 - tmp.each { |count| assert_equal nil, count } - end - - def test_trywritev_return_wait_writable - tmp = [] - tmp << @wr.kgio_trywritev(["HI"]) until tmp[-1] == :wait_writable - assert :wait_writable === tmp[-1] - assert(!(:wait_readable === tmp[-1])) - assert_equal :wait_writable, tmp.pop - assert tmp.size > 0 - penultimate = tmp.pop - assert(penultimate == "I" || penultimate == nil) - assert tmp.size > 0 - tmp.each { |count| assert_equal nil, count } - end - - def test_tryread_extra_buf_eagain_clears_buffer - tmp = "hello world" - rv = @rd.kgio_tryread(2, tmp) - assert_equal :wait_readable, rv - assert_equal "", tmp - end - - def test_tryread_extra_buf_eof_clears_buffer - tmp = "hello world" - @wr.close - IO.select([@rd]) # this seems needed on FreeBSD 9.0 - assert_nil @rd.kgio_tryread(2, tmp) - assert_equal "", tmp - end - - def test_monster_trywrite - buf = RANDOM_BLOB.dup - rv = @wr.kgio_trywrite(buf) - assert_kind_of String, rv - assert rv.size < buf.size - @rd.nonblock = false - assert_equal(buf, @rd.read(buf.size - rv.size) + rv) - end - - def test_monster_write - buf = RANDOM_BLOB.dup - thr = Thread.new { @wr.kgio_write(buf) } - @rd.nonblock = false - readed = @rd.read(buf.size) - thr.join - assert_nil thr.value - assert_equal buf, readed - end - - def test_monster_trywritev - buf, start = [], 0 - while start < RANDOM_BLOB.size - s = RANDOM_BLOB[start, 1000] - start += s.size - buf << s - end - rv = @wr.kgio_trywritev(buf) - assert_kind_of Array, rv - rv = rv.join - assert rv.size < RANDOM_BLOB.size - @rd.nonblock = false - assert_equal(RANDOM_BLOB, @rd.read(RANDOM_BLOB.size - rv.size) + rv) - end - - def test_monster_writev - buf, start = [], 0 - while start < RANDOM_BLOB.size - s = RANDOM_BLOB[start, 10000] - start += s.size - buf << s - end - thr = Thread.new { @wr.kgio_writev(buf) } - @rd.nonblock = false - readed = @rd.read(RANDOM_BLOB.size) - thr.join - assert_nil thr.value - e = (RANDOM_BLOB == readed) - assert e - end - - def test_monster_write_wait_writable - @wr.instance_variable_set :@nr, 0 - def @wr.kgio_wait_writable - @nr += 1 - IO.select(nil, [self]) - end - buf = "." * 1024 * 1024 * 10 - thr = Thread.new { @wr.kgio_write(buf) } - Thread.pass until thr.stop? - readed = @rd.read(buf.size) - thr.join - assert_nil thr.value - assert_equal buf, readed - assert @wr.instance_variable_get(:@nr) > 0 - end - - def test_monster_writev_wait_writable - @wr.instance_variable_set :@nr, 0 - def @wr.kgio_wait_writable - @nr += 1 - IO.select(nil, [self]) - end - buf = ["." * 1024] * 1024 * 10 - buf_size = buf.inject(0){|c, s| c + s.size} - thr = Thread.new { @wr.kgio_writev(buf) } - Thread.pass until thr.stop? - readed = @rd.read(buf_size) - thr.join - assert_nil thr.value - e = (buf.join == readed) - assert e - assert @wr.instance_variable_get(:@nr) > 0 - end - - def test_wait_readable_ruby_default - elapsed = 0 - foo = nil - t0 = Time.now - thr = Thread.new { sleep 1; @wr.write "HELLO" } - foo = @rd.kgio_read(5) - elapsed = Time.now - t0 - assert elapsed >= 1.0, "elapsed: #{elapsed}" - assert_equal "HELLO", foo - thr.join - assert_equal 5, thr.value - end - - def test_wait_writable_ruby_default - buf = "." * 512 - nr = 0 - begin - nr += @wr.write_nonblock(buf) - rescue Errno::EAGAIN - break - end while true - elapsed = 0 - foo = nil - t0 = Time.now - thr = Thread.new { sleep 1; @rd.read(nr) } - foo = @wr.kgio_write("HELLO") - elapsed = Time.now - t0 - - assert_nil foo - if @wr.stat.pipe? - assert elapsed >= 1.0, "elapsed: #{elapsed}" - end - assert(String === foo || foo == nil) - assert_kind_of String, thr.value - end - - def test_wait_readable_method - def @rd.kgio_wait_readable - defined?(@z) ? raise(RuntimeError, "Hello") : @z = "HI" - end - foo = nil - begin - foo = @rd.kgio_read(5) - assert false - rescue RuntimeError => e - assert_equal("Hello", e.message) - end - assert_equal "HI", @rd.instance_variable_get(:@z) - assert_nil foo - end - - def test_tryread_wait_readable_method - def @rd.kgio_wait_readable - raise "Hello" - end - assert_equal :wait_readable, @rd.kgio_tryread(5) - end - - def test_trywrite_wait_readable_method - def @wr.kgio_wait_writable - raise "Hello" - end - buf = "." * 4096 - rv = nil - until rv == :wait_writable - rv = @wr.kgio_trywrite(buf) - end - assert_equal :wait_writable, rv - end - - def test_wait_writable_method - def @wr.kgio_wait_writable - defined?(@z) ? raise(RuntimeError, "Hello") : @z = "HI" - end - n = [] - begin - loop { n << @wr.kgio_write("HIHIHIHIHIHI") } - assert false - rescue RuntimeError => e - assert_equal("Hello", e.message) - end - assert n.size > 0 - assert_equal "HI", @wr.instance_variable_get(:@z) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/lib_server_accept.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/lib_server_accept.rb deleted file mode 100644 index db0d120..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/lib_server_accept.rb +++ /dev/null @@ -1,89 +0,0 @@ -require 'test/unit' -require 'fcntl' -require 'io/nonblock' -require 'fileutils' -$-w = true -require 'kgio' - -module LibServerAccept - - def teardown - @srv.close unless @srv.closed? - FileUtils.remove_entry_secure(@tmpdir) if defined?(@tmpdir) - Kgio.accept_cloexec = true - Kgio.accept_nonblock = false - end - - def test_tryaccept_success - a = client_connect - IO.select([@srv]) - b = @srv.kgio_tryaccept - assert_kind_of Kgio::Socket, b - assert_equal @host, b.kgio_addr - end - - def test_tryaccept_flags - a = client_connect - IO.select([@srv]) - b = @srv.kgio_tryaccept nil, 0 - assert_kind_of Kgio::Socket, b - assert_equal 0, b.fcntl(Fcntl::F_GETFD) - end - - def test_blocking_accept_flags - a = client_connect - IO.select([@srv]) - b = @srv.kgio_accept nil, 0 - assert_kind_of Kgio::Socket, b - assert_equal 0, b.fcntl(Fcntl::F_GETFD) - end - - def test_tryaccept_fail - assert_equal nil, @srv.kgio_tryaccept - end - - def test_blocking_accept - t0 = Time.now - pid = fork { sleep 1; a = client_connect; sleep } - b = @srv.kgio_accept - elapsed = Time.now - t0 - assert_kind_of Kgio::Socket, b - assert_equal @host, b.kgio_addr - Process.kill(:KILL, pid) - Process.waitpid(pid) - assert elapsed >= 1, "elapsed: #{elapsed}" - end - - def test_blocking_accept_with_nonblock_socket - @srv.nonblock = true - t0 = Time.now - pid = fork { sleep 1; a = client_connect; sleep } - b = @srv.kgio_accept - elapsed = Time.now - t0 - assert_kind_of Kgio::Socket, b - assert_equal @host, b.kgio_addr - Process.kill(:KILL, pid) - Process.waitpid(pid) - assert elapsed >= 1, "elapsed: #{elapsed}" - - t0 = Time.now - pid = fork { sleep 6; a = client_connect; sleep } - b = @srv.kgio_accept - elapsed = Time.now - t0 - assert_kind_of Kgio::Socket, b - assert_equal @host, b.kgio_addr - Process.kill(:KILL, pid) - Process.waitpid(pid) - assert elapsed >= 6, "elapsed: #{elapsed}" - - t0 = Time.now - pid = fork { sleep 1; a = client_connect; sleep } - b = @srv.kgio_accept - elapsed = Time.now - t0 - assert_kind_of Kgio::Socket, b - assert_equal @host, b.kgio_addr - Process.kill(:KILL, pid) - Process.waitpid(pid) - assert elapsed >= 1, "elapsed: #{elapsed}" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_accept_class.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_accept_class.rb deleted file mode 100644 index 0e1d172..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_accept_class.rb +++ /dev/null @@ -1,62 +0,0 @@ -require 'test/unit' -require 'io/nonblock' -$-w = true -require 'kgio' - -class TestAcceptClass < Test::Unit::TestCase - class FooSocket < Kgio::Socket - end - - def setup - assert_equal Kgio::Socket, Kgio.accept_class - end - - def teardown - Kgio.accept_class = nil - assert_equal Kgio::Socket, Kgio.accept_class - end - - def test_tcp_socket - Kgio.accept_class = Kgio::TCPSocket - assert_equal Kgio::TCPSocket, Kgio.accept_class - end - - def test_invalid - assert_raises(TypeError) { Kgio.accept_class = TCPSocket } - assert_equal Kgio::Socket, Kgio.accept_class - end - - def test_accepted_class - @host = ENV["TEST_HOST"] || '127.0.0.1' - @srv = Kgio::TCPServer.new(@host, 0) - @port = @srv.addr[1] - - Kgio.accept_class = Kgio::TCPSocket - client = TCPSocket.new(@host, @port) - assert_instance_of Kgio::TCPSocket, @srv.kgio_accept - client = TCPSocket.new(@host, @port) - IO.select([@srv]) - assert_instance_of Kgio::TCPSocket, @srv.kgio_tryaccept - - Kgio.accept_class = nil - client = TCPSocket.new(@host, @port) - assert_instance_of Kgio::Socket, @srv.kgio_accept - client = TCPSocket.new(@host, @port) - IO.select([@srv]) - assert_instance_of Kgio::Socket, @srv.kgio_tryaccept - - Kgio.accept_class = Kgio::UNIXSocket - client = TCPSocket.new(@host, @port) - assert_instance_of Kgio::UNIXSocket, @srv.kgio_accept - client = TCPSocket.new(@host, @port) - IO.select([@srv]) - assert_instance_of Kgio::UNIXSocket, @srv.kgio_tryaccept - - client = TCPSocket.new(@host, @port) - assert_instance_of FooSocket, @srv.kgio_accept(FooSocket) - - client = TCPSocket.new(@host, @port) - IO.select([@srv]) - assert_instance_of FooSocket, @srv.kgio_tryaccept(FooSocket) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_accept_flags.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_accept_flags.rb deleted file mode 100644 index 0f21adf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_accept_flags.rb +++ /dev/null @@ -1,45 +0,0 @@ -require 'test/unit' -require 'fcntl' -require 'io/nonblock' -$-w = true -require 'kgio' - -class TestAcceptFlags < Test::Unit::TestCase - def test_accept_flags - @host = ENV["TEST_HOST"] || '127.0.0.1' - @srv = Kgio::TCPServer.new(@host, 0) - @port = @srv.addr[1] - - client = TCPSocket.new(@host, @port) - accepted = @srv.kgio_accept(nil, Kgio::SOCK_NONBLOCK) - assert_instance_of Kgio::Socket, accepted - flags = accepted.fcntl(Fcntl::F_GETFD) - assert_equal 0, flags & Fcntl::FD_CLOEXEC - assert_nil client.close - assert_nil accepted.close - - client = TCPSocket.new(@host, @port) - accepted = @srv.kgio_accept(nil, Kgio::SOCK_CLOEXEC) - assert_instance_of Kgio::Socket, accepted - flags = accepted.fcntl(Fcntl::F_GETFD) - assert_equal Fcntl::FD_CLOEXEC, flags & Fcntl::FD_CLOEXEC - assert_nil client.close - assert_nil accepted.close - - client = TCPSocket.new(@host, @port) - accepted = @srv.kgio_accept(nil, Kgio::SOCK_CLOEXEC|Kgio::SOCK_NONBLOCK) - assert_instance_of Kgio::Socket, accepted - flags = accepted.fcntl(Fcntl::F_GETFD) - assert_equal Fcntl::FD_CLOEXEC, flags & Fcntl::FD_CLOEXEC - assert_nil client.close - assert_nil accepted.close - - client = TCPSocket.new(@host, @port) - accepted = @srv.kgio_accept(nil, Kgio::SOCK_CLOEXEC|Kgio::SOCK_NONBLOCK) - assert_instance_of Kgio::Socket, accepted - flags = accepted.fcntl(Fcntl::F_GETFD) - assert_equal Fcntl::FD_CLOEXEC, flags & Fcntl::FD_CLOEXEC - assert_nil client.close - assert_nil accepted.close - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_autopush.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_autopush.rb deleted file mode 100644 index 38b7c52..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_autopush.rb +++ /dev/null @@ -1,165 +0,0 @@ -require 'tempfile' -require 'test/unit' -begin - $-w = false - RUBY_PLATFORM =~ /linux/ and require 'strace' -rescue LoadError -end -$-w = true -require 'kgio' - -class TestAutopush < Test::Unit::TestCase - TCP_CORK = 3 - TCP_NOPUSH = 4 - - def setup - Kgio.autopush = false - assert_equal false, Kgio.autopush? - - @host = ENV["TEST_HOST"] || '127.0.0.1' - @srv = Kgio::TCPServer.new(@host, 0) - RUBY_PLATFORM =~ /linux/ and - @srv.setsockopt(Socket::IPPROTO_TCP, TCP_CORK, 1) - RUBY_PLATFORM =~ /freebsd/ and - @srv.setsockopt(Socket::IPPROTO_TCP, TCP_NOPUSH, 1) - @port = @srv.addr[1] - end - - def test_autopush_accessors - Kgio.autopush = true - opt = RUBY_PLATFORM =~ /freebsd/ ? TCP_NOPUSH : TCP_CORK - s = Kgio::TCPSocket.new(@host, @port) - assert_equal 0, s.getsockopt(Socket::IPPROTO_TCP, opt).unpack('i')[0] - assert ! s.kgio_autopush? - s.kgio_autopush = true - assert s.kgio_autopush? - s.kgio_write 'asdf' - assert_equal :wait_readable, s.kgio_tryread(1) - assert s.kgio_autopush? - val = s.getsockopt(Socket::IPPROTO_TCP, opt).unpack('i')[0] - assert_operator val, :>, 0, "#{opt}=#{val} (#{RUBY_PLATFORM})" - end - - def test_autopush_true_unix - Kgio.autopush = true - tmp = Tempfile.new('kgio_unix') - @path = tmp.path - tmp.close! - @srv = Kgio::UNIXServer.new(@path) - @rd = Kgio::UNIXSocket.new(@path) - t0 = nil - if defined?(Strace) - io, err = Strace.me { @wr = @srv.kgio_accept } - assert_nil err - rc = nil - io, err = Strace.me { - t0 = Time.now - @wr.kgio_write "HI\n" - rc = @wr.kgio_tryread 666 - } - assert_nil err - lines = io.readlines - assert lines.grep(/TCP_CORK/).empty?, lines.inspect - else - @wr = @srv.kgio_accept - t0 = Time.now - @wr.kgio_write "HI\n" - rc = @wr.kgio_tryread 666 - end - assert_equal "HI\n", @rd.kgio_read(3) - diff = Time.now - t0 - assert(diff < 0.200, "nopush on UNIX sockets? diff=#{diff} > 200ms") - assert_equal :wait_readable, rc - ensure - File.unlink(@path) rescue nil - end - - def test_autopush_false - Kgio.autopush = nil - assert_equal false, Kgio.autopush? - - @wr = Kgio::TCPSocket.new(@host, @port) - if defined?(Strace) - io, err = Strace.me { @rd = @srv.kgio_accept } - assert_nil err - lines = io.readlines - assert lines.grep(/TCP_CORK/).empty?, lines.inspect - assert_equal 1, @rd.getsockopt(Socket::SOL_TCP, TCP_CORK).unpack("i")[0] - else - @rd = @srv.kgio_accept - end - - rbuf = "..." - t0 = Time.now - @rd.kgio_write "HI\n" - @wr.kgio_read(3, rbuf) - diff = Time.now - t0 - assert(diff >= 0.190, "nopush broken? diff=#{diff} > 200ms") - assert_equal "HI\n", rbuf - end - - def test_autopush_true - Kgio.autopush = true - assert_equal true, Kgio.autopush? - @wr = Kgio::TCPSocket.new(@host, @port) - - if defined?(Strace) - io, err = Strace.me { @rd = @srv.kgio_accept } - assert_nil err - lines = io.readlines - assert_equal 1, lines.grep(/TCP_CORK/).size, lines.inspect - assert_equal 1, @rd.getsockopt(Socket::SOL_TCP, TCP_CORK).unpack("i")[0] - else - @rd = @srv.kgio_accept - end - - @wr.write "HI\n" - rbuf = "" - if defined?(Strace) - io, err = Strace.me { @rd.kgio_read(3, rbuf) } - assert_nil err - lines = io.readlines - assert lines.grep(/TCP_CORK/).empty?, lines.inspect - assert_equal "HI\n", rbuf - else - assert_equal "HI\n", @rd.kgio_read(3, rbuf) - end - - t0 = Time.now - @rd.kgio_write "HI2U2\n" - @rd.kgio_write "HOW\n" - rc = false - - if defined?(Strace) - io, err = Strace.me { rc = @rd.kgio_tryread(666) } - else - rc = @rd.kgio_tryread(666) - end - - @wr.readpartial(666, rbuf) - rbuf == "HI2U2\nHOW\n" or warn "rbuf=#{rbuf.inspect} looking bad?" - diff = Time.now - t0 - assert(diff < 0.200, "time diff=#{diff} >= 200ms") - assert_equal :wait_readable, rc - if defined?(Strace) - assert_nil err - lines = io.readlines - assert_equal 2, lines.grep(/TCP_CORK/).size, lines.inspect - end - @wr.close - @rd.close - - @wr = Kgio::TCPSocket.new(@host, @port) - if defined?(Strace) - io, err = Strace.me { @rd = @srv.kgio_accept } - assert_nil err - lines = io.readlines - assert lines.grep(/TCP_CORK/).empty?,"optimization fail: #{lines.inspect}" - assert_equal 1, @rd.getsockopt(Socket::SOL_TCP, TCP_CORK).unpack("i")[0] - end - end - - def teardown - Kgio.autopush = false - end -end if RUBY_PLATFORM =~ /linux|freebsd/ diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_connect_fd_leak.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_connect_fd_leak.rb deleted file mode 100644 index 1dfc4cd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_connect_fd_leak.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'test/unit' -require 'io/nonblock' -$-w = true -require 'kgio' - -class TestConnectFDLeak < Test::Unit::TestCase - - def test_unix_socket - nr = 0 - path = "/non/existent/path" - assert(! File.exist?(path), "#{path} should not exist") - begin - sock = Kgio::UNIXSocket.new(path) - rescue Errno::ENOENT - end while (nr += 1) < 10000 - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_cross_thread_close.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_cross_thread_close.rb deleted file mode 100644 index 05c32de..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_cross_thread_close.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'test/unit' -$-w = true -require 'kgio' - -class TestCrossThreadClose < Test::Unit::TestCase - - def test_cross_thread_close - host = ENV["TEST_HOST"] || '127.0.0.1' - srv = Kgio::TCPServer.new(host, 0) - thr = Thread.new do - begin - srv.kgio_accept - rescue => e - e - end - end - sleep(0.1) until thr.stop? - srv.close - unless defined?(RUBY_ENGINE) && RUBY_ENGINE == "ruby" && - RUBY_VERSION == "1.9.3" - thr.run rescue nil - end - thr.join - assert_kind_of IOError, thr.value - end -end if defined?(RUBY_ENGINE) && RUBY_ENGINE == "ruby" diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_default_wait.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_default_wait.rb deleted file mode 100644 index 7137d0c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_default_wait.rb +++ /dev/null @@ -1,45 +0,0 @@ -require 'test/unit' -require 'io/nonblock' -$-w = true -require 'kgio' - -class TestDefaultWait < Test::Unit::TestCase - - def test_socket_pair - a, b = Kgio::UNIXSocket.pair - assert_equal a, a.kgio_wait_writable - a.syswrite('.') - assert_equal b, b.kgio_wait_readable - end - - def test_pipe - a, b = Kgio::Pipe.new - assert_equal b, b.kgio_wait_writable - b.syswrite('.') - assert_equal a, a.kgio_wait_readable - end - - def test_wait_readable_timed - a, b = Kgio::Pipe.new - t0 = Time.now - assert_nil a.kgio_wait_readable(1.1) - diff = Time.now - t0 - assert_in_delta diff, 1.1, 0.2 - - b.kgio_write '.' - assert_equal a, a.kgio_wait_readable(1.1) - end - - def test_wait_writable_timed - a, b = Kgio::Pipe.new - buf = "*" * 65536 - true until Symbol === b.kgio_trywrite(buf) - t0 = Time.now - assert_nil b.kgio_wait_writable(1.1) - diff = Time.now - t0 - assert_in_delta diff, 1.1, 0.2 - - a.kgio_read(16384) - assert_equal b, b.kgio_wait_writable(1.1) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_kgio_addr.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_kgio_addr.rb deleted file mode 100644 index 8650f5e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_kgio_addr.rb +++ /dev/null @@ -1,19 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -$-w = true -require 'kgio' - -class TestKgioAddr < Test::Unit::TestCase - def test_tcp - addr = ENV["TEST_HOST"] || '127.0.0.1' - tcp = TCPServer.new(addr, 0) - port = tcp.addr[1] - client = Kgio::TCPSocket.new(addr, port) - accepted = tcp.accept - assert ! accepted.instance_eval { defined?(@kgio_addr) } - accepted.extend Kgio::SocketMethods - s = accepted.kgio_addr! - assert_equal addr, s - assert_equal addr, accepted.instance_variable_get(:@kgio_addr) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_no_dns_on_tcp_connect.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_no_dns_on_tcp_connect.rb deleted file mode 100644 index d296826..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_no_dns_on_tcp_connect.rb +++ /dev/null @@ -1,13 +0,0 @@ -require 'test/unit' -$-w = true -require 'kgio' - -class TestNoDnsOnTcpConnect < Test::Unit::TestCase - def test_connect_remote - assert_raises(ArgumentError) { Kgio::TCPSocket.new("example.com", 666) } - end - - def test_connect_localhost - assert_raises(ArgumentError) { Kgio::TCPSocket.new("localhost", 666) } - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_peek.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_peek.rb deleted file mode 100644 index 9d4475d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_peek.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'test/unit' -$-w = true -require 'kgio' - -class TestPeek < Test::Unit::TestCase - class EIEIO < Errno::EIO - end - - def teardown - @rd.close - @wr.close - end - - def test_peek - @rd, @wr = Kgio::UNIXSocket.pair - @wr.kgio_write "HELLO" - assert_equal "HELLO", @rd.kgio_peek(5) - assert_equal "HELLO", @rd.kgio_trypeek(5) - assert_equal "HELLO", @rd.kgio_read(5) - assert_equal :wait_readable, @rd.kgio_trypeek(5) - def @rd.kgio_wait_readable - raise EIEIO - end - assert_raises(EIEIO) { @rd.kgio_peek(5) } - end - - def test_peek_singleton - @rd, @wr = UNIXSocket.pair - @wr.syswrite "HELLO" - assert_equal "HELLO", Kgio.trypeek(@rd, 666) - assert_equal "HELLO", Kgio.trypeek(@rd, 666) - assert_equal "HELLO", Kgio.tryread(@rd, 666) - assert_equal :wait_readable, Kgio.trypeek(@rd, 5) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_pipe_popen.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_pipe_popen.rb deleted file mode 100644 index bfd18be..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_pipe_popen.rb +++ /dev/null @@ -1,14 +0,0 @@ -require 'test/unit' -require 'io/nonblock' -$-w = true -require 'kgio' - -class TestPipePopen < Test::Unit::TestCase - def test_popen - io = Kgio::Pipe.popen("sleep 1 && echo HI") - assert_equal :wait_readable, io.kgio_tryread(2) - sleep 1.5 - assert_equal "HI\n", io.kgio_read(3) - assert_nil io.kgio_read(5) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_pipe_read_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_pipe_read_write.rb deleted file mode 100644 index a200aeb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_pipe_read_write.rb +++ /dev/null @@ -1,9 +0,0 @@ -require './test/lib_read_write.rb' - -class TestKgioPipe < Test::Unit::TestCase - def setup - @rd, @wr = Kgio::Pipe.new - end - - include LibReadWriteTest -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_poll.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_poll.rb deleted file mode 100644 index 6463ef9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_poll.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'test/unit' -$-w = true -require 'kgio' - -class TestPoll < Test::Unit::TestCase - def teardown - [ @rd, @wr ].each { |io| io.close unless io.closed? } - end - - def setup - @rd, @wr = IO.pipe - end - - def test_constants - assert_kind_of Integer, Kgio::POLLIN - assert_kind_of Integer, Kgio::POLLOUT - assert_kind_of Integer, Kgio::POLLPRI - assert_kind_of Integer, Kgio::POLLHUP - assert_kind_of Integer, Kgio::POLLERR - assert_kind_of Integer, Kgio::POLLNVAL - end - - def test_poll_symbol - set = { @rd => :wait_readable, @wr => :wait_writable } - res = Kgio.poll(set) - assert_equal({@wr => Kgio::POLLOUT}, res) - assert_equal set.object_id, res.object_id - end - - def test_poll_integer - set = { @wr => Kgio::POLLOUT|Kgio::POLLHUP } - res = Kgio.poll(set) - assert_equal({@wr => Kgio::POLLOUT}, res) - assert_equal set.object_id, res.object_id - end - - def test_poll_timeout - t0 = Time.now - res = Kgio.poll({}, 10) - diff = Time.now - t0 - assert diff >= 0.010, "diff=#{diff}" - assert_nil res - end - - def test_poll_close - foo = nil - thr = Thread.new { sleep 0.100; @wr.close } - t0 = Time.now - res = Kgio.poll({@rd => Kgio::POLLIN}) - diff = Time.now - t0 - thr.join - assert_equal([ @rd ], res.keys) - assert diff >= 0.010, "diff=#{diff}" - end - - def test_signal_close - orig = trap(:USR1) { @rd.close } - res = nil - thr = Thread.new { sleep 0.100; Process.kill(:USR1, $$) } - t0 = Time.now - assert_raises(IOError) do - result = Kgio.poll({@rd => Kgio::POLLIN}) - result.each_key { |io| io.read_nonblock(1) } - end - diff = Time.now - t0 - thr.join - assert diff >= 0.010, "diff=#{diff}" - ensure - trap(:USR1, orig) - end - - def test_poll_EINTR - ok = false - orig = trap(:USR1) { ok = true } - thr = Thread.new do - sleep 0.100 - Process.kill(:USR1, $$) - end - t0 = Time.now - res = Kgio.poll({@rd => Kgio::POLLIN}, 1000) - diff = Time.now - t0 - thr.join - assert_nil res - assert diff >= 1.0, "diff=#{diff}" - assert ok - ensure - trap(:USR1, orig) - end - - def test_poll_signal_torture - usr1 = 0 - empty = 0 - nr = 100 - set = { @rd => Kgio::POLLIN } - orig = trap(:USR1) { usr1 += 1 } - pid = fork do - trap(:USR1, "DEFAULT") - sleep 0.1 - ppid = Process.ppid - nr.times { Process.kill(:USR1, ppid); sleep 0.05 } - @wr.syswrite('.') - exit!(0) - end - - empty += 1 until Kgio.poll(set.dup, 100) - _, status = Process.waitpid2(pid) - assert status.success?, status.inspect - assert usr1 > 0, "usr1: #{usr1}" - ensure - trap(:USR1, orig) - end unless RUBY_PLATFORM =~ /kfreebsd-gnu/ -end if Kgio.respond_to?(:poll) diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_singleton_read_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_singleton_read_write.rb deleted file mode 100644 index 86d30a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_singleton_read_write.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'test/unit' -$-w = true -require 'kgio' - -class TestSingletonReadWrite < Test::Unit::TestCase - - def test_unix_socketpair - a, b = UNIXSocket.pair - Kgio.trywrite(a, "HELLO") - buf = "" - assert_equal "HELLO", Kgio.tryread(b, 5, buf) - assert_equal "HELLO", buf - assert_equal :wait_readable, Kgio.tryread(b, 5) - end - - def test_arg_error - assert_raises(ArgumentError) { Kgio.tryread } - assert_raises(ArgumentError) { Kgio.tryread($stdin) } - assert_raises(ArgumentError) { Kgio.trywrite($stdout) } - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_socket.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_socket.rb deleted file mode 100644 index a85f0cc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_socket.rb +++ /dev/null @@ -1,14 +0,0 @@ -require 'test/unit' -require 'kgio' - -class TestKgioSocket < Test::Unit::TestCase - def test_socket_args - s = Kgio::Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) - assert_kind_of Socket, s - assert_instance_of Kgio::Socket, s - - s = Kgio::Socket.new(Socket::AF_UNIX, Socket::SOCK_STREAM, 0) - assert_kind_of Socket, s - assert_instance_of Kgio::Socket, s - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_socketpair_read_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_socketpair_read_write.rb deleted file mode 100644 index 611313a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_socketpair_read_write.rb +++ /dev/null @@ -1,9 +0,0 @@ -require './test/lib_read_write.rb' - -class TestKgioUNIXSocketPair < Test::Unit::TestCase - def setup - @rd, @wr = Kgio::UNIXSocket.pair - end - - include LibReadWriteTest -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_syssend.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_syssend.rb deleted file mode 100644 index 7d2511a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_syssend.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'test/unit' -require 'kgio' - -class TestKgioSyssend < Test::Unit::TestCase - def setup - @host = '127.0.0.1' || ENV["TEST_HOST"] - end - - def test_syssend - srv = Kgio::TCPServer.new(@host, 0) - port = srv.addr[1] - client = TCPSocket.new(@host, port) - acc = srv.kgio_accept - th = Thread.new { client.readpartial(4) } - sleep(0.05) - assert_nil acc.kgio_syssend("HI", Socket::MSG_DONTWAIT | Socket::MSG_MORE) - assert_nil acc.kgio_syssend("HI", Socket::MSG_DONTWAIT) - assert_equal "HIHI", th.value - - buf = "*" * 123 - res = [] - case rv = acc.kgio_syssend(buf, Socket::MSG_DONTWAIT) - when nil - when String - res << rv - when Symbol - res << rv - break - end while true - assert_equal :wait_writable, res.last - if res.size > 1 - assert_kind_of String, res[-2] - else - warn "res too small" - end - - # blocking - th = Thread.new { loop { acc.kgio_syssend("ZZZZ", 0) } } - assert_nil th.join(0.1) - ensure - [ srv, acc, client ].each { |io| io.close if io } - end -end if RUBY_PLATFORM =~ /linux/ && Socket.const_defined?(:MSG_MORE) diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp6_client_read_server_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp6_client_read_server_write.rb deleted file mode 100644 index 4ad330f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp6_client_read_server_write.rb +++ /dev/null @@ -1,23 +0,0 @@ -require './test/lib_read_write' - -begin - tmp = TCPServer.new(ENV["TEST_HOST6"] || '::1', 0) - ipv6_enabled = true -rescue => e - warn "skipping IPv6 tests, host does not seem to be IPv6 enabled:" - warn " #{e.class}: #{e}" - ipv6_enabled = false -end - -class TestTcp6ClientReadServerWrite < Test::Unit::TestCase - def setup - @host = ENV["TEST_HOST6"] || '::1' - @srv = Kgio::TCPServer.new(@host, 0) - @port = @srv.addr[1] - @wr = Kgio::TCPSocket.new(@host, @port) - @rd = @srv.kgio_accept - assert_equal Socket.unpack_sockaddr_in(@rd.getpeername)[-1], @rd.kgio_addr - end - - include LibReadWriteTest -end if ipv6_enabled diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_client_read_server_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_client_read_server_write.rb deleted file mode 100644 index 13714e9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_client_read_server_write.rb +++ /dev/null @@ -1,13 +0,0 @@ -require './test/lib_read_write' - -class TesTcpClientReadServerWrite < Test::Unit::TestCase - def setup - @host = ENV["TEST_HOST"] || '127.0.0.1' - @srv = Kgio::TCPServer.new(@host, 0) - @port = @srv.addr[1] - @wr = Kgio::TCPSocket.new(@host, @port) - @rd = @srv.kgio_accept - end - - include LibReadWriteTest -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_connect.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_connect.rb deleted file mode 100644 index 2cf1b86..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_connect.rb +++ /dev/null @@ -1,84 +0,0 @@ -require 'test/unit' -require 'io/nonblock' -$-w = true -require 'kgio' - -class SubSocket < Kgio::Socket - attr_accessor :foo - def kgio_wait_writable - @foo = "waited" - end -end - -class TestKgioTcpConnect < Test::Unit::TestCase - - def setup - @host = ENV["TEST_HOST"] || '127.0.0.1' - @srv = Kgio::TCPServer.new(@host, 0) - @port = @srv.addr[1] - @addr = Socket.pack_sockaddr_in(@port, @host) - end - - def teardown - @srv.close unless @srv.closed? - Kgio.accept_cloexec = true - Kgio.accept_nonblock = false - end - - def test_new - sock = Kgio::Socket.new(@addr) - assert_kind_of Kgio::Socket, sock - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - - sock.respond_to?(:close_on_exec?) and - assert_equal(RUBY_VERSION.to_f >= 2.0, sock.close_on_exec?) - end - - def test_start - sock = Kgio::Socket.start(@addr) - - sock.respond_to?(:close_on_exec?) and - assert_equal(RUBY_VERSION.to_f >= 2.0, sock.close_on_exec?) - - assert_kind_of Kgio::Socket, sock - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - end - - def test_tcp_socket_new_invalid - assert_raises(ArgumentError) { Kgio::TCPSocket.new('example.com', 80) } - assert_raises(ArgumentError) { Kgio::TCPSocket.new('999.999.999.999', 80) } - assert_raises(TypeError) { Kgio::TCPSocket.new("127.0.0.1", "http") } - assert_raises(TypeError) { Kgio::TCPSocket.new('example.com', "http") } - end - - def test_tcp_socket_new - sock = Kgio::TCPSocket.new(@host, @port) - - sock.respond_to?(:close_on_exec?) and - assert_equal(RUBY_VERSION.to_f >= 2.0, sock.close_on_exec?) - - assert_instance_of Kgio::TCPSocket, sock - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - end - - def test_socket_start - sock = SubSocket.start(@addr) - assert_nil sock.foo - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - end - - def test_wait_writable_set - sock = SubSocket.new(@addr) - assert_equal "waited", sock.foo if RUBY_PLATFORM =~ /linux/ - IO.select(nil, [sock]) if RUBY_PLATFORM !~ /linux/ - assert_equal nil, sock.kgio_write("HELLO") - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_server.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_server.rb deleted file mode 100644 index eb6933e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_server.rb +++ /dev/null @@ -1,16 +0,0 @@ -require './test/lib_server_accept' - -class TestKgioTCPServer < Test::Unit::TestCase - - def setup - @host = ENV["TEST_HOST"] || '127.0.0.1' - @srv = Kgio::TCPServer.new(@host, 0) - @port = @srv.addr[1] - end - - def client_connect - TCPSocket.new(@host, @port) - end - - include LibServerAccept -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_server_read_client_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_server_read_client_write.rb deleted file mode 100644 index 68cada3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tcp_server_read_client_write.rb +++ /dev/null @@ -1,13 +0,0 @@ -require './test/lib_read_write' - -class TesTcpServerReadClientWrite < Test::Unit::TestCase - def setup - @host = ENV["TEST_HOST"] || '127.0.0.1' - @srv = Kgio::TCPServer.new(@host, 0) - @port = @srv.addr[1] - @wr = Kgio::TCPSocket.new(@host, @port) - @rd = @srv.kgio_accept - end - - include LibReadWriteTest -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tfo.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tfo.rb deleted file mode 100644 index 5ab208d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tfo.rb +++ /dev/null @@ -1,70 +0,0 @@ -require 'test/unit' -require 'kgio' - -class TestTFO < Test::Unit::TestCase - def test_constants - if `uname -s`.chomp == "Linux" && `uname -r`.to_f >= 3.7 - assert_equal 23, Kgio::TCP_FASTOPEN - assert_equal 0x20000000, Kgio::MSG_FASTOPEN - end - end - - def fastopen_ok? - if RUBY_PLATFORM =~ /linux/ - tfo = File.read("/proc/sys/net/ipv4/tcp_fastopen").to_i - client_enable = 1 - server_enable = 2 - enable = client_enable | server_enable - (tfo & enable) == enable - else - false - end - end - - def test_tfo_client_server - unless fastopen_ok? - warn "TCP Fast Open not enabled on this system (check kernel docs)" - return - end - addr = '127.0.0.1' - qlen = 1024 - s = Kgio::TCPServer.new(addr, 0) - s.setsockopt(:TCP, Kgio::TCP_FASTOPEN, qlen) - port = s.local_address.ip_port - addr = Socket.pack_sockaddr_in(port, addr) - c = Kgio::Socket.new(:INET, :STREAM) - assert_nil c.kgio_fastopen("HELLO", addr) - a = s.accept - assert_equal "HELLO", a.read(5) - c.close - a.close - - # ensure empty sends work - c = Kgio::Socket.new(:INET, :STREAM) - assert_nil c.kgio_fastopen("", addr) - a = s.accept - Thread.new { c.close } - assert_nil a.read(1) - a.close - - # try a monster packet - buf = 'x' * (1024 * 1024 * 320) - - c = Kgio::Socket.new(:INET, :STREAM) - thr = Thread.new do - a = s.accept - assert_equal buf.size, a.read(buf.size).size - a.close - end - assert_nil c.kgio_fastopen(buf, addr) - thr.join - c.close - - # allow timeouts - c = Kgio::Socket.new(:INET, :STREAM) - c.setsockopt(:SOCKET, :SNDTIMEO, [ 0, 10 ].pack("l_l_")) - unsent = c.kgio_fastopen(buf, addr) - c.close - assert_equal s.accept.read.size + unsent.size, buf.size - end if defined?(Addrinfo) && defined?(Kgio::TCP_FASTOPEN) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tryopen.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tryopen.rb deleted file mode 100644 index abcbd37..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_tryopen.rb +++ /dev/null @@ -1,90 +0,0 @@ -require 'tempfile' -require 'test/unit' -$-w = true -require 'kgio' - -class TestTryopen < Test::Unit::TestCase - - def test_tryopen_success - tmp = Kgio::File.tryopen(__FILE__) - - tmp.respond_to?(:close_on_exec?) and - assert_equal(RUBY_VERSION.to_f >= 2.0, tmp.close_on_exec?) - - assert_kind_of File, tmp - assert_equal File.read(__FILE__), tmp.read - assert_equal __FILE__, tmp.path - assert_equal __FILE__, tmp.to_path - tmp.close - end - - def test_tryopen_ENOENT - tmp = Tempfile.new "tryopen" - path = tmp.path - tmp.close! - tmp = Kgio::File.tryopen(path) - assert_equal :ENOENT, tmp - end - - def test_tryopen_EACCES - tmp = Tempfile.new "tryopen" - File.chmod 0000, tmp.path - tmp = Kgio::File.tryopen(tmp.path) - if Process.euid == 0 - assert_kind_of Kgio::File, tmp - warn "cannot test EACCES when euid == 0" - else - assert_equal(:EACCES, tmp) - end - end - - def test_tryopen_readwrite - tmp = Tempfile.new "tryopen" - file = Kgio::File.tryopen(tmp.path, IO::RDWR) - file.syswrite "FOO" - assert_equal "FOO", tmp.sysread(3) - end - - def test_tryopen_try_readwrite - tmp = Tempfile.new "tryopen" - file = Kgio::File.tryopen(tmp.path, IO::RDWR) - assert_nil file.kgio_trywrite("FOO") - file.rewind - assert_equal "FOO", file.kgio_tryread(3) - end - - def test_tryopen_mode - tmp = Tempfile.new "tryopen" - path = tmp.path - tmp.close! - file = Kgio::File.tryopen(path, IO::RDWR|IO::CREAT, 0000) - assert_equal 0100000, File.stat(path).mode - ensure - File.unlink path - end - - require "benchmark" - def test_benchmark - nr = 1000000 - tmp = Tempfile.new('tryopen') - file = tmp.path - Benchmark.bmbm do |x| - x.report("tryopen (OK)") do - nr.times { Kgio::File.tryopen(file).close } - end - x.report("open (OK)") do - nr.times { File.readable?(file) && File.open(file).close } - end - end - tmp.close! - assert_equal :ENOENT, Kgio::File.tryopen(file) - Benchmark.bmbm do |x| - x.report("tryopen (ENOENT)") do - nr.times { Kgio::File.tryopen(file) } - end - x.report("open (ENOENT)") do - nr.times { File.readable?(file) && File.open(file) } - end - end - end if ENV["BENCHMARK"] -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_client_read_server_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_client_read_server_write.rb deleted file mode 100644 index c8835cd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_client_read_server_write.rb +++ /dev/null @@ -1,18 +0,0 @@ -require './test/lib_read_write' -require 'tempfile' -require 'tmpdir' - -class TestUnixClientReadServerWrite < Test::Unit::TestCase - def setup - @tmpdir = Dir.mktmpdir('kgio_unix_0') - tmp = Tempfile.new('kgio_unix_0', @tmpdir) - @path = tmp.path - tmp.close! - @srv = Kgio::UNIXServer.new(@path) - @rd = Kgio::UNIXSocket.new(@path) - @wr = @srv.kgio_tryaccept - end - - include LibReadWriteTest -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_connect.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_connect.rb deleted file mode 100644 index 7b19941..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_connect.rb +++ /dev/null @@ -1,83 +0,0 @@ -require 'test/unit' -require 'io/nonblock' -$-w = true -require 'kgio' -require 'tempfile' -require 'tmpdir' - -class SubSocket < Kgio::Socket - attr_accessor :foo - def kgio_wait_writable - @foo = "waited" - end -end - -class TestKgioUnixConnect < Test::Unit::TestCase - - def setup - @tmpdir = Dir.mktmpdir('kgio_unix_1') - tmp = Tempfile.new('kgio_unix_1', @tmpdir) - @path = tmp.path - tmp.close! - @srv = Kgio::UNIXServer.new(@path) - @addr = Socket.pack_sockaddr_un(@path) - end - - def teardown - @srv.close unless @srv.closed? - File.unlink(@path) - FileUtils.remove_entry_secure(@tmpdir) - Kgio.accept_cloexec = true - end - - def test_unix_socket_new_invalid - assert_raises(ArgumentError) { Kgio::UNIXSocket.new('*' * 1024 * 1024) } - end - - def test_unix_socket_new - sock = Kgio::UNIXSocket.new(@path) - - sock.respond_to?(:close_on_exec?) and - assert_equal(RUBY_VERSION.to_f >= 2.0, sock.close_on_exec?) - - assert_instance_of Kgio::UNIXSocket, sock - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - end - - def test_new - sock = Kgio::Socket.new(@addr) - - sock.respond_to?(:close_on_exec?) and - assert_equal(RUBY_VERSION.to_f >= 2.0, sock.close_on_exec?) - - assert_instance_of Kgio::Socket, sock - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - end - - def test_start - sock = Kgio::Socket.start(@addr) - assert_instance_of Kgio::Socket, sock - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - end - - def test_socket_start - sock = SubSocket.start(@addr) - assert_nil sock.foo - ready = IO.select(nil, [ sock ]) - assert_equal sock, ready[1][0] - assert_equal nil, sock.kgio_write("HELLO") - end - - def test_wait_writable_set - sock = SubSocket.new(@addr) - assert_kind_of Kgio::Socket, sock - assert_instance_of SubSocket, sock - assert_equal nil, sock.kgio_write("HELLO") - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_server.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_server.rb deleted file mode 100644 index 96769b1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_server.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'tempfile' -require 'tmpdir' -require './test/lib_server_accept' - -class TestKgioUNIXServer < Test::Unit::TestCase - - def setup - @tmpdir = Dir.mktmpdir('kgio_unix_2') - tmp = Tempfile.new('kgio_unix_2', @tmpdir) - @path = tmp.path - tmp.close! - @srv = Kgio::UNIXServer.new(@path) - @host = '127.0.0.1' - end - - def client_connect - UNIXSocket.new(@path) - end - - include LibServerAccept -end diff --git a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_server_read_client_write.rb b/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_server_read_client_write.rb deleted file mode 100644 index 24581e1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/kgio-2.9.2/test/test_unix_server_read_client_write.rb +++ /dev/null @@ -1,18 +0,0 @@ -require './test/lib_read_write' -require 'tempfile' -require 'tmpdir' - -class TestUnixServerReadClientWrite < Test::Unit::TestCase - def setup - @tmpdir = Dir.mktmpdir('kgio_unix_3') - tmp = Tempfile.new('kgio_unix_3', @tmpdir) - @path = tmp.path - tmp.close! - @srv = Kgio::UNIXServer.new(@path) - @wr = Kgio::UNIXSocket.new(@path) - @rd = @srv.kgio_tryaccept - end - - include LibReadWriteTest -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/COPYING b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/COPYING deleted file mode 100644 index a4fe222..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/COPYING +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2007, 2008, 2009, 2010, 2011, 2012 Christian Neukirchen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/KNOWN-ISSUES b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/KNOWN-ISSUES deleted file mode 100644 index e0373b2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/KNOWN-ISSUES +++ /dev/null @@ -1,30 +0,0 @@ -= Known issues with Rack and ECMA-262 - -* Many users expect the escape() function defined in ECMA-262 to be compatible - with URI. Confusion is especially strong because the documentation for the - escape function includes a reference to the URI specifications. ECMA-262 - escape is not however a URI escape function, it is a javascript escape - function, and is not fully compatible. Most notably, for characters outside of - the BMP. Users should use the more correct encodeURI functions. - -= Known issues with Rack and Web servers - -* Lighttpd sets wrong SCRIPT_NAME and PATH_INFO if you mount your - FastCGI app at "/". This can be fixed by using this middleware: - - class LighttpdScriptNameFix - def initialize(app) - @app = app - end - - def call(env) - env["PATH_INFO"] = env["SCRIPT_NAME"].to_s + env["PATH_INFO"].to_s - env["SCRIPT_NAME"] = "" - @app.call(env) - end - end - - Of course, use this only when your app runs at "/". - - Since lighttpd 1.4.23, you also can use the "fix-root-scriptname" flag - in fastcgi.server. diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/README.rdoc b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/README.rdoc deleted file mode 100644 index 02c1193..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/README.rdoc +++ /dev/null @@ -1,624 +0,0 @@ -= Rack, a modular Ruby webserver interface {Build Status}[http://travis-ci.org/rack/rack] {Dependency Status}[https://gemnasium.com/rack/rack] - -Rack provides a minimal, modular and adaptable interface for developing -web applications in Ruby. By wrapping HTTP requests and responses in -the simplest way possible, it unifies and distills the API for web -servers, web frameworks, and software in between (the so-called -middleware) into a single method call. - -The exact details of this are described in the Rack specification, -which all Rack applications should conform to. - -== Supported web servers - -The included *handlers* connect all kinds of web servers to Rack: -* Mongrel -* EventedMongrel -* SwiftipliedMongrel -* WEBrick -* FCGI -* CGI -* SCGI -* LiteSpeed -* Thin - -These web servers include Rack handlers in their distributions: -* Ebb -* Fuzed -* Glassfish v3 -* Phusion Passenger (which is mod_rack for Apache and for nginx) -* Puma -* Rainbows! -* Reel -* Unicorn -* unixrack -* uWSGI -* Zbatery - -Any valid Rack app will run the same on all these handlers, without -changing anything. - -== Supported web frameworks - -These frameworks include Rack adapters in their distributions: -* Camping -* Coset -* Espresso -* Halcyon -* Mack -* Maveric -* Merb -* Racktools::SimpleApplication -* Ramaze -* Ruby on Rails -* Rum -* Sinatra -* Sin -* Vintage -* Waves -* Wee -* ... and many others. - -== Available middleware - -Between the server and the framework, Rack can be customized to your -applications needs using middleware, for example: -* Rack::URLMap, to route to multiple applications inside the same process. -* Rack::CommonLogger, for creating Apache-style logfiles. -* Rack::ShowException, for catching unhandled exceptions and - presenting them in a nice and helpful way with clickable backtrace. -* Rack::File, for serving static files. -* ...many others! - -All these components use the same interface, which is described in -detail in the Rack specification. These optional components can be -used in any way you wish. - -== Convenience - -If you want to develop outside of existing frameworks, implement your -own ones, or develop middleware, Rack provides many helpers to create -Rack applications quickly and without doing the same web stuff all -over: -* Rack::Request, which also provides query string parsing and - multipart handling. -* Rack::Response, for convenient generation of HTTP replies and - cookie handling. -* Rack::MockRequest and Rack::MockResponse for efficient and quick - testing of Rack application without real HTTP round-trips. - -== rack-contrib - -The plethora of useful middleware created the need for a project that -collects fresh Rack middleware. rack-contrib includes a variety of -add-on components for Rack and it is easy to contribute new modules. - -* http://github.com/rack/rack-contrib - -== rackup - -rackup is a useful tool for running Rack applications, which uses the -Rack::Builder DSL to configure middleware and build up applications -easily. - -rackup automatically figures out the environment it is run in, and -runs your application as FastCGI, CGI, or standalone with Mongrel or -WEBrick---all from the same configuration. - -== Quick start - -Try the lobster! - -Either with the embedded WEBrick starter: - - ruby -Ilib lib/rack/lobster.rb - -Or with rackup: - - bin/rackup -Ilib example/lobster.ru - -By default, the lobster is found at http://localhost:9292. - -== Installing with RubyGems - -A Gem of Rack is available at rubygems.org. You can install it with: - - gem install rack - -I also provide a local mirror of the gems (and development snapshots) -at my site: - - gem install rack --source http://chneukirchen.org/releases/gems/ - -== Running the tests - -Testing Rack requires the bacon testing framework: - - bundle install --without extra # to be able to run the fast tests - -Or: - - bundle install # this assumes that you have installed native extensions! - -There are two rake-based test tasks: - - rake test tests all the fast tests (no Handlers or Adapters) - rake fulltest runs all the tests - -The fast testsuite has no dependencies outside of the core Ruby -installation and bacon. - -To run the test suite completely, you need: - - * fcgi - * memcache-client - * mongrel - * thin - -The full set of tests test FCGI access with lighttpd (on port -9203) so you will need lighttpd installed as well as the FCGI -libraries and the fcgi gem: - -Download and install lighttpd: - - http://www.lighttpd.net/download - -Installing the FCGI libraries: - - curl -O http://www.fastcgi.com/dist/fcgi-2.4.0.tar.gz - tar xzvf fcgi-2.4.0.tar.gz - cd fcgi-2.4.0 - ./configure --prefix=/usr/local - make - sudo make install - cd .. - -Installing the Ruby fcgi gem: - - gem install fcgi - -Furthermore, to test Memcache sessions, you need memcached (will be -run on port 11211) and memcache-client installed. - -== History - -* March 3rd, 2007: First public release 0.1. - -* May 16th, 2007: Second public release 0.2. - * HTTP Basic authentication. - * Cookie Sessions. - * Static file handler. - * Improved Rack::Request. - * Improved Rack::Response. - * Added Rack::ShowStatus, for better default error messages. - * Bug fixes in the Camping adapter. - * Removed Rails adapter, was too alpha. - -* February 26th, 2008: Third public release 0.3. - * LiteSpeed handler, by Adrian Madrid. - * SCGI handler, by Jeremy Evans. - * Pool sessions, by blink. - * OpenID authentication, by blink. - * :Port and :File options for opening FastCGI sockets, by blink. - * Last-Modified HTTP header for Rack::File, by blink. - * Rack::Builder#use now accepts blocks, by Corey Jewett. - (See example/protectedlobster.ru) - * HTTP status 201 can contain a Content-Type and a body now. - * Many bugfixes, especially related to Cookie handling. - -* August 21st, 2008: Fourth public release 0.4. - * New middleware, Rack::Deflater, by Christoffer Sawicki. - * OpenID authentication now needs ruby-openid 2. - * New Memcache sessions, by blink. - * Explicit EventedMongrel handler, by Joshua Peek - * Rack::Reloader is not loaded in rackup development mode. - * rackup can daemonize with -D. - * Many bugfixes, especially for pool sessions, URLMap, thread safety - and tempfile handling. - * Improved tests. - * Rack moved to Git. - -* January 6th, 2009: Fifth public release 0.9. - * Rack is now managed by the Rack Core Team. - * Rack::Lint is stricter and follows the HTTP RFCs more closely. - * Added ConditionalGet middleware. - * Added ContentLength middleware. - * Added Deflater middleware. - * Added Head middleware. - * Added MethodOverride middleware. - * Rack::Mime now provides popular MIME-types and their extension. - * Mongrel Header now streams. - * Added Thin handler. - * Official support for swiftiplied Mongrel. - * Secure cookies. - * Made HeaderHash case-preserving. - * Many bugfixes and small improvements. - -* January 9th, 2009: Sixth public release 0.9.1. - * Fix directory traversal exploits in Rack::File and Rack::Directory. - -* April 25th, 2009: Seventh public release 1.0.0. - * SPEC change: Rack::VERSION has been pushed to [1,0]. - * SPEC change: header values must be Strings now, split on "\n". - * SPEC change: Content-Length can be missing, in this case chunked transfer - encoding is used. - * SPEC change: rack.input must be rewindable and support reading into - a buffer, wrap with Rack::RewindableInput if it isn't. - * SPEC change: rack.session is now specified. - * SPEC change: Bodies can now additionally respond to #to_path with - a filename to be served. - * NOTE: String bodies break in 1.9, use an Array consisting of a - single String instead. - * New middleware Rack::Lock. - * New middleware Rack::ContentType. - * Rack::Reloader has been rewritten. - * Major update to Rack::Auth::OpenID. - * Support for nested parameter parsing in Rack::Response. - * Support for redirects in Rack::Response. - * HttpOnly cookie support in Rack::Response. - * The Rakefile has been rewritten. - * Many bugfixes and small improvements. - -* October 18th, 2009: Eighth public release 1.0.1. - * Bump remainder of rack.versions. - * Support the pure Ruby FCGI implementation. - * Fix for form names containing "=": split first then unescape components - * Fixes the handling of the filename parameter with semicolons in names. - * Add anchor to nested params parsing regexp to prevent stack overflows - * Use more compatible gzip write api instead of "<<". - * Make sure that Reloader doesn't break when executed via ruby -e - * Make sure WEBrick respects the :Host option - * Many Ruby 1.9 fixes. - -* January 3rd, 2010: Ninth public release 1.1.0. - * Moved Auth::OpenID to rack-contrib. - * SPEC change that relaxes Lint slightly to allow subclasses of the - required types - * SPEC change to document rack.input binary mode in greator detail - * SPEC define optional rack.logger specification - * File servers support X-Cascade header - * Imported Config middleware - * Imported ETag middleware - * Imported Runtime middleware - * Imported Sendfile middleware - * New Logger and NullLogger middlewares - * Added mime type for .ogv and .manifest. - * Don't squeeze PATH_INFO slashes - * Use Content-Type to determine POST params parsing - * Update Rack::Utils::HTTP_STATUS_CODES hash - * Add status code lookup utility - * Response should call #to_i on the status - * Add Request#user_agent - * Request#host knows about forwared host - * Return an empty string for Request#host if HTTP_HOST and - SERVER_NAME are both missing - * Allow MockRequest to accept hash params - * Optimizations to HeaderHash - * Refactored rackup into Rack::Server - * Added Utils.build_nested_query to complement Utils.parse_nested_query - * Added Utils::Multipart.build_multipart to complement - Utils::Multipart.parse_multipart - * Extracted set and delete cookie helpers into Utils so they can be - used outside Response - * Extract parse_query and parse_multipart in Request so subclasses - can change their behavior - * Enforce binary encoding in RewindableInput - * Set correct external_encoding for handlers that don't use RewindableInput - -* June 13th, 2010: Tenth public release 1.2.0. - * Removed Camping adapter: Camping 2.0 supports Rack as-is - * Removed parsing of quoted values - * Add Request.trace? and Request.options? - * Add mime-type for .webm and .htc - * Fix HTTP_X_FORWARDED_FOR - * Various multipart fixes - * Switch test suite to bacon - -* June 15th, 2010: Eleventh public release 1.2.1. - * Make CGI handler rewindable - * Rename spec/ to test/ to not conflict with SPEC on lesser - operating systems - -* March 13th, 2011: Twelfth public release 1.2.2/1.1.2. - * Security fix in Rack::Auth::Digest::MD5: when authenticator - returned nil, permission was granted on empty password. - -* May 22nd, 2011: Thirteenth public release 1.3.0 - * Various performance optimizations - * Various multipart fixes - * Various multipart refactors - * Infinite loop fix for multipart - * Test coverage for Rack::Server returns - * Allow files with '..', but not path components that are '..' - * rackup accepts handler-specific options on the command line - * Request#params no longer merges POST into GET (but returns the same) - * Use URI.encode_www_form_component instead. Use core methods for escaping. - * Allow multi-line comments in the config file - * Bug L#94 reported by Nikolai Lugovoi, query parameter unescaping. - * Rack::Response now deletes Content-Length when appropriate - * Rack::Deflater now supports streaming - * Improved Rack::Handler loading and searching - * Support for the PATCH verb - * env['rack.session.options'] now contains session options - * Cookies respect renew - * Session middleware uses SecureRandom.hex - -* May 22nd, 2011: Fourteenth public release 1.2.3 - * Pulled in relevant bug fixes from 1.3 - * Fixed 1.8.6 support - -* July 13, 2011: Fifteenth public release 1.3.1 - * Fix 1.9.1 support - * Fix JRuby support - * Properly handle $KCODE in Rack::Utils.escape - * Make method_missing/respond_to behavior consistent for Rack::Lock, - Rack::Auth::Digest::Request and Rack::Multipart::UploadedFile - * Reenable passing rack.session to session middleware - * Rack::CommonLogger handles streaming responses correctly - * Rack::MockResponse calls close on the body object - * Fix a DOS vector from MRI stdlib backport - -* July 16, 2011: Sixteenth public release 1.3.2 - * Fix for Rails and rack-test, Rack::Utils#escape calls to_s - -* September 16, 2011: Seventeenth public release 1.3.3 - * Fix bug with broken query parameters in Rack::ShowExceptions - * Rack::Request#cookies no longer swallows exceptions on broken input - * Prevents XSS attacks enabled by bug in Ruby 1.8's regexp engine - * Rack::ConditionalGet handles broken If-Modified-Since helpers - -* September 16, 2011: Eighteenth public release 1.2.4 - * Fix a bug with MRI regex engine to prevent XSS by malformed unicode - -* October 1, 2011: Nineteenth public release 1.3.4 - * Backport security fix from 1.9.3, also fixes some roundtrip issues in URI - * Small documentation update - * Fix an issue where BodyProxy could cause an infinite recursion - * Add some supporting files for travis-ci - -* October 17, 2011: Twentieth public release 1.3.5 - * Fix annoying warnings caused by the backport in 1.3.4 - -* December 28th, 2011: Twenty first public release: 1.1.3. - * Security fix. http://www.ocert.org/advisories/ocert-2011-003.html - Further information here: http://jruby.org/2011/12/27/jruby-1-6-5-1 - -* December 28th, 2011: Twenty fourth public release 1.4.0 - * Ruby 1.8.6 support has officially been dropped. Not all tests pass. - * Raise sane error messages for broken config.ru - * Allow combining run and map in a config.ru - * Rack::ContentType will not set Content-Type for responses without a body - * Status code 205 does not send a response body - * Rack::Response::Helpers will not rely on instance variables - * Rack::Utils.build_query no longer outputs '=' for nil query values - * Various mime types added - * Rack::MockRequest now supports HEAD - * Rack::Directory now supports files that contain RFC3986 reserved chars - * Rack::File now only supports GET and HEAD requests - * Rack::Server#start now passes the block to Rack::Handler::#run - * Rack::Static now supports an index option - * Added the Teapot status code - * rackup now defaults to Thin instead of Mongrel (if installed) - * Support added for HTTP_X_FORWARDED_SCHEME - * Numerous bug fixes, including many fixes for new and alternate rubies - -* January 22nd, 2012: Twenty fifth public release 1.4.1 - * Alter the keyspace limit calculations to reduce issues with nested params - * Add a workaround for multipart parsing where files contain unescaped "%" - * Added Rack::Response::Helpers#method_not_allowed? (code 405) - * Rack::File now returns 404 for illegal directory traversals - * Rack::File now returns 405 for illegal methods (non HEAD/GET) - * Rack::Cascade now catches 405 by default, as well as 404 - * Cookies missing '--' no longer cause an exception to be raised - * Various style changes and documentation spelling errors - * Rack::BodyProxy always ensures to execute its block - * Additional test coverage around cookies and secrets - * Rack::Session::Cookie can now be supplied either secret or old_secret - * Tests are no longer dependent on set order - * Rack::Static no longer defaults to serving index files - * Rack.release was fixed - -* January 6th, 2013: Twenty sixth public release 1.1.4 - * Add warnings when users do not provide a session secret - -* January 6th, 2013: Twenty seventh public release 1.2.6 - * Add warnings when users do not provide a session secret - * Fix parsing performance for unquoted filenames - -* January 6th, 2013: Twenty eighth public release 1.3.7 - * Add warnings when users do not provide a session secret - * Fix parsing performance for unquoted filenames - * Updated URI backports - * Fix URI backport version matching, and silence constant warnings - * Correct parameter parsing with empty values - * Correct rackup '-I' flag, to allow multiple uses - * Correct rackup pidfile handling - * Report rackup line numbers correctly - * Fix request loops caused by non-stale nonces with time limits - * Fix reloader on Windows - * Prevent infinite recursions from Response#to_ary - * Various middleware better conforms to the body close specification - * Updated language for the body close specification - * Additional notes regarding ECMA escape compatibility issues - * Fix the parsing of multiple ranges in range headers - -* January 6th, 2013: Twenty ninth public release 1.4.2 - * Add warnings when users do not provide a session secret - * Fix parsing performance for unquoted filenames - * Updated URI backports - * Fix URI backport version matching, and silence constant warnings - * Correct parameter parsing with empty values - * Correct rackup '-I' flag, to allow multiple uses - * Correct rackup pidfile handling - * Report rackup line numbers correctly - * Fix request loops caused by non-stale nonces with time limits - * Fix reloader on Windows - * Prevent infinite recursions from Response#to_ary - * Various middleware better conforms to the body close specification - * Updated language for the body close specification - * Additional notes regarding ECMA escape compatibility issues - * Fix the parsing of multiple ranges in range headers - * Prevent errors from empty parameter keys - * Added PATCH verb to Rack::Request - * Various documentation updates - * Fix session merge semantics (fixes rack-test) - * Rack::Static :index can now handle multiple directories - * All tests now utilize Rack::Lint (special thanks to Lars Gierth) - * Rack::File cache_control parameter is now deprecated, and removed by 1.5 - * Correct Rack::Directory script name escaping - * Rack::Static supports header rules for sophisticated configurations - * Multipart parsing now works without a Content-Length header - * New logos courtesy of Zachary Scott! - * Rack::BodyProxy now explicitly defines #each, useful for C extensions - * Cookies that are not URI escaped no longer cause exceptions - -* January 7th, 2013: Thirtieth public release 1.3.8 - * Security: Prevent unbounded reads in large multipart boundaries - -* January 7th, 2013: Thirty first public release 1.4.3 - * Security: Prevent unbounded reads in large multipart boundaries - -* January 13th, 2013: Thirty second public release 1.4.4, 1.3.9, 1.2.7, 1.1.5 - * [SEC] Rack::Auth::AbstractRequest no longer symbolizes arbitrary strings - * Fixed erroneous test case in the 1.3.x series - -* January 21st, 2013: Thirty third public release 1.5.0 - * Introduced hijack SPEC, for before-response and after-response hijacking - * SessionHash is no longer a Hash subclass - * Rack::File cache_control parameter is removed, in place of headers options - * Rack::Auth::AbstractRequest#scheme now yields strings, not symbols - * Rack::Utils cookie functions now format expires in RFC 2822 format - * Rack::File now has a default mime type - * rackup -b 'run Rack::File.new(".")', option provides command line configs - * Rack::Deflater will no longer double encode bodies - * Rack::Mime#match? provides convenience for Accept header matching - * Rack::Utils#q_values provides splitting for Accept headers - * Rack::Utils#best_q_match provides a helper for Accept headers - * Rack::Handler.pick provides convenience for finding available servers - * Puma added to the list of default servers (preferred over Webrick) - * Various middleware now correctly close body when replacing it - * Rack::Request#params is no longer persistent with only GET params - * Rack::Request#update_param and #delete_param provide persistent operations - * Rack::Request#trusted_proxy? now returns true for local unix sockets - * Rack::Response no longer forces Content-Types - * Rack::Sendfile provides local mapping configuration options - * Rack::Utils#rfc2109 provides old netscape style time output - * Updated HTTP status codes - * Ruby 1.8.6 likely no longer passes tests, and is no longer fully supported - -* January 28th, 2013: Thirty fourth public release 1.5.1 - * Rack::Lint check_hijack now conforms to other parts of SPEC - * Added hash-like methods to Abstract::ID::SessionHash for compatibility - * Various documentation corrections - -* February 7th, Thirty fifth public release 1.1.6, 1.2.8, 1.3.10 - * Fix CVE-2013-0263, timing attack against Rack::Session::Cookie - -* February 7th, Thirty fifth public release 1.4.5 - * Fix CVE-2013-0263, timing attack against Rack::Session::Cookie - * Fix CVE-2013-0262, symlink path traversal in Rack::File - -* February 7th, Thirty fifth public release 1.5.2 - * Fix CVE-2013-0263, timing attack against Rack::Session::Cookie - * Fix CVE-2013-0262, symlink path traversal in Rack::File - * Add various methods to Session for enhanced Rails compatibility - * Request#trusted_proxy? now only matches whole stirngs - * Add JSON cookie coder, to be default in Rack 1.6+ due to security concerns - * URLMap host matching in environments that don't set the Host header fixed - * Fix a race condition that could result in overwritten pidfiles - * Various documentation additions - -== Contact - -Please post bugs, suggestions and patches to -the bug tracker at . - -Please post security related bugs and suggestions to the core team at - or rack-core@googlegroups.com. This -list is not public. Due to wide usage of the library, it is strongly preferred -that we manage timing in order to provide viable patches at the time of -disclosure. Your assistance in this matter is greatly appreciated. - -Mailing list archives are available at -. - -Git repository (send Git patches to the mailing list): -* http://github.com/rack/rack -* http://git.vuxu.org/cgi-bin/gitweb.cgi?p=rack-github.git - -You are also welcome to join the #rack channel on irc.freenode.net. - -== Thanks - -The Rack Core Team, consisting of - -* Christian Neukirchen (chneukirchen) -* James Tucker (raggi) -* Josh Peek (josh) -* Michael Fellinger (manveru) -* Ryan Tomayko (rtomayko) -* Scytrin dai Kinthra (scytrin) -* Aaron Patterson (tenderlove) -* Konstantin Haase (rkh) - -would like to thank: - -* Adrian Madrid, for the LiteSpeed handler. -* Christoffer Sawicki, for the first Rails adapter and Rack::Deflater. -* Tim Fletcher, for the HTTP authentication code. -* Luc Heinrich for the Cookie sessions, the static file handler and bugfixes. -* Armin Ronacher, for the logo and racktools. -* Alex Beregszaszi, Alexander Kahn, Anil Wadghule, Aredridel, Ben - Alpert, Dan Kubb, Daniel Roethlisberger, Matt Todd, Tom Robinson, - Phil Hagelberg, S. Brent Faulkner, Bosko Milekic, Daniel Rodríguez - Troitiño, Genki Takiuchi, Geoffrey Grosenbach, Julien Sanchez, Kamal - Fariz Mahyuddin, Masayoshi Takahashi, Patrick Aljordm, Mig, Kazuhiro - Nishiyama, Jon Bardin, Konstantin Haase, Larry Siden, Matias - Korhonen, Sam Ruby, Simon Chiang, Tim Connor, Timur Batyrshin, and - Zach Brock for bug fixing and other improvements. -* Eric Wong, Hongli Lai, Jeremy Kemper for their continuous support - and API improvements. -* Yehuda Katz and Carl Lerche for refactoring rackup. -* Brian Candler, for Rack::ContentType. -* Graham Batty, for improved handler loading. -* Stephen Bannasch, for bug reports and documentation. -* Gary Wright, for proposing a better Rack::Response interface. -* Jonathan Buch, for improvements regarding Rack::Response. -* Armin Röhrl, for tracking down bugs in the Cookie generator. -* Alexander Kellett for testing the Gem and reviewing the announcement. -* Marcus Rückert, for help with configuring and debugging lighttpd. -* The WSGI team for the well-done and documented work they've done and - Rack builds up on. -* All bug reporters and patch contributors not mentioned above. - -== Copyright - -Copyright (C) 2007, 2008, 2009, 2010 Christian Neukirchen - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -== Links - -Rack:: -Official Rack repositories:: -Rack Bug Tracking:: -rack-devel mailing list:: -Rack's Rubyforge project:: - -Christian Neukirchen:: - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/Rakefile b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/Rakefile deleted file mode 100644 index dcd253d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/Rakefile +++ /dev/null @@ -1,125 +0,0 @@ -# Rakefile for Rack. -*-ruby-*- - -desc "Run all the tests" -task :default => [:test] - -desc "Install gem dependencies" -task :deps do - require 'rubygems' - require 'rbconfig' - spec = Gem::Specification.load('rack.gemspec') - spec.dependencies.each do |dep| - reqs = dep.requirements_list - reqs = (["-v"] * reqs.size).zip(reqs).flatten - # Use system over sh, because we want to ignore errors! - system Gem.ruby, "-S", "gem", "install", '--conservative', dep.name, *reqs - end -end - -desc "Make an archive as .tar.gz" -task :dist => %w[chmod ChangeLog SPEC rdoc] do - sh "git archive --format=tar --prefix=#{release}/ HEAD^{tree} >#{release}.tar" - sh "pax -waf #{release}.tar -s ':^:#{release}/:' SPEC ChangeLog doc rack.gemspec" - sh "gzip -f -9 #{release}.tar" -end - -desc "Make an official release" -task :officialrelease do - puts "Official build for #{release}..." - sh "rm -rf stage" - sh "git clone --shared . stage" - sh "cd stage && rake officialrelease_really" - sh "mv stage/#{release}.tar.gz stage/#{release}.gem ." -end - -task :officialrelease_really => %w[SPEC dist gem] do - sh "sha1sum #{release}.tar.gz #{release}.gem" -end - -def release - "rack-#{File.read("rack.gemspec")[/s.version *= *"(.*?)"/, 1]}" -end - -desc "Make binaries executable" -task :chmod do - Dir["bin/*"].each { |binary| File.chmod(0775, binary) } - Dir["test/cgi/test*"].each { |binary| File.chmod(0775, binary) } -end - -desc "Generate a ChangeLog" -task :changelog => %w[ChangeLog] - -file '.git/index' -file "ChangeLog" => '.git/index' do - File.open("ChangeLog", "w") { |out| - log = `git log -z` - log.force_encoding(Encoding::BINARY) if log.respond_to?(:force_encoding) - log.split("\0").map { |chunk| - author = chunk[/Author: (.*)/, 1].strip - date = chunk[/Date: (.*)/, 1].strip - desc, detail = $'.strip.split("\n", 2) - detail ||= "" - detail = detail.gsub(/.*darcs-hash:.*/, '') - detail.rstrip! - out.puts "#{date} #{author}" - out.puts " * #{desc.strip}" - out.puts detail unless detail.empty? - out.puts - } - } -end - -file 'lib/rack/lint.rb' -desc "Generate Rack Specification" -file "SPEC" => 'lib/rack/lint.rb' do - File.open("SPEC", "wb") { |file| - IO.foreach("lib/rack/lint.rb") { |line| - if line =~ /## (.*)/ - file.puts $1 - end - } - } -end - -desc "Run all the fast + platform agnostic tests" -task :test => 'SPEC' do - opts = ENV['TEST'] || '-a' - specopts = ENV['TESTOPTS'] || - "-q -t '^(?!Rack::Adapter|Rack::Session::Memcache|Rack::Server|Rack::Handler)'" - - sh "bacon -w -I./lib:./test #{opts} #{specopts}" -end - -desc "Run all the tests we run on CI" -task :ci => :test - -desc "Run all the tests" -task :fulltest => %w[SPEC chmod] do - opts = ENV['TEST'] || '-a' - specopts = ENV['TESTOPTS'] || '-q' - sh "bacon -r./test/gemloader -I./lib:./test -w #{opts} #{specopts}" -end - -task :gem => ["SPEC"] do - sh "gem build rack.gemspec" -end - -task :doc => :rdoc -desc "Generate RDoc documentation" -task :rdoc => %w[ChangeLog SPEC] do - sh(*%w{rdoc --line-numbers --main README.rdoc - --title 'Rack\ Documentation' --charset utf-8 -U -o doc} + - %w{README.rdoc KNOWN-ISSUES SPEC ChangeLog} + - `git ls-files lib/\*\*/\*.rb`.strip.split) - cp "contrib/rdoc.css", "doc/rdoc.css" -end - -task :pushdoc => %w[rdoc] do - sh "rsync -avz doc/ rack.rubyforge.org:/var/www/gforge-projects/rack/doc/" -end - -task :pushsite => %w[pushdoc] do - sh "cd site && git gc" - sh "rsync -avz site/ rack.rubyforge.org:/var/www/gforge-projects/rack/" - sh "cd site && git push" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/SPEC b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/SPEC deleted file mode 100644 index 9b28627..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/SPEC +++ /dev/null @@ -1,237 +0,0 @@ -This specification aims to formalize the Rack protocol. You -can (and should) use Rack::Lint to enforce it. -When you develop middleware, be sure to add a Lint before and -after to catch all mistakes. -= Rack applications -A Rack application is a Ruby object (not a class) that -responds to +call+. -It takes exactly one argument, the *environment* -and returns an Array of exactly three values: -The *status*, -the *headers*, -and the *body*. -== The Environment -The environment must be an instance of Hash that includes -CGI-like headers. The application is free to modify the -environment. -The environment is required to include these variables -(adopted from PEP333), except when they'd be empty, but see -below. -REQUEST_METHOD:: The HTTP request method, such as - "GET" or "POST". This cannot ever - be an empty string, and so is - always required. -SCRIPT_NAME:: The initial portion of the request - URL's "path" that corresponds to the - application object, so that the - application knows its virtual - "location". This may be an empty - string, if the application corresponds - to the "root" of the server. -PATH_INFO:: The remainder of the request URL's - "path", designating the virtual - "location" of the request's target - within the application. This may be an - empty string, if the request URL targets - the application root and does not have a - trailing slash. This value may be - percent-encoded when I originating from - a URL. -QUERY_STRING:: The portion of the request URL that - follows the ?, if any. May be - empty, but is always required! -SERVER_NAME, SERVER_PORT:: When combined with SCRIPT_NAME and PATH_INFO, these variables can be used to complete the URL. Note, however, that HTTP_HOST, if present, should be used in preference to SERVER_NAME for reconstructing the request URL. SERVER_NAME and SERVER_PORT can never be empty strings, and so are always required. -HTTP_ Variables:: Variables corresponding to the - client-supplied HTTP request - headers (i.e., variables whose - names begin with HTTP_). The - presence or absence of these - variables should correspond with - the presence or absence of the - appropriate HTTP header in the - request. See - RFC3875 section 4.1.18 for specific behavior. -In addition to this, the Rack environment must include these -Rack-specific variables: -rack.version:: The Array representing this version of Rack. See Rack::VERSION, that corresponds to the version of this SPEC. -rack.url_scheme:: +http+ or +https+, depending on the request URL. -rack.input:: See below, the input stream. -rack.errors:: See below, the error stream. -rack.multithread:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise. -rack.multiprocess:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise. -rack.run_once:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar). -rack.hijack?:: present and true if the server supports connection hijacking. See below, hijacking. -rack.hijack:: an object responding to #call that must be called at least once before using rack.hijack_io. It is recommended #call return rack.hijack_io as well as setting it in env if necessary. -rack.hijack_io:: if rack.hijack? is true, and rack.hijack has received #call, this will contain an object resembling an IO. See hijacking. -Additional environment specifications have approved to -standardized middleware APIs. None of these are required to -be implemented by the server. -rack.session:: A hash like interface for storing request session data. - The store must implement: - store(key, value) (aliased as []=); - fetch(key, default = nil) (aliased as []); - delete(key); - clear; -rack.logger:: A common object interface for logging messages. - The object must implement: - info(message, &block) - debug(message, &block) - warn(message, &block) - error(message, &block) - fatal(message, &block) -The server or the application can store their own data in the -environment, too. The keys must contain at least one dot, -and should be prefixed uniquely. The prefix rack. -is reserved for use with the Rack core distribution and other -accepted specifications and must not be used otherwise. -The environment must not contain the keys -HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH -(use the versions without HTTP_). -The CGI keys (named without a period) must have String values. -There are the following restrictions: -* rack.version must be an array of Integers. -* rack.url_scheme must either be +http+ or +https+. -* There must be a valid input stream in rack.input. -* There must be a valid error stream in rack.errors. -* There may be a valid hijack stream in rack.hijack_io -* The REQUEST_METHOD must be a valid token. -* The SCRIPT_NAME, if non-empty, must start with / -* The PATH_INFO, if non-empty, must start with / -* The CONTENT_LENGTH, if given, must consist of digits only. -* One of SCRIPT_NAME or PATH_INFO must be - set. PATH_INFO should be / if - SCRIPT_NAME is empty. - SCRIPT_NAME never should be /, but instead be empty. -=== The Input Stream -The input stream is an IO-like object which contains the raw HTTP -POST data. -When applicable, its external encoding must be "ASCII-8BIT" and it -must be opened in binary mode, for Ruby 1.9 compatibility. -The input stream must respond to +gets+, +each+, +read+ and +rewind+. -* +gets+ must be called without arguments and return a string, - or +nil+ on EOF. -* +read+ behaves like IO#read. Its signature is read([length, [buffer]]). - If given, +length+ must be a non-negative Integer (>= 0) or +nil+, and +buffer+ must - be a String and may not be nil. If +length+ is given and not nil, then this method - reads at most +length+ bytes from the input stream. If +length+ is not given or nil, - then this method reads all data until EOF. - When EOF is reached, this method returns nil if +length+ is given and not nil, or "" - if +length+ is not given or is nil. - If +buffer+ is given, then the read data will be placed into +buffer+ instead of a - newly created String object. -* +each+ must be called without arguments and only yield Strings. -* +rewind+ must be called without arguments. It rewinds the input - stream back to the beginning. It must not raise Errno::ESPIPE: - that is, it may not be a pipe or a socket. Therefore, handler - developers must buffer the input data into some rewindable object - if the underlying input stream is not rewindable. -* +close+ must never be called on the input stream. -=== The Error Stream -The error stream must respond to +puts+, +write+ and +flush+. -* +puts+ must be called with a single argument that responds to +to_s+. -* +write+ must be called with a single argument that is a String. -* +flush+ must be called without arguments and must be called - in order to make the error appear for sure. -* +close+ must never be called on the error stream. -=== Hijacking -==== Request (before status) -If rack.hijack? is true then rack.hijack must respond to #call. -rack.hijack must return the io that will also be assigned (or is -already present, in rack.hijack_io. - -rack.hijack_io must respond to: -read, write, read_nonblock, write_nonblock, flush, close, -close_read, close_write, closed? - -The semantics of these IO methods must be a best effort match to -those of a normal ruby IO or Socket object, using standard -arguments and raising standard exceptions. Servers are encouraged -to simply pass on real IO objects, although it is recognized that -this approach is not directly compatible with SPDY and HTTP 2.0. - -IO provided in rack.hijack_io should preference the -IO::WaitReadable and IO::WaitWritable APIs wherever supported. - -There is a deliberate lack of full specification around -rack.hijack_io, as semantics will change from server to server. -Users are encouraged to utilize this API with a knowledge of their -server choice, and servers may extend the functionality of -hijack_io to provide additional features to users. The purpose of -rack.hijack is for Rack to "get out of the way", as such, Rack only -provides the minimum of specification and support. - -If rack.hijack? is false, then rack.hijack should not be set. - -If rack.hijack? is false, then rack.hijack_io should not be set. -==== Response (after headers) -It is also possible to hijack a response after the status and headers -have been sent. -In order to do this, an application may set the special header -rack.hijack to an object that responds to call -accepting an argument that conforms to the rack.hijack_io -protocol. - -After the headers have been sent, and this hijack callback has been -called, the application is now responsible for the remaining lifecycle -of the IO. The application is also responsible for maintaining HTTP -semantics. Of specific note, in almost all cases in the current SPEC, -applications will have wanted to specify the header Connection:close in -HTTP/1.1, and not Connection:keep-alive, as there is no protocol for -returning hijacked sockets to the web server. For that purpose, use the -body streaming API instead (progressively yielding strings via each). - -Servers must ignore the body part of the response tuple when -the rack.hijack response API is in use. - -The special response header rack.hijack must only be set -if the request env has rack.hijack? true. -==== Conventions -* Middleware should not use hijack unless it is handling the whole - response. -* Middleware may wrap the IO object for the response pattern. -* Middleware should not wrap the IO object for the request pattern. The - request pattern is intended to provide the hijacker with "raw tcp". -== The Response -=== The Status -This is an HTTP status. When parsed as integer (+to_i+), it must be -greater than or equal to 100. -=== The Headers -The header must respond to +each+, and yield values of key and value. -Special headers starting "rack." are for communicating with the -server, and must not be sent back to the client. -The header keys must be Strings. -The header must not contain a +Status+ key, -contain keys with : or newlines in their name, -contain keys names that end in - or _, -but only contain keys that consist of -letters, digits, _ or - and start with a letter. -The values of the header must be Strings, -consisting of lines (for multiple header values, e.g. multiple -Set-Cookie values) seperated by "\n". -The lines must not contain characters below 037. -=== The Content-Type -There must not be a Content-Type, when the +Status+ is 1xx, -204, 205 or 304. -=== The Content-Length -There must not be a Content-Length header when the -+Status+ is 1xx, 204, 205 or 304. -=== The Body -The Body must respond to +each+ -and must only yield String values. -The Body itself should not be an instance of String, as this will -break in Ruby 1.9. -If the Body responds to +close+, it will be called after iteration. If -the body is replaced by a middleware after action, the original body -must be closed first, if it repsonds to close. -If the Body responds to +to_path+, it must return a String -identifying the location of a file whose contents are identical -to that produced by calling +each+; this may be used by the -server as an alternative, possibly more efficient way to -transport the response. -The Body commonly is an Array of Strings, the application -instance itself, or a File-like object. -== Thanks -Some parts of this specification are adopted from PEP333: Python -Web Server Gateway Interface -v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank -everyone involved in that effort. diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/bin/rackup b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/bin/rackup deleted file mode 100755 index ad94af4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/bin/rackup +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby - -require "rack" -Rack::Server.start diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack.png b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack.png deleted file mode 100644 index 0920c4f..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack.png and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack.svg b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack.svg deleted file mode 100644 index 0d3f961..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack.svg +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack_logo.svg b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack_logo.svg deleted file mode 100644 index 434175a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rack_logo.svg +++ /dev/null @@ -1,111 +0,0 @@ - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rdoc.css b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rdoc.css deleted file mode 100644 index f1e342f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/contrib/rdoc.css +++ /dev/null @@ -1,412 +0,0 @@ -/* Forked from the Darkfish templates rdoc.css file, much hacked, probably - * imperfect */ - -html { max-width: 960px; margin: 0 auto; } -body { - font: 14px "Helvetica Neue", Helvetica, Tahoma, sans-serif; -} -body.file-popup { - font-size: 90%; - margin-left: 0; -} - -h1 { - color: #4183C4; -} - -:link, -:visited { - color: #4183C4; - text-decoration: none; -} -:link:hover, -:visited:hover { - border-bottom: 1px dotted #4183C4; -} - -pre, pre.description { - font: 12px Monaco,"Courier New","DejaVu Sans Mono","Bitstream Vera Sans Mono",monospace; - padding: 1em; - overflow: auto; - line-height: 1.4; -} - -/* @group Generic Classes */ - -.initially-hidden { - display: none; -} - -#search-field { - width: 98%; -} - -.missing-docs { - font-size: 120%; - background: white url(images/wrench_orange.png) no-repeat 4px center; - color: #ccc; - line-height: 2em; - border: 1px solid #d00; - opacity: 1; - text-indent: 24px; - letter-spacing: 3px; - font-weight: bold; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; -} - -.target-section { - border: 2px solid #dcce90; - border-left-width: 8px; - background: #fff3c2; -} - -/* @end */ - -/* @group Index Page, Standalone file pages */ -.indexpage ul { - line-height: 160%; - list-style: none; -} -.indexpage ul :link, -.indexpage ul :visited { - font-size: 16px; -} - -.indexpage li { - padding-left: 20px; -} - -.indexpage ul > li { - background: url(images/bullet_black.png) no-repeat left 4px; -} -.indexpage li.method { - background: url(images/plugin.png) no-repeat left 4px; -} -.indexpage li.module { - background: url(images/package.png) no-repeat left 4px; -} -.indexpage li.class { - background: url(images/ruby.png) no-repeat left 4px; -} -.indexpage li.file { - background: url(images/page_white_text.png) no-repeat left 4px; -} -.indexpage li li { - background: url(images/tag_blue.png) no-repeat left 4px; -} -.indexpage li .toc-toggle { - width: 16px; - height: 16px; - background: url(images/add.png) no-repeat; -} - -.indexpage li .toc-toggle.open { - background: url(images/delete.png) no-repeat; -} - -/* @end */ - -/* @group Top-Level Structure */ - -.project-section, #file-metadata, #class-metadata { - display: block; - background: #f5f5f5; - margin-bottom: 1em; - padding: 0.5em; -} -.project-section h3, #file-metadata h3, #class-metadata h3 { - margin: 0; -} - -#metadata { - float: left; - width: 280px; -} - -#documentation { - margin: 2em 1em 2em 300px; -} - -#validator-badges { - clear: both; - margin: 1em 1em 2em; - font-size: smaller; -} - -/* @end */ - -/* @group Metadata Section */ - -#metadata ul, -#metadata dl, -#metadata p { - padding: 0px; - list-style: none; -} - -dl.svninfo { - color: #666; - margin: 0; -} -dl.svninfo dt { - font-weight: bold; -} - -ul.link-list li { - white-space: nowrap; -} -ul.link-list .type { - font-size: 8px; - text-transform: uppercase; - color: white; - background: #969696; -} - -/* @end */ - -/* @group Documentation Section */ - -.note-list { - margin: 8px 0; -} - -.label-list { - margin: 8px 1.5em; - border: 1px solid #ccc; -} -.description .label-list { - font-size: 14px; -} - -.note-list dt { - font-weight: bold; -} -.note-list dd { -} - -.label-list dt { - font-weight: bold; - background: #ddd; -} -.label-list dd { -} -.label-list dd + dt, -.note-list dd + dt { - margin-top: 0.7em; -} - -#documentation .section { - font-size: 90%; -} - -#documentation h2.section-header { - color: #333; - font-size: 175%; -} - -.documentation-section-title { - position: relative; -} -.documentation-section-title .section-click-top { - position: absolute; - top: 6px; - right: 12px; - font-size: 10px; - visibility: hidden; -} - -.documentation-section-title:hover .section-click-top { - visibility: visible; -} - -#documentation h3.section-header { - color: #333; - font-size: 150%; -} - -#constants-list > dl, -#attributes-list > dl { - margin: 1em 0 2em; - border: 0; -} -#constants-list > dl dt, -#attributes-list > dl dt { - font-weight: bold; - font-family: Monaco, "Andale Mono"; - background: inherit; -} -#constants-list > dl dt a, -#attributes-list > dl dt a { - color: inherit; -} -#constants-list > dl dd, -#attributes-list > dl dd { - margin: 0 0 1em 0; - color: #666; -} - -.documentation-section h2 { - position: relative; -} - -.documentation-section h2 a { - position: absolute; - top: 8px; - right: 10px; - font-size: 12px; - color: #9b9877; - visibility: hidden; -} - -.documentation-section h2:hover a { - visibility: visible; -} - -/* @group Method Details */ - -#documentation .method-source-code { - display: none; -} - -#documentation .method-detail { - margin: 0.2em 0.2em; - padding: 0.5em; -} -#documentation .method-detail:hover { - background-color: #f5f5f5; -} -#documentation .method-heading { - cursor: pointer; - position: relative; - font-size: 125%; - line-height: 125%; - font-weight: bold; - color: #333; - background: url(images/brick.png) no-repeat left bottom; - padding-left: 20px; -} -#documentation .method-heading :link, -#documentation .method-heading :visited { - color: inherit; -} -#documentation .method-click-advice { - position: absolute; - right: 5px; - font-size: 10px; - color: #aaa; - visibility: hidden; - background: url(images/zoom.png) no-repeat right 5px; - padding-right: 20px; - overflow: show; -} -#documentation .method-heading:hover .method-click-advice { - visibility: visible; -} - -#documentation .method-alias .method-heading { - color: #666; - background: url(images/brick_link.png) no-repeat left bottom; -} - -#documentation .method-description, -#documentation .aliases { - margin: 0 20px; - color: #666; -} - -#documentation .method-description p, -#documentation .aliases p { - line-height: 1.2em; -} - -#documentation .aliases { - font-style: italic; - cursor: default; -} -#documentation .method-description p { - margin-bottom: 0.5em; -} -#documentation .method-description ul { - margin-left: 1.5em; -} - -#documentation .attribute-method-heading { - background: url(images/tag_green.png) no-repeat left bottom; -} -#documentation #attribute-method-details .method-detail:hover { - background-color: transparent; - cursor: default; -} -#documentation .attribute-access-type { - font-size: 60%; - text-transform: uppercase; - vertical-align: super; -} - -.method-section .method-source-code { - background: white; -} - -/* @group Source Code */ - -.ruby-constant .ruby-keyword .ruby-ivar .ruby-operator .ruby-identifier -.ruby-node .ruby-comment .ruby-regexp .ruby-value { - background: transparent; -} - -/* Thanks GitHub!!! */ -.ruby-constant { color: #458; font-weight: bold; } -.ruby-keyword { color: black; font-weight: bold; } -.ruby-ivar { color: teal; } -.ruby-operator { color: #000; } -.ruby-identifier { color: black; } -.ruby-node { color: red; } -.ruby-comment { color: #998; font-weight: bold; } -.ruby-regexp { color: #009926; } -.ruby-value { color: #099; } -.ruby-string { color: red; } - -/* @group search results */ - -#search-section .section-header { - margin: 0; - padding: 0; -} - -#search-results { - width: 100%; - list-style: none; - margin: 0; - padding: 0; -} - -#search-results h1 { - font-size: 1em; - font-weight: normal; - text-shadow: none; -} - -#search-results .current { - background: #eee; -} - -#search-results li { - list-style: none; - line-height: 1em; - padding: 0.5em; - border-bottom: 1px solid black; -} - -#search-results .search-namespace { - font-weight: bold; -} - -#search-results li em { - background: yellow; - font-style: normal; -} - -#search-results pre { - margin: 0.5em; -} diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/lobster.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/lobster.ru deleted file mode 100644 index cc7ffca..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/lobster.ru +++ /dev/null @@ -1,4 +0,0 @@ -require 'rack/lobster' - -use Rack::ShowExceptions -run Rack::Lobster.new diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/protectedlobster.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/protectedlobster.rb deleted file mode 100644 index d904b4c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/protectedlobster.rb +++ /dev/null @@ -1,14 +0,0 @@ -require 'rack' -require 'rack/lobster' - -lobster = Rack::Lobster.new - -protected_lobster = Rack::Auth::Basic.new(lobster) do |username, password| - 'secret' == password -end - -protected_lobster.realm = 'Lobster 2.0' - -pretty_protected_lobster = Rack::ShowStatus.new(Rack::ShowExceptions.new(protected_lobster)) - -Rack::Server.start :app => pretty_protected_lobster, :Port => 9292 diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/protectedlobster.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/protectedlobster.ru deleted file mode 100644 index b0da62f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/example/protectedlobster.ru +++ /dev/null @@ -1,8 +0,0 @@ -require 'rack/lobster' - -use Rack::ShowExceptions -use Rack::Auth::Basic, "Lobster 2.0" do |username, password| - 'secret' == password -end - -run Rack::Lobster.new diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack.rb deleted file mode 100644 index 57119df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack.rb +++ /dev/null @@ -1,87 +0,0 @@ -# Copyright (C) 2007, 2008, 2009, 2010 Christian Neukirchen -# -# Rack is freely distributable under the terms of an MIT-style license. -# See COPYING or http://www.opensource.org/licenses/mit-license.php. - -# The Rack main module, serving as a namespace for all core Rack -# modules and classes. -# -# All modules meant for use in your application are autoloaded here, -# so it should be enough just to require rack.rb in your code. - -module Rack - # The Rack protocol version number implemented. - VERSION = [1,2] - - # Return the Rack protocol version as a dotted string. - def self.version - VERSION.join(".") - end - - # Return the Rack release as a dotted string. - def self.release - "1.5" - end - - autoload :Builder, "rack/builder" - autoload :BodyProxy, "rack/body_proxy" - autoload :Cascade, "rack/cascade" - autoload :Chunked, "rack/chunked" - autoload :CommonLogger, "rack/commonlogger" - autoload :ConditionalGet, "rack/conditionalget" - autoload :Config, "rack/config" - autoload :ContentLength, "rack/content_length" - autoload :ContentType, "rack/content_type" - autoload :ETag, "rack/etag" - autoload :File, "rack/file" - autoload :Deflater, "rack/deflater" - autoload :Directory, "rack/directory" - autoload :ForwardRequest, "rack/recursive" - autoload :Handler, "rack/handler" - autoload :Head, "rack/head" - autoload :Lint, "rack/lint" - autoload :Lock, "rack/lock" - autoload :Logger, "rack/logger" - autoload :MethodOverride, "rack/methodoverride" - autoload :Mime, "rack/mime" - autoload :NullLogger, "rack/nulllogger" - autoload :Recursive, "rack/recursive" - autoload :Reloader, "rack/reloader" - autoload :Runtime, "rack/runtime" - autoload :Sendfile, "rack/sendfile" - autoload :Server, "rack/server" - autoload :ShowExceptions, "rack/showexceptions" - autoload :ShowStatus, "rack/showstatus" - autoload :Static, "rack/static" - autoload :URLMap, "rack/urlmap" - autoload :Utils, "rack/utils" - autoload :Multipart, "rack/multipart" - - autoload :MockRequest, "rack/mock" - autoload :MockResponse, "rack/mock" - - autoload :Request, "rack/request" - autoload :Response, "rack/response" - - module Auth - autoload :Basic, "rack/auth/basic" - autoload :AbstractRequest, "rack/auth/abstract/request" - autoload :AbstractHandler, "rack/auth/abstract/handler" - module Digest - autoload :MD5, "rack/auth/digest/md5" - autoload :Nonce, "rack/auth/digest/nonce" - autoload :Params, "rack/auth/digest/params" - autoload :Request, "rack/auth/digest/request" - end - end - - module Session - autoload :Cookie, "rack/session/cookie" - autoload :Pool, "rack/session/pool" - autoload :Memcache, "rack/session/memcache" - end - - module Utils - autoload :OkJson, "rack/utils/okjson" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/abstract/handler.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/abstract/handler.rb deleted file mode 100644 index 214df62..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/abstract/handler.rb +++ /dev/null @@ -1,37 +0,0 @@ -module Rack - module Auth - # Rack::Auth::AbstractHandler implements common authentication functionality. - # - # +realm+ should be set for all handlers. - - class AbstractHandler - - attr_accessor :realm - - def initialize(app, realm=nil, &authenticator) - @app, @realm, @authenticator = app, realm, authenticator - end - - - private - - def unauthorized(www_authenticate = challenge) - return [ 401, - { 'Content-Type' => 'text/plain', - 'Content-Length' => '0', - 'WWW-Authenticate' => www_authenticate.to_s }, - [] - ] - end - - def bad_request - return [ 400, - { 'Content-Type' => 'text/plain', - 'Content-Length' => '0' }, - [] - ] - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/abstract/request.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/abstract/request.rb deleted file mode 100644 index aa6bf8e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/abstract/request.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'rack/request' - -module Rack - module Auth - class AbstractRequest - - def initialize(env) - @env = env - end - - def request - @request ||= Request.new(@env) - end - - def provided? - !authorization_key.nil? - end - - def parts - @parts ||= @env[authorization_key].split(' ', 2) - end - - def scheme - @scheme ||= parts.first.downcase - end - - def params - @params ||= parts.last - end - - - private - - AUTHORIZATION_KEYS = ['HTTP_AUTHORIZATION', 'X-HTTP_AUTHORIZATION', 'X_HTTP_AUTHORIZATION'] - - def authorization_key - @authorization_key ||= AUTHORIZATION_KEYS.detect { |key| @env.has_key?(key) } - end - - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/basic.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/basic.rb deleted file mode 100644 index 7dd9a99..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/basic.rb +++ /dev/null @@ -1,58 +0,0 @@ -require 'rack/auth/abstract/handler' -require 'rack/auth/abstract/request' - -module Rack - module Auth - # Rack::Auth::Basic implements HTTP Basic Authentication, as per RFC 2617. - # - # Initialize with the Rack application that you want protecting, - # and a block that checks if a username and password pair are valid. - # - # See also: example/protectedlobster.rb - - class Basic < AbstractHandler - - def call(env) - auth = Basic::Request.new(env) - - return unauthorized unless auth.provided? - - return bad_request unless auth.basic? - - if valid?(auth) - env['REMOTE_USER'] = auth.username - - return @app.call(env) - end - - unauthorized - end - - - private - - def challenge - 'Basic realm="%s"' % realm - end - - def valid?(auth) - @authenticator.call(*auth.credentials) - end - - class Request < Auth::AbstractRequest - def basic? - !parts.first.nil? && "basic" == scheme - end - - def credentials - @credentials ||= params.unpack("m*").first.split(/:/, 2) - end - - def username - credentials.first - end - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/md5.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/md5.rb deleted file mode 100644 index b5871d7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/md5.rb +++ /dev/null @@ -1,129 +0,0 @@ -require 'rack/auth/abstract/handler' -require 'rack/auth/digest/request' -require 'rack/auth/digest/params' -require 'rack/auth/digest/nonce' -require 'digest/md5' - -module Rack - module Auth - module Digest - # Rack::Auth::Digest::MD5 implements the MD5 algorithm version of - # HTTP Digest Authentication, as per RFC 2617. - # - # Initialize with the [Rack] application that you want protecting, - # and a block that looks up a plaintext password for a given username. - # - # +opaque+ needs to be set to a constant base64/hexadecimal string. - # - class MD5 < AbstractHandler - - attr_accessor :opaque - - attr_writer :passwords_hashed - - def initialize(app, realm=nil, opaque=nil, &authenticator) - @passwords_hashed = nil - if opaque.nil? and realm.respond_to? :values_at - realm, opaque, @passwords_hashed = realm.values_at :realm, :opaque, :passwords_hashed - end - super(app, realm, &authenticator) - @opaque = opaque - end - - def passwords_hashed? - !!@passwords_hashed - end - - def call(env) - auth = Request.new(env) - - unless auth.provided? - return unauthorized - end - - if !auth.digest? || !auth.correct_uri? || !valid_qop?(auth) - return bad_request - end - - if valid?(auth) - if auth.nonce.stale? - return unauthorized(challenge(:stale => true)) - else - env['REMOTE_USER'] = auth.username - - return @app.call(env) - end - end - - unauthorized - end - - - private - - QOP = 'auth'.freeze - - def params(hash = {}) - Params.new do |params| - params['realm'] = realm - params['nonce'] = Nonce.new.to_s - params['opaque'] = H(opaque) - params['qop'] = QOP - - hash.each { |k, v| params[k] = v } - end - end - - def challenge(hash = {}) - "Digest #{params(hash)}" - end - - def valid?(auth) - valid_opaque?(auth) && valid_nonce?(auth) && valid_digest?(auth) - end - - def valid_qop?(auth) - QOP == auth.qop - end - - def valid_opaque?(auth) - H(opaque) == auth.opaque - end - - def valid_nonce?(auth) - auth.nonce.valid? - end - - def valid_digest?(auth) - pw = @authenticator.call(auth.username) - pw && digest(auth, pw) == auth.response - end - - def md5(data) - ::Digest::MD5.hexdigest(data) - end - - alias :H :md5 - - def KD(secret, data) - H([secret, data] * ':') - end - - def A1(auth, password) - [ auth.username, auth.realm, password ] * ':' - end - - def A2(auth) - [ auth.method, auth.uri ] * ':' - end - - def digest(auth, password) - password_hash = passwords_hashed? ? password : H(A1(auth, password)) - - KD(password_hash, [ auth.nonce, auth.nc, auth.cnonce, QOP, H(A2(auth)) ] * ':') - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/nonce.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/nonce.rb deleted file mode 100644 index 57089cb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/nonce.rb +++ /dev/null @@ -1,51 +0,0 @@ -require 'digest/md5' - -module Rack - module Auth - module Digest - # Rack::Auth::Digest::Nonce is the default nonce generator for the - # Rack::Auth::Digest::MD5 authentication handler. - # - # +private_key+ needs to set to a constant string. - # - # +time_limit+ can be optionally set to an integer (number of seconds), - # to limit the validity of the generated nonces. - - class Nonce - - class << self - attr_accessor :private_key, :time_limit - end - - def self.parse(string) - new(*string.unpack("m*").first.split(' ', 2)) - end - - def initialize(timestamp = Time.now, given_digest = nil) - @timestamp, @given_digest = timestamp.to_i, given_digest - end - - def to_s - [([ @timestamp, digest ] * ' ')].pack("m*").strip - end - - def digest - ::Digest::MD5.hexdigest([ @timestamp, self.class.private_key ] * ':') - end - - def valid? - digest == @given_digest - end - - def stale? - !self.class.time_limit.nil? && (Time.now.to_i - @timestamp) > self.class.time_limit - end - - def fresh? - !stale? - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/params.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/params.rb deleted file mode 100644 index f35a7ba..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/params.rb +++ /dev/null @@ -1,53 +0,0 @@ -module Rack - module Auth - module Digest - class Params < Hash - - def self.parse(str) - Params[*split_header_value(str).map do |param| - k, v = param.split('=', 2) - [k, dequote(v)] - end.flatten] - end - - def self.dequote(str) # From WEBrick::HTTPUtils - ret = (/\A"(.*)"\Z/ =~ str) ? $1 : str.dup - ret.gsub!(/\\(.)/, "\\1") - ret - end - - def self.split_header_value(str) - str.scan( /(\w+\=(?:"[^\"]+"|[^,]+))/n ).collect{ |v| v[0] } - end - - def initialize - super() - - yield self if block_given? - end - - def [](k) - super k.to_s - end - - def []=(k, v) - super k.to_s, v.to_s - end - - UNQUOTED = ['nc', 'stale'] - - def to_s - map do |k, v| - "#{k}=" + (UNQUOTED.include?(k) ? v.to_s : quote(v)) - end.join(', ') - end - - def quote(str) # From WEBrick::HTTPUtils - '"' << str.gsub(/[\\\"]/o, "\\\1") << '"' - end - - end - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/request.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/request.rb deleted file mode 100644 index 706c651..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/auth/digest/request.rb +++ /dev/null @@ -1,41 +0,0 @@ -require 'rack/auth/abstract/request' -require 'rack/auth/digest/params' -require 'rack/auth/digest/nonce' - -module Rack - module Auth - module Digest - class Request < Auth::AbstractRequest - def method - @env['rack.methodoverride.original_method'] || @env['REQUEST_METHOD'] - end - - def digest? - "digest" == scheme - end - - def correct_uri? - request.fullpath == uri - end - - def nonce - @nonce ||= Nonce.parse(params['nonce']) - end - - def params - @params ||= Params.parse(parts.last) - end - - def respond_to?(sym, *) - super or params.has_key? sym.to_s - end - - def method_missing(sym, *args) - return super unless params.has_key?(key = sym.to_s) - return params[key] if args.size == 0 - raise ArgumentError, "wrong number of arguments (#{args.size} for 0)" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_18.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_18.rb deleted file mode 100644 index 0ea1998..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_18.rb +++ /dev/null @@ -1,56 +0,0 @@ -# :stopdoc: - -# Stolen from ruby core's uri/common.rb, with modifications to support 1.8.x -# -# https://github.com/ruby/ruby/blob/trunk/lib/uri/common.rb -# -# - -module URI - TBLENCWWWCOMP_ = {} # :nodoc: - 256.times do |i| - TBLENCWWWCOMP_[i.chr] = '%%%02X' % i - end - TBLENCWWWCOMP_[' '] = '+' - TBLENCWWWCOMP_.freeze - TBLDECWWWCOMP_ = {} # :nodoc: - 256.times do |i| - h, l = i>>4, i&15 - TBLDECWWWCOMP_['%%%X%X' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%x%X' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%X%x' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%x%x' % [h, l]] = i.chr - end - TBLDECWWWCOMP_['+'] = ' ' - TBLDECWWWCOMP_.freeze - - # Encode given +s+ to URL-encoded form data. - # - # This method doesn't convert *, -, ., 0-9, A-Z, _, a-z, but does convert SP - # (ASCII space) to + and converts others to %XX. - # - # This is an implementation of - # http://www.w3.org/TR/html5/forms.html#url-encoded-form-data - # - # See URI.decode_www_form_component, URI.encode_www_form - def self.encode_www_form_component(s) - str = s.to_s - if RUBY_VERSION < "1.9" && $KCODE =~ /u/i - str.gsub(/([^ a-zA-Z0-9_.-]+)/) do - '%' + $1.unpack('H2' * Rack::Utils.bytesize($1)).join('%').upcase - end.tr(' ', '+') - else - str.gsub(/[^*\-.0-9A-Z_a-z]/) {|m| TBLENCWWWCOMP_[m]} - end - end - - # Decode given +str+ of URL-encoded form data. - # - # This decods + to SP. - # - # See URI.encode_www_form_component, URI.decode_www_form - def self.decode_www_form_component(str, enc=nil) - raise ArgumentError, "invalid %-encoding (#{str})" unless /\A(?:%[0-9a-fA-F]{2}|[^%])*\z/ =~ str - str.gsub(/\+|%[0-9a-fA-F]{2}/) {|m| TBLDECWWWCOMP_[m]} - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_192.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_192.rb deleted file mode 100644 index 1a0522b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_192.rb +++ /dev/null @@ -1,52 +0,0 @@ -# :stopdoc: - -# Stolen from ruby core's uri/common.rb @32618ba to fix DoS issues in 1.9.2 -# -# https://github.com/ruby/ruby/blob/32618ba7438a2247042bba9b5d85b5d49070f5e5/lib/uri/common.rb -# -# Issue: -# http://redmine.ruby-lang.org/issues/5149 -# -# Relevant Fixes: -# https://github.com/ruby/ruby/commit/b5f91deee04aa6ccbe07c23c8222b937c22a799b -# https://github.com/ruby/ruby/commit/93177c1e5c3906abf14472ae0b905d8b5c72ce1b -# -# This should probably be removed once there is a Ruby 1.9.2 patch level that -# includes this fix. - -require 'uri/common' - -module URI - TBLDECWWWCOMP_ = {} unless const_defined?(:TBLDECWWWCOMP_) #:nodoc: - if TBLDECWWWCOMP_.empty? - 256.times do |i| - h, l = i>>4, i&15 - TBLDECWWWCOMP_['%%%X%X' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%x%X' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%X%x' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%x%x' % [h, l]] = i.chr - end - TBLDECWWWCOMP_['+'] = ' ' - TBLDECWWWCOMP_.freeze - end - - def self.decode_www_form(str, enc=Encoding::UTF_8) - return [] if str.empty? - unless /\A#{WFKV_}=#{WFKV_}(?:[;&]#{WFKV_}=#{WFKV_})*\z/o =~ str - raise ArgumentError, "invalid data of application/x-www-form-urlencoded (#{str})" - end - ary = [] - $&.scan(/([^=;&]+)=([^;&]*)/) do - ary << [decode_www_form_component($1, enc), decode_www_form_component($2, enc)] - end - ary - end - - def self.decode_www_form_component(str, enc=Encoding::UTF_8) - raise ArgumentError, "invalid %-encoding (#{str})" unless /\A[^%]*(?:%\h\h[^%]*)*\z/ =~ str - str.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc) - end - - remove_const :WFKV_ if const_defined?(:WFKV_) - WFKV_ = '(?:[^%#=;&]*(?:%\h\h[^%#=;&]*)*)' # :nodoc: -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_193.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_193.rb deleted file mode 100644 index 2e58203..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/backports/uri/common_193.rb +++ /dev/null @@ -1,29 +0,0 @@ -# :stopdoc: - -require 'uri/common' - -# Issue: -# http://bugs.ruby-lang.org/issues/5925 -# -# Relevant commit: -# https://github.com/ruby/ruby/commit/edb7cdf1eabaff78dfa5ffedfbc2e91b29fa9ca1 - -module URI - 256.times do |i| - TBLENCWWWCOMP_[i.chr] = '%%%02X' % i - end - TBLENCWWWCOMP_[' '] = '+' - TBLENCWWWCOMP_.freeze - - 256.times do |i| - h, l = i>>4, i&15 - TBLDECWWWCOMP_['%%%X%X' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%x%X' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%X%x' % [h, l]] = i.chr - TBLDECWWWCOMP_['%%%x%x' % [h, l]] = i.chr - end - TBLDECWWWCOMP_['+'] = ' ' - TBLDECWWWCOMP_.freeze -end - -# :startdoc: diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/body_proxy.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/body_proxy.rb deleted file mode 100644 index 95a7462..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/body_proxy.rb +++ /dev/null @@ -1,39 +0,0 @@ -module Rack - class BodyProxy - def initialize(body, &block) - @body, @block, @closed = body, block, false - end - - def respond_to?(*args) - return false if args.first.to_s =~ /^to_ary$/ - super or @body.respond_to?(*args) - end - - def close - return if @closed - @closed = true - begin - @body.close if @body.respond_to? :close - ensure - @block.call - end - end - - def closed? - @closed - end - - # N.B. This method is a special case to address the bug described by #434. - # We are applying this special case for #each only. Future bugs of this - # class will be handled by requesting users to patch their ruby - # implementation, to save adding too many methods in this class. - def each(*args, &block) - @body.each(*args, &block) - end - - def method_missing(*args, &block) - super if args.first.to_s =~ /^to_ary$/ - @body.__send__(*args, &block) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb deleted file mode 100644 index 66dc7bd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/builder.rb +++ /dev/null @@ -1,149 +0,0 @@ -module Rack - # Rack::Builder implements a small DSL to iteratively construct Rack - # applications. - # - # Example: - # - # require 'rack/lobster' - # app = Rack::Builder.new do - # use Rack::CommonLogger - # use Rack::ShowExceptions - # map "/lobster" do - # use Rack::Lint - # run Rack::Lobster.new - # end - # end - # - # run app - # - # Or - # - # app = Rack::Builder.app do - # use Rack::CommonLogger - # run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] } - # end - # - # run app - # - # +use+ adds middleware to the stack, +run+ dispatches to an application. - # You can use +map+ to construct a Rack::URLMap in a convenient way. - - class Builder - def self.parse_file(config, opts = Server::Options.new) - options = {} - if config =~ /\.ru$/ - cfgfile = ::File.read(config) - if cfgfile[/^#\\(.*)/] && opts - options = opts.parse! $1.split(/\s+/) - end - cfgfile.sub!(/^__END__\n.*\Z/m, '') - app = new_from_string cfgfile, config - else - require config - app = Object.const_get(::File.basename(config, '.rb').capitalize) - end - return app, options - end - - def self.new_from_string(builder_script, file="(rackup)") - eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app", - TOPLEVEL_BINDING, file, 0 - end - - def initialize(default_app = nil,&block) - @use, @map, @run = [], nil, default_app - instance_eval(&block) if block_given? - end - - def self.app(default_app = nil, &block) - self.new(default_app, &block).to_app - end - - # Specifies middleware to use in a stack. - # - # class Middleware - # def initialize(app) - # @app = app - # end - # - # def call(env) - # env["rack.some_header"] = "setting an example" - # @app.call(env) - # end - # end - # - # use Middleware - # run lambda { |env| [200, { "Content-Type => "text/plain" }, ["OK"]] } - # - # All requests through to this application will first be processed by the middleware class. - # The +call+ method in this example sets an additional environment key which then can be - # referenced in the application if required. - def use(middleware, *args, &block) - if @map - mapping, @map = @map, nil - @use << proc { |app| generate_map app, mapping } - end - @use << proc { |app| middleware.new(app, *args, &block) } - end - - # Takes an argument that is an object that responds to #call and returns a Rack response. - # The simplest form of this is a lambda object: - # - # run lambda { |env| [200, { "Content-Type" => "text/plain" }, ["OK"]] } - # - # However this could also be a class: - # - # class Heartbeat - # def self.call(env) - # [200, { "Content-Type" => "text/plain" }, ["OK"]] - # end - # end - # - # run Heartbeat - def run(app) - @run = app - end - - # Creates a route within the application. - # - # Rack::Builder.app do - # map '/' do - # run Heartbeat - # end - # end - # - # The +use+ method can also be used here to specify middleware to run under a specific path: - # - # Rack::Builder.app do - # map '/' do - # use Middleware - # run Heartbeat - # end - # end - # - # This example includes a piece of middleware which will run before requests hit +Heartbeat+. - # - def map(path, &block) - @map ||= {} - @map[path] = block - end - - def to_app - app = @map ? generate_map(@run, @map) : @run - fail "missing run or map statement" unless app - @use.reverse.inject(app) { |a,e| e[a] } - end - - def call(env) - to_app.call(env) - end - - private - - def generate_map(default_app, mapping) - mapped = default_app ? {'/' => default_app} : {} - mapping.each { |r,b| mapped[r] = self.class.new(default_app, &b) } - URLMap.new(mapped) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/cascade.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/cascade.rb deleted file mode 100644 index d104a4b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/cascade.rb +++ /dev/null @@ -1,52 +0,0 @@ -module Rack - # Rack::Cascade tries a request on several apps, and returns the - # first response that is not 404 or 405 (or in a list of configurable - # status codes). - - class Cascade - NotFound = [404, {"Content-Type" => "text/plain"}, []] - - attr_reader :apps - - def initialize(apps, catch=[404, 405]) - @apps = []; @has_app = {} - apps.each { |app| add app } - - @catch = {} - [*catch].each { |status| @catch[status] = true } - end - - def call(env) - result = NotFound - - last_body = nil - - @apps.each do |app| - # The SPEC says that the body must be closed after it has been iterated - # by the server, or if it is replaced by a middleware action. Cascade - # replaces the body each time a cascade happens. It is assumed that nil - # does not respond to close, otherwise the previous application body - # will be closed. The final application body will not be closed, as it - # will be passed to the server as a result. - last_body.close if last_body.respond_to? :close - - result = app.call(env) - last_body = result[2] - break unless @catch.include?(result[0].to_i) - end - - result - end - - def add app - @has_app[app] = true - @apps << app - end - - def include? app - @has_app.include? app - end - - alias_method :<<, :add - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/chunked.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/chunked.rb deleted file mode 100644 index a400756..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/chunked.rb +++ /dev/null @@ -1,58 +0,0 @@ -require 'rack/utils' - -module Rack - - # Middleware that applies chunked transfer encoding to response bodies - # when the response does not include a Content-Length header. - class Chunked - include Rack::Utils - - # A body wrapper that emits chunked responses - class Body - TERM = "\r\n" - TAIL = "0#{TERM}#{TERM}" - - include Rack::Utils - - def initialize(body) - @body = body - end - - def each - term = TERM - @body.each do |chunk| - size = bytesize(chunk) - next if size == 0 - - chunk = chunk.dup.force_encoding(Encoding::BINARY) if chunk.respond_to?(:force_encoding) - yield [size.to_s(16), term, chunk, term].join - end - yield TAIL - end - - def close - @body.close if @body.respond_to?(:close) - end - end - - def initialize(app) - @app = app - end - - def call(env) - status, headers, body = @app.call(env) - headers = HeaderHash.new(headers) - - if env['HTTP_VERSION'] == 'HTTP/1.0' || - STATUS_WITH_NO_ENTITY_BODY.include?(status) || - headers['Content-Length'] || - headers['Transfer-Encoding'] - [status, headers, body] - else - headers.delete('Content-Length') - headers['Transfer-Encoding'] = 'chunked' - [status, headers, Body.new(body)] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/commonlogger.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/commonlogger.rb deleted file mode 100644 index 7028615..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/commonlogger.rb +++ /dev/null @@ -1,64 +0,0 @@ -require 'rack/body_proxy' - -module Rack - # Rack::CommonLogger forwards every request to the given +app+, and - # logs a line in the - # {Apache common log format}[http://httpd.apache.org/docs/1.3/logs.html#common] - # to the +logger+. - # - # If +logger+ is nil, CommonLogger will fall back +rack.errors+, which is - # an instance of Rack::NullLogger. - # - # +logger+ can be any class, including the standard library Logger, and is - # expected to have a +write+ method, which accepts the CommonLogger::FORMAT. - # According to the SPEC, the error stream must also respond to +puts+ - # (which takes a single argument that responds to +to_s+), and +flush+ - # (which is called without arguments in order to make the error appear for - # sure) - class CommonLogger - # Common Log Format: http://httpd.apache.org/docs/1.3/logs.html#common - # - # lilith.local - - [07/Aug/2006 23:58:02] "GET / HTTP/1.1" 500 - - # - # %{%s - %s [%s] "%s %s%s %s" %d %s\n} % - FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n} - - def initialize(app, logger=nil) - @app = app - @logger = logger - end - - def call(env) - began_at = Time.now - status, header, body = @app.call(env) - header = Utils::HeaderHash.new(header) - body = BodyProxy.new(body) { log(env, status, header, began_at) } - [status, header, body] - end - - private - - def log(env, status, header, began_at) - now = Time.now - length = extract_content_length(header) - - logger = @logger || env['rack.errors'] - logger.write FORMAT % [ - env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"] || "-", - env["REMOTE_USER"] || "-", - now.strftime("%d/%b/%Y %H:%M:%S"), - env["REQUEST_METHOD"], - env["PATH_INFO"], - env["QUERY_STRING"].empty? ? "" : "?"+env["QUERY_STRING"], - env["HTTP_VERSION"], - status.to_s[0..3], - length, - now - began_at ] - end - - def extract_content_length(headers) - value = headers['Content-Length'] or return '-' - value.to_s == '0' ? '-' : value - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/conditionalget.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/conditionalget.rb deleted file mode 100644 index 014e22f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/conditionalget.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'rack/utils' - -module Rack - - # Middleware that enables conditional GET using If-None-Match and - # If-Modified-Since. The application should set either or both of the - # Last-Modified or Etag response headers according to RFC 2616. When - # either of the conditions is met, the response body is set to be zero - # length and the response status is set to 304 Not Modified. - # - # Applications that defer response body generation until the body's each - # message is received will avoid response body generation completely when - # a conditional GET matches. - # - # Adapted from Michael Klishin's Merb implementation: - # https://github.com/wycats/merb/blob/master/merb-core/lib/merb-core/rack/middleware/conditional_get.rb - class ConditionalGet - def initialize(app) - @app = app - end - - def call(env) - case env['REQUEST_METHOD'] - when "GET", "HEAD" - status, headers, body = @app.call(env) - headers = Utils::HeaderHash.new(headers) - if status == 200 && fresh?(env, headers) - status = 304 - headers.delete('Content-Type') - headers.delete('Content-Length') - body = [] - end - [status, headers, body] - else - @app.call(env) - end - end - - private - - def fresh?(env, headers) - modified_since = env['HTTP_IF_MODIFIED_SINCE'] - none_match = env['HTTP_IF_NONE_MATCH'] - - return false unless modified_since || none_match - - success = true - success &&= modified_since?(to_rfc2822(modified_since), headers) if modified_since - success &&= etag_matches?(none_match, headers) if none_match - success - end - - def etag_matches?(none_match, headers) - etag = headers['ETag'] and etag == none_match - end - - def modified_since?(modified_since, headers) - last_modified = to_rfc2822(headers['Last-Modified']) and - modified_since and - modified_since >= last_modified - end - - def to_rfc2822(since) - Time.rfc2822(since) rescue nil - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/config.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/config.rb deleted file mode 100644 index dc255d2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/config.rb +++ /dev/null @@ -1,20 +0,0 @@ -module Rack - # Rack::Config modifies the environment using the block given during - # initialization. - # - # Example: - # use Rack::Config do |env| - # env['my-key'] = 'some-value' - # end - class Config - def initialize(app, &block) - @app = app - @block = block - end - - def call(env) - @block.call(env) - @app.call(env) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_length.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_length.rb deleted file mode 100644 index 634bdc4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_length.rb +++ /dev/null @@ -1,33 +0,0 @@ -require 'rack/utils' - -module Rack - - # Sets the Content-Length header on responses with fixed-length bodies. - class ContentLength - include Rack::Utils - - def initialize(app) - @app = app - end - - def call(env) - status, headers, body = @app.call(env) - headers = HeaderHash.new(headers) - - if !STATUS_WITH_NO_ENTITY_BODY.include?(status.to_i) && - !headers['Content-Length'] && - !headers['Transfer-Encoding'] && - body.respond_to?(:to_ary) - - obody = body - body, length = [], 0 - obody.each { |part| body << part; length += bytesize(part) } - obody.close if obody.respond_to?(:close) - - headers['Content-Length'] = length.to_s - end - - [status, headers, body] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_type.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_type.rb deleted file mode 100644 index dd96e95..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/content_type.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'rack/utils' - -module Rack - - # Sets the Content-Type header on responses which don't have one. - # - # Builder Usage: - # use Rack::ContentType, "text/plain" - # - # When no content type argument is provided, "text/html" is assumed. - class ContentType - include Rack::Utils - - def initialize(app, content_type = "text/html") - @app, @content_type = app, content_type - end - - def call(env) - status, headers, body = @app.call(env) - headers = Utils::HeaderHash.new(headers) - - unless STATUS_WITH_NO_ENTITY_BODY.include?(status) - headers['Content-Type'] ||= @content_type - end - - [status, headers, body] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/deflater.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/deflater.rb deleted file mode 100644 index 2f219f0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/deflater.rb +++ /dev/null @@ -1,116 +0,0 @@ -require "zlib" -require "stringio" -require "time" # for Time.httpdate -require 'rack/utils' - -module Rack - # This middleware enables compression of http responses. - # - # Currently supported compression algorithms: - # - # * gzip - # * deflate - # * identity (no transformation) - # - # The middleware automatically detects when compression is supported - # and allowed. For example no transformation is made when a cache - # directive of 'no-transform' is present, or when the response status - # code is one that doesn't allow an entity body. - class Deflater - def initialize(app) - @app = app - end - - def call(env) - status, headers, body = @app.call(env) - headers = Utils::HeaderHash.new(headers) - - # Skip compressing empty entity body responses and responses with - # no-transform set. - if Utils::STATUS_WITH_NO_ENTITY_BODY.include?(status) || - headers['Cache-Control'].to_s =~ /\bno-transform\b/ || - (headers['Content-Encoding'] && headers['Content-Encoding'] !~ /\bidentity\b/) - return [status, headers, body] - end - - request = Request.new(env) - - encoding = Utils.select_best_encoding(%w(gzip deflate identity), - request.accept_encoding) - - # Set the Vary HTTP header. - vary = headers["Vary"].to_s.split(",").map { |v| v.strip } - unless vary.include?("*") || vary.include?("Accept-Encoding") - headers["Vary"] = vary.push("Accept-Encoding").join(",") - end - - case encoding - when "gzip" - headers['Content-Encoding'] = "gzip" - headers.delete('Content-Length') - mtime = headers.key?("Last-Modified") ? - Time.httpdate(headers["Last-Modified"]) : Time.now - [status, headers, GzipStream.new(body, mtime)] - when "deflate" - headers['Content-Encoding'] = "deflate" - headers.delete('Content-Length') - [status, headers, DeflateStream.new(body)] - when "identity" - [status, headers, body] - when nil - body.close if body.respond_to?(:close) - message = "An acceptable encoding for the requested resource #{request.fullpath} could not be found." - [406, {"Content-Type" => "text/plain", "Content-Length" => message.length.to_s}, [message]] - end - end - - class GzipStream - def initialize(body, mtime) - @body = body - @mtime = mtime - end - - def each(&block) - @writer = block - gzip =::Zlib::GzipWriter.new(self) - gzip.mtime = @mtime - @body.each { |part| - gzip.write(part) - gzip.flush - } - ensure - @body.close if @body.respond_to?(:close) - gzip.close - @writer = nil - end - - def write(data) - @writer.call(data) - end - end - - class DeflateStream - DEFLATE_ARGS = [ - Zlib::DEFAULT_COMPRESSION, - # drop the zlib header which causes both Safari and IE to choke - -Zlib::MAX_WBITS, - Zlib::DEF_MEM_LEVEL, - Zlib::DEFAULT_STRATEGY - ] - - def initialize(body) - @body = body - end - - def each - deflater = ::Zlib::Deflate.new(*DEFLATE_ARGS) - @body.each { |part| yield deflater.deflate(part, Zlib::SYNC_FLUSH) } - yield deflater.finish - nil - ensure - @body.close if @body.respond_to?(:close) - deflater.close - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/directory.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/directory.rb deleted file mode 100644 index e90ee08..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/directory.rb +++ /dev/null @@ -1,161 +0,0 @@ -require 'time' -require 'rack/utils' -require 'rack/mime' - -module Rack - # Rack::Directory serves entries below the +root+ given, according to the - # path info of the Rack request. If a directory is found, the file's contents - # will be presented in an html based index. If a file is found, the env will - # be passed to the specified +app+. - # - # If +app+ is not specified, a Rack::File of the same +root+ will be used. - - class Directory - DIR_FILE = "%s%s%s%s" - DIR_PAGE = <<-PAGE - - %s - - - -

%s

-
- - - - - - - -%s -
NameSizeTypeLast Modified
-
- - PAGE - - attr_reader :files - attr_accessor :root, :path - - def initialize(root, app=nil) - @root = F.expand_path(root) - @app = app || Rack::File.new(@root) - end - - def call(env) - dup._call(env) - end - - F = ::File - - def _call(env) - @env = env - @script_name = env['SCRIPT_NAME'] - @path_info = Utils.unescape(env['PATH_INFO']) - - if forbidden = check_forbidden - forbidden - else - @path = F.join(@root, @path_info) - list_path - end - end - - def check_forbidden - return unless @path_info.include? ".." - - body = "Forbidden\n" - size = Rack::Utils.bytesize(body) - return [403, {"Content-Type" => "text/plain", - "Content-Length" => size.to_s, - "X-Cascade" => "pass"}, [body]] - end - - def list_directory - @files = [['../','Parent Directory','','','']] - glob = F.join(@path, '*') - - url_head = (@script_name.split('/') + @path_info.split('/')).map do |part| - Rack::Utils.escape part - end - - Dir[glob].sort.each do |node| - stat = stat(node) - next unless stat - basename = F.basename(node) - ext = F.extname(node) - - url = F.join(*url_head + [Rack::Utils.escape(basename)]) - size = stat.size - type = stat.directory? ? 'directory' : Mime.mime_type(ext) - size = stat.directory? ? '-' : filesize_format(size) - mtime = stat.mtime.httpdate - url << '/' if stat.directory? - basename << '/' if stat.directory? - - @files << [ url, basename, size, type, mtime ] - end - - return [ 200, {'Content-Type'=>'text/html; charset=utf-8'}, self ] - end - - def stat(node, max = 10) - F.stat(node) - rescue Errno::ENOENT, Errno::ELOOP - return nil - end - - # TODO: add correct response if not readable, not sure if 404 is the best - # option - def list_path - @stat = F.stat(@path) - - if @stat.readable? - return @app.call(@env) if @stat.file? - return list_directory if @stat.directory? - else - raise Errno::ENOENT, 'No such file or directory' - end - - rescue Errno::ENOENT, Errno::ELOOP - return entity_not_found - end - - def entity_not_found - body = "Entity not found: #{@path_info}\n" - size = Rack::Utils.bytesize(body) - return [404, {"Content-Type" => "text/plain", - "Content-Length" => size.to_s, - "X-Cascade" => "pass"}, [body]] - end - - def each - show_path = @path.sub(/^#{@root}/,'') - files = @files.map{|f| DIR_FILE % f }*"\n" - page = DIR_PAGE % [ show_path, show_path , files ] - page.each_line{|l| yield l } - end - - # Stolen from Ramaze - - FILESIZE_FORMAT = [ - ['%.1fT', 1 << 40], - ['%.1fG', 1 << 30], - ['%.1fM', 1 << 20], - ['%.1fK', 1 << 10], - ] - - def filesize_format(int) - FILESIZE_FORMAT.each do |format, size| - return format % (int.to_f / size) if int >= size - end - - int.to_s + 'B' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/etag.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/etag.rb deleted file mode 100644 index 3f5006a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/etag.rb +++ /dev/null @@ -1,64 +0,0 @@ -require 'digest/md5' - -module Rack - # Automatically sets the ETag header on all String bodies. - # - # The ETag header is skipped if ETag or Last-Modified headers are sent or if - # a sendfile body (body.responds_to :to_path) is given (since such cases - # should be handled by apache/nginx). - # - # On initialization, you can pass two parameters: a Cache-Control directive - # used when Etag is absent and a directive when it is present. The first - # defaults to nil, while the second defaults to "max-age=0, private, must-revalidate" - class ETag - DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze - - def initialize(app, no_cache_control = nil, cache_control = DEFAULT_CACHE_CONTROL) - @app = app - @cache_control = cache_control - @no_cache_control = no_cache_control - end - - def call(env) - status, headers, body = @app.call(env) - - if etag_status?(status) && etag_body?(body) && !skip_caching?(headers) - digest, body = digest_body(body) - headers['ETag'] = %("#{digest}") if digest - end - - unless headers['Cache-Control'] - if digest - headers['Cache-Control'] = @cache_control if @cache_control - else - headers['Cache-Control'] = @no_cache_control if @no_cache_control - end - end - - [status, headers, body] - end - - private - - def etag_status?(status) - status == 200 || status == 201 - end - - def etag_body?(body) - !body.respond_to?(:to_path) - end - - def skip_caching?(headers) - (headers['Cache-Control'] && headers['Cache-Control'].include?('no-cache')) || - headers.key?('ETag') || headers.key?('Last-Modified') - end - - def digest_body(body) - parts = [] - body.each { |part| parts << part } - string_body = parts.join - digest = Digest::MD5.hexdigest(string_body) unless string_body.empty? - [digest, parts] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/file.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/file.rb deleted file mode 100644 index ee58a1a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/file.rb +++ /dev/null @@ -1,138 +0,0 @@ -require 'time' -require 'rack/utils' -require 'rack/mime' - -module Rack - # Rack::File serves files below the +root+ directory given, according to the - # path info of the Rack request. - # e.g. when Rack::File.new("/etc") is used, you can access 'passwd' file - # as http://localhost:9292/passwd - # - # Handlers can detect if bodies are a Rack::File, and use mechanisms - # like sendfile on the +path+. - - class File - SEPS = Regexp.union(*[::File::SEPARATOR, ::File::ALT_SEPARATOR].compact) - ALLOWED_VERBS = %w[GET HEAD] - - attr_accessor :root - attr_accessor :path - attr_accessor :cache_control - - alias :to_path :path - - def initialize(root, headers={}, default_mime = 'text/plain') - @root = root - @headers = headers - @default_mime = default_mime - end - - def call(env) - dup._call(env) - end - - F = ::File - - def _call(env) - unless ALLOWED_VERBS.include? env["REQUEST_METHOD"] - return fail(405, "Method Not Allowed") - end - - path_info = Utils.unescape(env["PATH_INFO"]) - parts = path_info.split SEPS - - clean = [] - - parts.each do |part| - next if part.empty? || part == '.' - part == '..' ? clean.pop : clean << part - end - - @path = F.join(@root, *clean) - - available = begin - F.file?(@path) && F.readable?(@path) - rescue SystemCallError - false - end - - if available - serving(env) - else - fail(404, "File not found: #{path_info}") - end - end - - def serving(env) - last_modified = F.mtime(@path).httpdate - return [304, {}, []] if env['HTTP_IF_MODIFIED_SINCE'] == last_modified - - headers = { "Last-Modified" => last_modified } - mime = Mime.mime_type(F.extname(@path), @default_mime) - headers["Content-Type"] = mime if mime - - # Set custom headers - @headers.each { |field, content| headers[field] = content } if @headers - - response = [ 200, headers, env["REQUEST_METHOD"] == "HEAD" ? [] : self ] - - # NOTE: - # We check via File::size? whether this file provides size info - # via stat (e.g. /proc files often don't), otherwise we have to - # figure it out by reading the whole file into memory. - size = F.size?(@path) || Utils.bytesize(F.read(@path)) - - ranges = Rack::Utils.byte_ranges(env, size) - if ranges.nil? || ranges.length > 1 - # No ranges, or multiple ranges (which we don't support): - # TODO: Support multiple byte-ranges - response[0] = 200 - @range = 0..size-1 - elsif ranges.empty? - # Unsatisfiable. Return error, and file size: - response = fail(416, "Byte range unsatisfiable") - response[1]["Content-Range"] = "bytes */#{size}" - return response - else - # Partial content: - @range = ranges[0] - response[0] = 206 - response[1]["Content-Range"] = "bytes #{@range.begin}-#{@range.end}/#{size}" - size = @range.end - @range.begin + 1 - end - - response[1]["Content-Length"] = size.to_s - response - end - - def each - F.open(@path, "rb") do |file| - file.seek(@range.begin) - remaining_len = @range.end-@range.begin+1 - while remaining_len > 0 - part = file.read([8192, remaining_len].min) - break unless part - remaining_len -= part.length - - yield part - end - end - end - - private - - def fail(status, body) - body += "\n" - [ - status, - { - "Content-Type" => "text/plain", - "Content-Length" => body.size.to_s, - "X-Cascade" => "pass" - }, - [body] - ] - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler.rb deleted file mode 100644 index 155dbfa..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler.rb +++ /dev/null @@ -1,107 +0,0 @@ -module Rack - # *Handlers* connect web servers with Rack. - # - # Rack includes Handlers for Thin, WEBrick, FastCGI, CGI, SCGI - # and LiteSpeed. - # - # Handlers usually are activated by calling MyHandler.run(myapp). - # A second optional hash can be passed to include server-specific - # configuration. - module Handler - def self.get(server) - return unless server - server = server.to_s - - unless @handlers.include? server - load_error = try_require('rack/handler', server) - end - - if klass = @handlers[server] - klass.split("::").inject(Object) { |o, x| o.const_get(x) } - else - const_get(server) - end - - rescue NameError => name_error - raise load_error || name_error - end - - # Select first available Rack handler given an `Array` of server names. - # Raises `LoadError` if no handler was found. - # - # > pick ['thin', 'webrick'] - # => Rack::Handler::WEBrick - def self.pick(server_names) - server_names = Array(server_names) - server_names.each do |server_name| - begin - return get(server_name.to_s) - rescue LoadError, NameError - end - end - - raise LoadError, "Couldn't find handler for: #{server_names.join(', ')}." - end - - def self.default(options = {}) - # Guess. - if ENV.include?("PHP_FCGI_CHILDREN") - # We already speak FastCGI - options.delete :File - options.delete :Port - - Rack::Handler::FastCGI - elsif ENV.include?("REQUEST_METHOD") - Rack::Handler::CGI - else - pick ['thin', 'puma', 'webrick'] - end - end - - # Transforms server-name constants to their canonical form as filenames, - # then tries to require them but silences the LoadError if not found - # - # Naming convention: - # - # Foo # => 'foo' - # FooBar # => 'foo_bar.rb' - # FooBAR # => 'foobar.rb' - # FOObar # => 'foobar.rb' - # FOOBAR # => 'foobar.rb' - # FooBarBaz # => 'foo_bar_baz.rb' - def self.try_require(prefix, const_name) - file = const_name.gsub(/^[A-Z]+/) { |pre| pre.downcase }. - gsub(/[A-Z]+[^A-Z]/, '_\&').downcase - - require(::File.join(prefix, file)) - nil - rescue LoadError => error - error - end - - def self.register(server, klass) - @handlers ||= {} - @handlers[server.to_s] = klass.to_s - end - - autoload :CGI, "rack/handler/cgi" - autoload :FastCGI, "rack/handler/fastcgi" - autoload :Mongrel, "rack/handler/mongrel" - autoload :EventedMongrel, "rack/handler/evented_mongrel" - autoload :SwiftipliedMongrel, "rack/handler/swiftiplied_mongrel" - autoload :WEBrick, "rack/handler/webrick" - autoload :LSWS, "rack/handler/lsws" - autoload :SCGI, "rack/handler/scgi" - autoload :Thin, "rack/handler/thin" - - register 'cgi', 'Rack::Handler::CGI' - register 'fastcgi', 'Rack::Handler::FastCGI' - register 'mongrel', 'Rack::Handler::Mongrel' - register 'emongrel', 'Rack::Handler::EventedMongrel' - register 'smongrel', 'Rack::Handler::SwiftipliedMongrel' - register 'webrick', 'Rack::Handler::WEBrick' - register 'lsws', 'Rack::Handler::LSWS' - register 'scgi', 'Rack::Handler::SCGI' - register 'thin', 'Rack::Handler::Thin' - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/cgi.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/cgi.rb deleted file mode 100644 index 15af1ac..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/cgi.rb +++ /dev/null @@ -1,61 +0,0 @@ -require 'rack/content_length' -require 'rack/rewindable_input' - -module Rack - module Handler - class CGI - def self.run(app, options=nil) - $stdin.binmode - serve app - end - - def self.serve(app) - env = ENV.to_hash - env.delete "HTTP_CONTENT_LENGTH" - - env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" - - env.update({"rack.version" => Rack::VERSION, - "rack.input" => Rack::RewindableInput.new($stdin), - "rack.errors" => $stderr, - - "rack.multithread" => false, - "rack.multiprocess" => true, - "rack.run_once" => true, - - "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http" - }) - - env["QUERY_STRING"] ||= "" - env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] - env["REQUEST_PATH"] ||= "/" - - status, headers, body = app.call(env) - begin - send_headers status, headers - send_body body - ensure - body.close if body.respond_to? :close - end - end - - def self.send_headers(status, headers) - $stdout.print "Status: #{status}\r\n" - headers.each { |k, vs| - vs.split("\n").each { |v| - $stdout.print "#{k}: #{v}\r\n" - } - } - $stdout.print "\r\n" - $stdout.flush - end - - def self.send_body(body) - body.each { |part| - $stdout.print part - $stdout.flush - } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/evented_mongrel.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/evented_mongrel.rb deleted file mode 100644 index 0f5cbf7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/evented_mongrel.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'swiftcore/evented_mongrel' - -module Rack - module Handler - class EventedMongrel < Handler::Mongrel - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/fastcgi.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/fastcgi.rb deleted file mode 100644 index 340e361..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/fastcgi.rb +++ /dev/null @@ -1,98 +0,0 @@ -require 'fcgi' -require 'socket' -require 'rack/content_length' -require 'rack/rewindable_input' - -if defined? FCGI::Stream - class FCGI::Stream - alias _rack_read_without_buffer read - - def read(n, buffer=nil) - buf = _rack_read_without_buffer n - buffer.replace(buf.to_s) if buffer - buf - end - end -end - -module Rack - module Handler - class FastCGI - def self.run(app, options={}) - if options[:File] - STDIN.reopen(UNIXServer.new(options[:File])) - elsif options[:Port] - STDIN.reopen(TCPServer.new(options[:Host], options[:Port])) - end - FCGI.each { |request| - serve request, app - } - end - - def self.valid_options - { - "Host=HOST" => "Hostname to listen on (default: localhost)", - "Port=PORT" => "Port to listen on (default: 8080)", - "File=PATH" => "Creates a Domain socket at PATH instead of a TCP socket. Ignores Host and Port if set.", - } - end - - def self.serve(request, app) - env = request.env - env.delete "HTTP_CONTENT_LENGTH" - - env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" - - rack_input = RewindableInput.new(request.in) - - env.update({"rack.version" => Rack::VERSION, - "rack.input" => rack_input, - "rack.errors" => request.err, - - "rack.multithread" => false, - "rack.multiprocess" => true, - "rack.run_once" => false, - - "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" - }) - - env["QUERY_STRING"] ||= "" - env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] - env["REQUEST_PATH"] ||= "/" - env.delete "CONTENT_TYPE" if env["CONTENT_TYPE"] == "" - env.delete "CONTENT_LENGTH" if env["CONTENT_LENGTH"] == "" - - begin - status, headers, body = app.call(env) - begin - send_headers request.out, status, headers - send_body request.out, body - ensure - body.close if body.respond_to? :close - end - ensure - rack_input.close - request.finish - end - end - - def self.send_headers(out, status, headers) - out.print "Status: #{status}\r\n" - headers.each { |k, vs| - vs.split("\n").each { |v| - out.print "#{k}: #{v}\r\n" - } - } - out.print "\r\n" - out.flush - end - - def self.send_body(out, body) - body.each { |part| - out.print part - out.flush - } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/lsws.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/lsws.rb deleted file mode 100644 index 1dee78a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/lsws.rb +++ /dev/null @@ -1,61 +0,0 @@ -require 'lsapi' -require 'rack/content_length' -require 'rack/rewindable_input' - -module Rack - module Handler - class LSWS - def self.run(app, options=nil) - while LSAPI.accept != nil - serve app - end - end - def self.serve(app) - env = ENV.to_hash - env.delete "HTTP_CONTENT_LENGTH" - env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" - - rack_input = RewindableInput.new($stdin.read.to_s) - - env.update( - "rack.version" => Rack::VERSION, - "rack.input" => rack_input, - "rack.errors" => $stderr, - "rack.multithread" => false, - "rack.multiprocess" => true, - "rack.run_once" => false, - "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http" - ) - - env["QUERY_STRING"] ||= "" - env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] - env["REQUEST_PATH"] ||= "/" - status, headers, body = app.call(env) - begin - send_headers status, headers - send_body body - ensure - body.close if body.respond_to? :close - end - ensure - rack_input.close - end - def self.send_headers(status, headers) - print "Status: #{status}\r\n" - headers.each { |k, vs| - vs.split("\n").each { |v| - print "#{k}: #{v}\r\n" - } - } - print "\r\n" - STDOUT.flush - end - def self.send_body(body) - body.each { |part| - print part - STDOUT.flush - } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/mongrel.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/mongrel.rb deleted file mode 100644 index 1a702fd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/mongrel.rb +++ /dev/null @@ -1,100 +0,0 @@ -require 'mongrel' -require 'stringio' -require 'rack/content_length' -require 'rack/chunked' - -module Rack - module Handler - class Mongrel < ::Mongrel::HttpHandler - def self.run(app, options={}) - server = ::Mongrel::HttpServer.new( - options[:Host] || '0.0.0.0', - options[:Port] || 8080, - options[:num_processors] || 950, - options[:throttle] || 0, - options[:timeout] || 60) - # Acts like Rack::URLMap, utilizing Mongrel's own path finding methods. - # Use is similar to #run, replacing the app argument with a hash of - # { path=>app, ... } or an instance of Rack::URLMap. - if options[:map] - if app.is_a? Hash - app.each do |path, appl| - path = '/'+path unless path[0] == ?/ - server.register(path, Rack::Handler::Mongrel.new(appl)) - end - elsif app.is_a? URLMap - app.instance_variable_get(:@mapping).each do |(host, path, appl)| - next if !host.nil? && !options[:Host].nil? && options[:Host] != host - path = '/'+path unless path[0] == ?/ - server.register(path, Rack::Handler::Mongrel.new(appl)) - end - else - raise ArgumentError, "first argument should be a Hash or URLMap" - end - else - server.register('/', Rack::Handler::Mongrel.new(app)) - end - yield server if block_given? - server.run.join - end - - def self.valid_options - { - "Host=HOST" => "Hostname to listen on (default: localhost)", - "Port=PORT" => "Port to listen on (default: 8080)", - "Processors=N" => "Number of concurrent processors to accept (default: 950)", - "Timeout=N" => "Time before a request is dropped for inactivity (default: 60)", - "Throttle=N" => "Throttle time between socket.accept calls in hundredths of a second (default: 0)", - } - end - - def initialize(app) - @app = app - end - - def process(request, response) - env = Hash[request.params] - env.delete "HTTP_CONTENT_TYPE" - env.delete "HTTP_CONTENT_LENGTH" - - env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" - - rack_input = request.body || StringIO.new('') - rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding) - - env.update({"rack.version" => Rack::VERSION, - "rack.input" => rack_input, - "rack.errors" => $stderr, - - "rack.multithread" => true, - "rack.multiprocess" => false, # ??? - "rack.run_once" => false, - - "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" - }) - env["QUERY_STRING"] ||= "" - - status, headers, body = @app.call(env) - - begin - response.status = status.to_i - response.send_status(nil) - - headers.each { |k, vs| - vs.split("\n").each { |v| - response.header[k] = v - } - } - response.send_header - - body.each { |part| - response.write part - response.socket.flush - } - ensure - body.close if body.respond_to? :close - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/scgi.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/scgi.rb deleted file mode 100644 index a4fe6ce..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/scgi.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'scgi' -require 'stringio' -require 'rack/content_length' -require 'rack/chunked' - -module Rack - module Handler - class SCGI < ::SCGI::Processor - attr_accessor :app - - def self.run(app, options=nil) - options[:Socket] = UNIXServer.new(options[:File]) if options[:File] - new(options.merge(:app=>app, - :host=>options[:Host], - :port=>options[:Port], - :socket=>options[:Socket])).listen - end - - def self.valid_options - { - "Host=HOST" => "Hostname to listen on (default: localhost)", - "Port=PORT" => "Port to listen on (default: 8080)", - } - end - - def initialize(settings = {}) - @app = settings[:app] - super(settings) - end - - def process_request(request, input_body, socket) - env = Hash[request] - env.delete "HTTP_CONTENT_TYPE" - env.delete "HTTP_CONTENT_LENGTH" - env["REQUEST_PATH"], env["QUERY_STRING"] = env["REQUEST_URI"].split('?', 2) - env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] - env["PATH_INFO"] = env["REQUEST_PATH"] - env["QUERY_STRING"] ||= "" - env["SCRIPT_NAME"] = "" - - rack_input = StringIO.new(input_body) - rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding) - - env.update({"rack.version" => Rack::VERSION, - "rack.input" => rack_input, - "rack.errors" => $stderr, - "rack.multithread" => true, - "rack.multiprocess" => true, - "rack.run_once" => false, - - "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" - }) - status, headers, body = app.call(env) - begin - socket.write("Status: #{status}\r\n") - headers.each do |k, vs| - vs.split("\n").each { |v| socket.write("#{k}: #{v}\r\n")} - end - socket.write("\r\n") - body.each {|s| socket.write(s)} - ensure - body.close if body.respond_to? :close - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/swiftiplied_mongrel.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/swiftiplied_mongrel.rb deleted file mode 100644 index 4bafd0b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/swiftiplied_mongrel.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'swiftcore/swiftiplied_mongrel' - -module Rack - module Handler - class SwiftipliedMongrel < Handler::Mongrel - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/thin.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/thin.rb deleted file mode 100644 index dc26972..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/thin.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "thin" -require "rack/content_length" -require "rack/chunked" - -module Rack - module Handler - class Thin - def self.run(app, options={}) - host = options.delete(:Host) || '0.0.0.0' - port = options.delete(:Port) || 8080 - args = [host, port, app, options] - # Thin versions below 0.8.0 do not support additional options - args.pop if ::Thin::VERSION::MAJOR < 1 && ::Thin::VERSION::MINOR < 8 - server = ::Thin::Server.new(*args) - yield server if block_given? - server.start - end - - def self.valid_options - { - "Host=HOST" => "Hostname to listen on (default: localhost)", - "Port=PORT" => "Port to listen on (default: 8080)", - } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb deleted file mode 100644 index 487a0ea..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb +++ /dev/null @@ -1,81 +0,0 @@ -require 'webrick' -require 'stringio' -require 'rack/content_length' - -module Rack - module Handler - class WEBrick < ::WEBrick::HTTPServlet::AbstractServlet - def self.run(app, options={}) - options[:BindAddress] = options.delete(:Host) if options[:Host] - options[:Port] ||= 8080 - @server = ::WEBrick::HTTPServer.new(options) - @server.mount "/", Rack::Handler::WEBrick, app - yield @server if block_given? - @server.start - end - - def self.valid_options - { - "Host=HOST" => "Hostname to listen on (default: localhost)", - "Port=PORT" => "Port to listen on (default: 8080)", - } - end - - def self.shutdown - @server.shutdown - @server = nil - end - - def initialize(server, app) - super server - @app = app - end - - def service(req, res) - env = req.meta_vars - env.delete_if { |k, v| v.nil? } - - rack_input = StringIO.new(req.body.to_s) - rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding) - - env.update({"rack.version" => Rack::VERSION, - "rack.input" => rack_input, - "rack.errors" => $stderr, - - "rack.multithread" => true, - "rack.multiprocess" => false, - "rack.run_once" => false, - - "rack.url_scheme" => ["yes", "on", "1"].include?(ENV["HTTPS"]) ? "https" : "http" - }) - - env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] - env["QUERY_STRING"] ||= "" - unless env["PATH_INFO"] == "" - path, n = req.request_uri.path, env["SCRIPT_NAME"].length - env["PATH_INFO"] = path[n, path.length-n] - end - env["REQUEST_PATH"] ||= [env["SCRIPT_NAME"], env["PATH_INFO"]].join - - status, headers, body = @app.call(env) - begin - res.status = status.to_i - headers.each { |k, vs| - if k.downcase == "set-cookie" - res.cookies.concat vs.split("\n") - else - # Since WEBrick won't accept repeated headers, - # merge the values per RFC 1945 section 4.2. - res[k] = vs.split("\n").join(", ") - end - } - body.each { |part| - res.body << part - } - ensure - body.close if body.respond_to? :close - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/head.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/head.rb deleted file mode 100644 index 7ffead6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/head.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Rack - -class Head - # Rack::Head returns an empty body for all HEAD requests. It leaves - # all other requests unchanged. - def initialize(app) - @app = app - end - - def call(env) - status, headers, body = @app.call(env) - - if env["REQUEST_METHOD"] == "HEAD" - body.close if body.respond_to? :close - [status, headers, []] - else - [status, headers, body] - end - end -end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lint.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lint.rb deleted file mode 100644 index fd21f77..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lint.rb +++ /dev/null @@ -1,699 +0,0 @@ -require 'rack/utils' -require 'forwardable' - -module Rack - # Rack::Lint validates your application and the requests and - # responses according to the Rack spec. - - class Lint - def initialize(app) - @app = app - @content_length = nil - end - - # :stopdoc: - - class LintError < RuntimeError; end - module Assertion - def assert(message, &block) - unless block.call - raise LintError, message - end - end - end - include Assertion - - ## This specification aims to formalize the Rack protocol. You - ## can (and should) use Rack::Lint to enforce it. - ## - ## When you develop middleware, be sure to add a Lint before and - ## after to catch all mistakes. - - ## = Rack applications - - ## A Rack application is a Ruby object (not a class) that - ## responds to +call+. - def call(env=nil) - dup._call(env) - end - - def _call(env) - ## It takes exactly one argument, the *environment* - assert("No env given") { env } - check_env env - - env['rack.input'] = InputWrapper.new(env['rack.input']) - env['rack.errors'] = ErrorWrapper.new(env['rack.errors']) - - ## and returns an Array of exactly three values: - status, headers, @body = @app.call(env) - ## The *status*, - check_status status - ## the *headers*, - check_headers headers - - check_hijack_response headers, env - - ## and the *body*. - check_content_type status, headers - check_content_length status, headers - @head_request = env["REQUEST_METHOD"] == "HEAD" - [status, headers, self] - end - - ## == The Environment - def check_env(env) - ## The environment must be an instance of Hash that includes - ## CGI-like headers. The application is free to modify the - ## environment. - assert("env #{env.inspect} is not a Hash, but #{env.class}") { - env.kind_of? Hash - } - - ## - ## The environment is required to include these variables - ## (adopted from PEP333), except when they'd be empty, but see - ## below. - - ## REQUEST_METHOD:: The HTTP request method, such as - ## "GET" or "POST". This cannot ever - ## be an empty string, and so is - ## always required. - - ## SCRIPT_NAME:: The initial portion of the request - ## URL's "path" that corresponds to the - ## application object, so that the - ## application knows its virtual - ## "location". This may be an empty - ## string, if the application corresponds - ## to the "root" of the server. - - ## PATH_INFO:: The remainder of the request URL's - ## "path", designating the virtual - ## "location" of the request's target - ## within the application. This may be an - ## empty string, if the request URL targets - ## the application root and does not have a - ## trailing slash. This value may be - ## percent-encoded when I originating from - ## a URL. - - ## QUERY_STRING:: The portion of the request URL that - ## follows the ?, if any. May be - ## empty, but is always required! - - ## SERVER_NAME, SERVER_PORT:: When combined with SCRIPT_NAME and PATH_INFO, these variables can be used to complete the URL. Note, however, that HTTP_HOST, if present, should be used in preference to SERVER_NAME for reconstructing the request URL. SERVER_NAME and SERVER_PORT can never be empty strings, and so are always required. - - ## HTTP_ Variables:: Variables corresponding to the - ## client-supplied HTTP request - ## headers (i.e., variables whose - ## names begin with HTTP_). The - ## presence or absence of these - ## variables should correspond with - ## the presence or absence of the - ## appropriate HTTP header in the - ## request. See - ## RFC3875 section 4.1.18 for specific behavior. - - ## In addition to this, the Rack environment must include these - ## Rack-specific variables: - - ## rack.version:: The Array representing this version of Rack. See Rack::VERSION, that corresponds to the version of this SPEC. - ## rack.url_scheme:: +http+ or +https+, depending on the request URL. - ## rack.input:: See below, the input stream. - ## rack.errors:: See below, the error stream. - ## rack.multithread:: true if the application object may be simultaneously invoked by another thread in the same process, false otherwise. - ## rack.multiprocess:: true if an equivalent application object may be simultaneously invoked by another process, false otherwise. - ## rack.run_once:: true if the server expects (but does not guarantee!) that the application will only be invoked this one time during the life of its containing process. Normally, this will only be true for a server based on CGI (or something similar). - ## rack.hijack?:: present and true if the server supports connection hijacking. See below, hijacking. - ## rack.hijack:: an object responding to #call that must be called at least once before using rack.hijack_io. It is recommended #call return rack.hijack_io as well as setting it in env if necessary. - ## rack.hijack_io:: if rack.hijack? is true, and rack.hijack has received #call, this will contain an object resembling an IO. See hijacking. - ## - - ## Additional environment specifications have approved to - ## standardized middleware APIs. None of these are required to - ## be implemented by the server. - - ## rack.session:: A hash like interface for storing request session data. - ## The store must implement: - if session = env['rack.session'] - ## store(key, value) (aliased as []=); - assert("session #{session.inspect} must respond to store and []=") { - session.respond_to?(:store) && session.respond_to?(:[]=) - } - - ## fetch(key, default = nil) (aliased as []); - assert("session #{session.inspect} must respond to fetch and []") { - session.respond_to?(:fetch) && session.respond_to?(:[]) - } - - ## delete(key); - assert("session #{session.inspect} must respond to delete") { - session.respond_to?(:delete) - } - - ## clear; - assert("session #{session.inspect} must respond to clear") { - session.respond_to?(:clear) - } - end - - ## rack.logger:: A common object interface for logging messages. - ## The object must implement: - if logger = env['rack.logger'] - ## info(message, &block) - assert("logger #{logger.inspect} must respond to info") { - logger.respond_to?(:info) - } - - ## debug(message, &block) - assert("logger #{logger.inspect} must respond to debug") { - logger.respond_to?(:debug) - } - - ## warn(message, &block) - assert("logger #{logger.inspect} must respond to warn") { - logger.respond_to?(:warn) - } - - ## error(message, &block) - assert("logger #{logger.inspect} must respond to error") { - logger.respond_to?(:error) - } - - ## fatal(message, &block) - assert("logger #{logger.inspect} must respond to fatal") { - logger.respond_to?(:fatal) - } - end - - ## The server or the application can store their own data in the - ## environment, too. The keys must contain at least one dot, - ## and should be prefixed uniquely. The prefix rack. - ## is reserved for use with the Rack core distribution and other - ## accepted specifications and must not be used otherwise. - ## - - %w[REQUEST_METHOD SERVER_NAME SERVER_PORT - QUERY_STRING - rack.version rack.input rack.errors - rack.multithread rack.multiprocess rack.run_once].each { |header| - assert("env missing required key #{header}") { env.include? header } - } - - ## The environment must not contain the keys - ## HTTP_CONTENT_TYPE or HTTP_CONTENT_LENGTH - ## (use the versions without HTTP_). - %w[HTTP_CONTENT_TYPE HTTP_CONTENT_LENGTH].each { |header| - assert("env contains #{header}, must use #{header[5,-1]}") { - not env.include? header - } - } - - ## The CGI keys (named without a period) must have String values. - env.each { |key, value| - next if key.include? "." # Skip extensions - assert("env variable #{key} has non-string value #{value.inspect}") { - value.kind_of? String - } - } - - ## - ## There are the following restrictions: - - ## * rack.version must be an array of Integers. - assert("rack.version must be an Array, was #{env["rack.version"].class}") { - env["rack.version"].kind_of? Array - } - ## * rack.url_scheme must either be +http+ or +https+. - assert("rack.url_scheme unknown: #{env["rack.url_scheme"].inspect}") { - %w[http https].include? env["rack.url_scheme"] - } - - ## * There must be a valid input stream in rack.input. - check_input env["rack.input"] - ## * There must be a valid error stream in rack.errors. - check_error env["rack.errors"] - ## * There may be a valid hijack stream in rack.hijack_io - check_hijack env - - ## * The REQUEST_METHOD must be a valid token. - assert("REQUEST_METHOD unknown: #{env["REQUEST_METHOD"]}") { - env["REQUEST_METHOD"] =~ /\A[0-9A-Za-z!\#$%&'*+.^_`|~-]+\z/ - } - - ## * The SCRIPT_NAME, if non-empty, must start with / - assert("SCRIPT_NAME must start with /") { - !env.include?("SCRIPT_NAME") || - env["SCRIPT_NAME"] == "" || - env["SCRIPT_NAME"] =~ /\A\// - } - ## * The PATH_INFO, if non-empty, must start with / - assert("PATH_INFO must start with /") { - !env.include?("PATH_INFO") || - env["PATH_INFO"] == "" || - env["PATH_INFO"] =~ /\A\// - } - ## * The CONTENT_LENGTH, if given, must consist of digits only. - assert("Invalid CONTENT_LENGTH: #{env["CONTENT_LENGTH"]}") { - !env.include?("CONTENT_LENGTH") || env["CONTENT_LENGTH"] =~ /\A\d+\z/ - } - - ## * One of SCRIPT_NAME or PATH_INFO must be - ## set. PATH_INFO should be / if - ## SCRIPT_NAME is empty. - assert("One of SCRIPT_NAME or PATH_INFO must be set (make PATH_INFO '/' if SCRIPT_NAME is empty)") { - env["SCRIPT_NAME"] || env["PATH_INFO"] - } - ## SCRIPT_NAME never should be /, but instead be empty. - assert("SCRIPT_NAME cannot be '/', make it '' and PATH_INFO '/'") { - env["SCRIPT_NAME"] != "/" - } - end - - ## === The Input Stream - ## - ## The input stream is an IO-like object which contains the raw HTTP - ## POST data. - def check_input(input) - ## When applicable, its external encoding must be "ASCII-8BIT" and it - ## must be opened in binary mode, for Ruby 1.9 compatibility. - assert("rack.input #{input} does not have ASCII-8BIT as its external encoding") { - input.external_encoding.name == "ASCII-8BIT" - } if input.respond_to?(:external_encoding) - assert("rack.input #{input} is not opened in binary mode") { - input.binmode? - } if input.respond_to?(:binmode?) - - ## The input stream must respond to +gets+, +each+, +read+ and +rewind+. - [:gets, :each, :read, :rewind].each { |method| - assert("rack.input #{input} does not respond to ##{method}") { - input.respond_to? method - } - } - end - - class InputWrapper - include Assertion - - def initialize(input) - @input = input - end - - ## * +gets+ must be called without arguments and return a string, - ## or +nil+ on EOF. - def gets(*args) - assert("rack.input#gets called with arguments") { args.size == 0 } - v = @input.gets - assert("rack.input#gets didn't return a String") { - v.nil? or v.kind_of? String - } - v - end - - ## * +read+ behaves like IO#read. Its signature is read([length, [buffer]]). - ## If given, +length+ must be a non-negative Integer (>= 0) or +nil+, and +buffer+ must - ## be a String and may not be nil. If +length+ is given and not nil, then this method - ## reads at most +length+ bytes from the input stream. If +length+ is not given or nil, - ## then this method reads all data until EOF. - ## When EOF is reached, this method returns nil if +length+ is given and not nil, or "" - ## if +length+ is not given or is nil. - ## If +buffer+ is given, then the read data will be placed into +buffer+ instead of a - ## newly created String object. - def read(*args) - assert("rack.input#read called with too many arguments") { - args.size <= 2 - } - if args.size >= 1 - assert("rack.input#read called with non-integer and non-nil length") { - args.first.kind_of?(Integer) || args.first.nil? - } - assert("rack.input#read called with a negative length") { - args.first.nil? || args.first >= 0 - } - end - if args.size >= 2 - assert("rack.input#read called with non-String buffer") { - args[1].kind_of?(String) - } - end - - v = @input.read(*args) - - assert("rack.input#read didn't return nil or a String") { - v.nil? or v.kind_of? String - } - if args[0].nil? - assert("rack.input#read(nil) returned nil on EOF") { - !v.nil? - } - end - - v - end - - ## * +each+ must be called without arguments and only yield Strings. - def each(*args) - assert("rack.input#each called with arguments") { args.size == 0 } - @input.each { |line| - assert("rack.input#each didn't yield a String") { - line.kind_of? String - } - yield line - } - end - - ## * +rewind+ must be called without arguments. It rewinds the input - ## stream back to the beginning. It must not raise Errno::ESPIPE: - ## that is, it may not be a pipe or a socket. Therefore, handler - ## developers must buffer the input data into some rewindable object - ## if the underlying input stream is not rewindable. - def rewind(*args) - assert("rack.input#rewind called with arguments") { args.size == 0 } - assert("rack.input#rewind raised Errno::ESPIPE") { - begin - @input.rewind - true - rescue Errno::ESPIPE - false - end - } - end - - ## * +close+ must never be called on the input stream. - def close(*args) - assert("rack.input#close must not be called") { false } - end - end - - ## === The Error Stream - def check_error(error) - ## The error stream must respond to +puts+, +write+ and +flush+. - [:puts, :write, :flush].each { |method| - assert("rack.error #{error} does not respond to ##{method}") { - error.respond_to? method - } - } - end - - class ErrorWrapper - include Assertion - - def initialize(error) - @error = error - end - - ## * +puts+ must be called with a single argument that responds to +to_s+. - def puts(str) - @error.puts str - end - - ## * +write+ must be called with a single argument that is a String. - def write(str) - assert("rack.errors#write not called with a String") { str.kind_of? String } - @error.write str - end - - ## * +flush+ must be called without arguments and must be called - ## in order to make the error appear for sure. - def flush - @error.flush - end - - ## * +close+ must never be called on the error stream. - def close(*args) - assert("rack.errors#close must not be called") { false } - end - end - - class HijackWrapper - include Assertion - extend Forwardable - - REQUIRED_METHODS = [ - :read, :write, :read_nonblock, :write_nonblock, :flush, :close, - :close_read, :close_write, :closed? - ] - - def_delegators :@io, *REQUIRED_METHODS - - def initialize(io) - @io = io - REQUIRED_METHODS.each do |meth| - assert("rack.hijack_io must respond to #{meth}") { io.respond_to? meth } - end - end - end - - ## === Hijacking - # - # AUTHORS: n.b. The trailing whitespace between paragraphs is important and - # should not be removed. The whitespace creates paragraphs in the RDoc - # output. - # - ## ==== Request (before status) - def check_hijack(env) - if env['rack.hijack?'] - ## If rack.hijack? is true then rack.hijack must respond to #call. - original_hijack = env['rack.hijack'] - assert("rack.hijack must respond to call") { original_hijack.respond_to?(:call) } - env['rack.hijack'] = proc do - ## rack.hijack must return the io that will also be assigned (or is - ## already present, in rack.hijack_io. - io = original_hijack.call - HijackWrapper.new(io) - ## - ## rack.hijack_io must respond to: - ## read, write, read_nonblock, write_nonblock, flush, close, - ## close_read, close_write, closed? - ## - ## The semantics of these IO methods must be a best effort match to - ## those of a normal ruby IO or Socket object, using standard - ## arguments and raising standard exceptions. Servers are encouraged - ## to simply pass on real IO objects, although it is recognized that - ## this approach is not directly compatible with SPDY and HTTP 2.0. - ## - ## IO provided in rack.hijack_io should preference the - ## IO::WaitReadable and IO::WaitWritable APIs wherever supported. - ## - ## There is a deliberate lack of full specification around - ## rack.hijack_io, as semantics will change from server to server. - ## Users are encouraged to utilize this API with a knowledge of their - ## server choice, and servers may extend the functionality of - ## hijack_io to provide additional features to users. The purpose of - ## rack.hijack is for Rack to "get out of the way", as such, Rack only - ## provides the minimum of specification and support. - env['rack.hijack_io'] = HijackWrapper.new(env['rack.hijack_io']) - io - end - else - ## - ## If rack.hijack? is false, then rack.hijack should not be set. - assert("rack.hijack? is false, but rack.hijack is present") { env['rack.hijack'].nil? } - ## - ## If rack.hijack? is false, then rack.hijack_io should not be set. - assert("rack.hijack? is false, but rack.hijack_io is present") { env['rack.hijack_io'].nil? } - end - end - - ## ==== Response (after headers) - ## It is also possible to hijack a response after the status and headers - ## have been sent. - def check_hijack_response(headers, env) - - # this check uses headers like a hash, but the spec only requires - # headers respond to #each - headers = Rack::Utils::HeaderHash.new(headers) - - ## In order to do this, an application may set the special header - ## rack.hijack to an object that responds to call - ## accepting an argument that conforms to the rack.hijack_io - ## protocol. - ## - ## After the headers have been sent, and this hijack callback has been - ## called, the application is now responsible for the remaining lifecycle - ## of the IO. The application is also responsible for maintaining HTTP - ## semantics. Of specific note, in almost all cases in the current SPEC, - ## applications will have wanted to specify the header Connection:close in - ## HTTP/1.1, and not Connection:keep-alive, as there is no protocol for - ## returning hijacked sockets to the web server. For that purpose, use the - ## body streaming API instead (progressively yielding strings via each). - ## - ## Servers must ignore the body part of the response tuple when - ## the rack.hijack response API is in use. - - if env['rack.hijack?'] && headers['rack.hijack'] - assert('rack.hijack header must respond to #call') { - headers['rack.hijack'].respond_to? :call - } - original_hijack = headers['rack.hijack'] - headers['rack.hijack'] = proc do |io| - original_hijack.call HijackWrapper.new(io) - end - else - ## - ## The special response header rack.hijack must only be set - ## if the request env has rack.hijack? true. - assert('rack.hijack header must not be present if server does not support hijacking') { - headers['rack.hijack'].nil? - } - end - end - ## ==== Conventions - ## * Middleware should not use hijack unless it is handling the whole - ## response. - ## * Middleware may wrap the IO object for the response pattern. - ## * Middleware should not wrap the IO object for the request pattern. The - ## request pattern is intended to provide the hijacker with "raw tcp". - - ## == The Response - - ## === The Status - def check_status(status) - ## This is an HTTP status. When parsed as integer (+to_i+), it must be - ## greater than or equal to 100. - assert("Status must be >=100 seen as integer") { status.to_i >= 100 } - end - - ## === The Headers - def check_headers(header) - ## The header must respond to +each+, and yield values of key and value. - assert("headers object should respond to #each, but doesn't (got #{header.class} as headers)") { - header.respond_to? :each - } - header.each { |key, value| - ## Special headers starting "rack." are for communicating with the - ## server, and must not be sent back to the client. - next if key =~ /^rack\..+$/ - - ## The header keys must be Strings. - assert("header key must be a string, was #{key.class}") { - key.kind_of? String - } - ## The header must not contain a +Status+ key, - assert("header must not contain Status") { key.downcase != "status" } - ## contain keys with : or newlines in their name, - assert("header names must not contain : or \\n") { key !~ /[:\n]/ } - ## contain keys names that end in - or _, - assert("header names must not end in - or _") { key !~ /[-_]\z/ } - ## but only contain keys that consist of - ## letters, digits, _ or - and start with a letter. - assert("invalid header name: #{key}") { key =~ /\A[a-zA-Z][a-zA-Z0-9_-]*\z/ } - - ## The values of the header must be Strings, - assert("a header value must be a String, but the value of " + - "'#{key}' is a #{value.class}") { value.kind_of? String } - ## consisting of lines (for multiple header values, e.g. multiple - ## Set-Cookie values) seperated by "\n". - value.split("\n").each { |item| - ## The lines must not contain characters below 037. - assert("invalid header value #{key}: #{item.inspect}") { - item !~ /[\000-\037]/ - } - } - } - end - - ## === The Content-Type - def check_content_type(status, headers) - headers.each { |key, value| - ## There must not be a Content-Type, when the +Status+ is 1xx, - ## 204, 205 or 304. - if key.downcase == "content-type" - assert("Content-Type header found in #{status} response, not allowed") { - not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i - } - return - end - } - end - - ## === The Content-Length - def check_content_length(status, headers) - headers.each { |key, value| - if key.downcase == 'content-length' - ## There must not be a Content-Length header when the - ## +Status+ is 1xx, 204, 205 or 304. - assert("Content-Length header found in #{status} response, not allowed") { - not Rack::Utils::STATUS_WITH_NO_ENTITY_BODY.include? status.to_i - } - @content_length = value - end - } - end - - def verify_content_length(bytes) - if @head_request - assert("Response body was given for HEAD request, but should be empty") { - bytes == 0 - } - elsif @content_length - assert("Content-Length header was #{@content_length}, but should be #{bytes}") { - @content_length == bytes.to_s - } - end - end - - ## === The Body - def each - @closed = false - bytes = 0 - - ## The Body must respond to +each+ - assert("Response body must respond to each") do - @body.respond_to?(:each) - end - - @body.each { |part| - ## and must only yield String values. - assert("Body yielded non-string value #{part.inspect}") { - part.kind_of? String - } - bytes += Rack::Utils.bytesize(part) - yield part - } - verify_content_length(bytes) - - ## - ## The Body itself should not be an instance of String, as this will - ## break in Ruby 1.9. - ## - ## If the Body responds to +close+, it will be called after iteration. If - ## the body is replaced by a middleware after action, the original body - ## must be closed first, if it repsonds to close. - # XXX howto: assert("Body has not been closed") { @closed } - - - ## - ## If the Body responds to +to_path+, it must return a String - ## identifying the location of a file whose contents are identical - ## to that produced by calling +each+; this may be used by the - ## server as an alternative, possibly more efficient way to - ## transport the response. - - if @body.respond_to?(:to_path) - assert("The file identified by body.to_path does not exist") { - ::File.exist? @body.to_path - } - end - - ## - ## The Body commonly is an Array of Strings, the application - ## instance itself, or a File-like object. - end - - def close - @closed = true - @body.close if @body.respond_to?(:close) - end - - # :startdoc: - - end -end - -## == Thanks -## Some parts of this specification are adopted from PEP333: Python -## Web Server Gateway Interface -## v1.0 (http://www.python.org/dev/peps/pep-0333/). I'd like to thank -## everyone involved in that effort. diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lobster.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lobster.rb deleted file mode 100644 index d1a7f7b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lobster.rb +++ /dev/null @@ -1,65 +0,0 @@ -require 'zlib' - -require 'rack/request' -require 'rack/response' - -module Rack - # Paste has a Pony, Rack has a Lobster! - class Lobster - LobsterString = Zlib::Inflate.inflate("eJx9kEEOwyAMBO99xd7MAcytUhPlJyj2 - P6jy9i4k9EQyGAnBarEXeCBqSkntNXsi/ZCvC48zGQoZKikGrFMZvgS5ZHd+aGWVuWwhVF0 - t1drVmiR42HcWNz5w3QanT+2gIvTVCiE1lm1Y0eU4JGmIIbaKwextKn8rvW+p5PIwFl8ZWJ - I8jyiTlhTcYXkekJAzTyYN6E08A+dk8voBkAVTJQ==".delete("\n ").unpack("m*")[0]) - - LambdaLobster = lambda { |env| - if env["QUERY_STRING"].include?("flip") - lobster = LobsterString.split("\n"). - map { |line| line.ljust(42).reverse }. - join("\n") - href = "?" - else - lobster = LobsterString - href = "?flip" - end - - content = ["Lobstericious!", - "
", lobster, "
", - "flip!"] - length = content.inject(0) { |a,e| a+e.size }.to_s - [200, {"Content-Type" => "text/html", "Content-Length" => length}, content] - } - - def call(env) - req = Request.new(env) - if req.GET["flip"] == "left" - lobster = LobsterString.split("\n"). - map { |line| line.ljust(42).reverse }. - join("\n") - href = "?flip=right" - elsif req.GET["flip"] == "crash" - raise "Lobster crashed" - else - lobster = LobsterString - href = "?flip=left" - end - - res = Response.new - res.write "Lobstericious!" - res.write "
"
-      res.write lobster
-      res.write "
" - res.write "

flip!

" - res.write "

crash!

" - res.finish - end - - end -end - -if $0 == __FILE__ - require 'rack' - require 'rack/showexceptions' - Rack::Server.start( - :app => Rack::ShowExceptions.new(Rack::Lint.new(Rack::Lobster.new)), :Port => 9292 - ) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lock.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lock.rb deleted file mode 100644 index b3139c0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/lock.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'thread' -require 'rack/body_proxy' - -module Rack - # Rack::Lock locks every request inside a mutex, so that every request - # will effectively be executed synchronously. - class Lock - FLAG = 'rack.multithread'.freeze - - def initialize(app, mutex = Mutex.new) - @app, @mutex = app, mutex - end - - def call(env) - old, env[FLAG] = env[FLAG], false - @mutex.lock - response = @app.call(env) - body = BodyProxy.new(response[2]) { @mutex.unlock } - response[2] = body - response - ensure - @mutex.unlock unless body - env[FLAG] = old - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/logger.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/logger.rb deleted file mode 100644 index 88f9837..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/logger.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'logger' - -module Rack - # Sets up rack.logger to write to rack.errors stream - class Logger - def initialize(app, level = ::Logger::INFO) - @app, @level = app, level - end - - def call(env) - logger = ::Logger.new(env['rack.errors']) - logger.level = @level - - env['rack.logger'] = logger - @app.call(env) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb deleted file mode 100644 index 1bdaca8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/methodoverride.rb +++ /dev/null @@ -1,31 +0,0 @@ -module Rack - class MethodOverride - HTTP_METHODS = %w(GET HEAD PUT POST DELETE OPTIONS PATCH) - - METHOD_OVERRIDE_PARAM_KEY = "_method".freeze - HTTP_METHOD_OVERRIDE_HEADER = "HTTP_X_HTTP_METHOD_OVERRIDE".freeze - - def initialize(app) - @app = app - end - - def call(env) - if env["REQUEST_METHOD"] == "POST" - method = method_override(env) - if HTTP_METHODS.include?(method) - env["rack.methodoverride.original_method"] = env["REQUEST_METHOD"] - env["REQUEST_METHOD"] = method - end - end - - @app.call(env) - end - - def method_override(env) - req = Request.new(env) - method = req.POST[METHOD_OVERRIDE_PARAM_KEY] || - env[HTTP_METHOD_OVERRIDE_HEADER] - method.to_s.upcase - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/mime.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/mime.rb deleted file mode 100644 index 5d05022..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/mime.rb +++ /dev/null @@ -1,677 +0,0 @@ -module Rack - module Mime - # Returns String with mime type if found, otherwise use +fallback+. - # +ext+ should be filename extension in the '.ext' format that - # File.extname(file) returns. - # +fallback+ may be any object - # - # Also see the documentation for MIME_TYPES - # - # Usage: - # Rack::Mime.mime_type('.foo') - # - # This is a shortcut for: - # Rack::Mime::MIME_TYPES.fetch('.foo', 'application/octet-stream') - - def mime_type(ext, fallback='application/octet-stream') - MIME_TYPES.fetch(ext.to_s.downcase, fallback) - end - module_function :mime_type - - # Returns true if the given value is a mime match for the given mime match - # specification, false otherwise. - # - # Rack::Mime.match?('text/html', 'text/*') => true - # Rack::Mime.match?('text/plain', '*') => true - # Rack::Mime.match?('text/html', 'application/json') => false - - def match?(value, matcher) - v1, v2 = value.split('/', 2) - m1, m2 = matcher.split('/', 2) - - if m1 == '*' - if m2.nil? || m2 == '*' - return true - elsif m2 == v2 - return true - else - return false - end - end - - return false if v1 != m1 - - return true if m2.nil? || m2 == '*' - - m2 == v2 - end - module_function :match? - - # List of most common mime-types, selected various sources - # according to their usefulness in a webserving scope for Ruby - # users. - # - # To amend this list with your local mime.types list you can use: - # - # require 'webrick/httputils' - # list = WEBrick::HTTPUtils.load_mime_types('/etc/mime.types') - # Rack::Mime::MIME_TYPES.merge!(list) - # - # N.B. On Ubuntu the mime.types file does not include the leading period, so - # users may need to modify the data before merging into the hash. - # - # To add the list mongrel provides, use: - # - # require 'mongrel/handlers' - # Rack::Mime::MIME_TYPES.merge!(Mongrel::DirHandler::MIME_TYPES) - - MIME_TYPES = { - ".123" => "application/vnd.lotus-1-2-3", - ".3dml" => "text/vnd.in3d.3dml", - ".3g2" => "video/3gpp2", - ".3gp" => "video/3gpp", - ".a" => "application/octet-stream", - ".acc" => "application/vnd.americandynamics.acc", - ".ace" => "application/x-ace-compressed", - ".acu" => "application/vnd.acucobol", - ".aep" => "application/vnd.audiograph", - ".afp" => "application/vnd.ibm.modcap", - ".ai" => "application/postscript", - ".aif" => "audio/x-aiff", - ".aiff" => "audio/x-aiff", - ".ami" => "application/vnd.amiga.ami", - ".appcache" => "text/cache-manifest", - ".apr" => "application/vnd.lotus-approach", - ".asc" => "application/pgp-signature", - ".asf" => "video/x-ms-asf", - ".asm" => "text/x-asm", - ".aso" => "application/vnd.accpac.simply.aso", - ".asx" => "video/x-ms-asf", - ".atc" => "application/vnd.acucorp", - ".atom" => "application/atom+xml", - ".atomcat" => "application/atomcat+xml", - ".atomsvc" => "application/atomsvc+xml", - ".atx" => "application/vnd.antix.game-component", - ".au" => "audio/basic", - ".avi" => "video/x-msvideo", - ".bat" => "application/x-msdownload", - ".bcpio" => "application/x-bcpio", - ".bdm" => "application/vnd.syncml.dm+wbxml", - ".bh2" => "application/vnd.fujitsu.oasysprs", - ".bin" => "application/octet-stream", - ".bmi" => "application/vnd.bmi", - ".bmp" => "image/bmp", - ".box" => "application/vnd.previewsystems.box", - ".btif" => "image/prs.btif", - ".bz" => "application/x-bzip", - ".bz2" => "application/x-bzip2", - ".c" => "text/x-c", - ".c4g" => "application/vnd.clonk.c4group", - ".cab" => "application/vnd.ms-cab-compressed", - ".cc" => "text/x-c", - ".ccxml" => "application/ccxml+xml", - ".cdbcmsg" => "application/vnd.contact.cmsg", - ".cdkey" => "application/vnd.mediastation.cdkey", - ".cdx" => "chemical/x-cdx", - ".cdxml" => "application/vnd.chemdraw+xml", - ".cdy" => "application/vnd.cinderella", - ".cer" => "application/pkix-cert", - ".cgm" => "image/cgm", - ".chat" => "application/x-chat", - ".chm" => "application/vnd.ms-htmlhelp", - ".chrt" => "application/vnd.kde.kchart", - ".cif" => "chemical/x-cif", - ".cii" => "application/vnd.anser-web-certificate-issue-initiation", - ".cil" => "application/vnd.ms-artgalry", - ".cla" => "application/vnd.claymore", - ".class" => "application/octet-stream", - ".clkk" => "application/vnd.crick.clicker.keyboard", - ".clkp" => "application/vnd.crick.clicker.palette", - ".clkt" => "application/vnd.crick.clicker.template", - ".clkw" => "application/vnd.crick.clicker.wordbank", - ".clkx" => "application/vnd.crick.clicker", - ".clp" => "application/x-msclip", - ".cmc" => "application/vnd.cosmocaller", - ".cmdf" => "chemical/x-cmdf", - ".cml" => "chemical/x-cml", - ".cmp" => "application/vnd.yellowriver-custom-menu", - ".cmx" => "image/x-cmx", - ".com" => "application/x-msdownload", - ".conf" => "text/plain", - ".cpio" => "application/x-cpio", - ".cpp" => "text/x-c", - ".cpt" => "application/mac-compactpro", - ".crd" => "application/x-mscardfile", - ".crl" => "application/pkix-crl", - ".crt" => "application/x-x509-ca-cert", - ".csh" => "application/x-csh", - ".csml" => "chemical/x-csml", - ".csp" => "application/vnd.commonspace", - ".css" => "text/css", - ".csv" => "text/csv", - ".curl" => "application/vnd.curl", - ".cww" => "application/prs.cww", - ".cxx" => "text/x-c", - ".daf" => "application/vnd.mobius.daf", - ".davmount" => "application/davmount+xml", - ".dcr" => "application/x-director", - ".dd2" => "application/vnd.oma.dd2+xml", - ".ddd" => "application/vnd.fujixerox.ddd", - ".deb" => "application/x-debian-package", - ".der" => "application/x-x509-ca-cert", - ".dfac" => "application/vnd.dreamfactory", - ".diff" => "text/x-diff", - ".dis" => "application/vnd.mobius.dis", - ".djv" => "image/vnd.djvu", - ".djvu" => "image/vnd.djvu", - ".dll" => "application/x-msdownload", - ".dmg" => "application/octet-stream", - ".dna" => "application/vnd.dna", - ".doc" => "application/msword", - ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - ".dot" => "application/msword", - ".dp" => "application/vnd.osgi.dp", - ".dpg" => "application/vnd.dpgraph", - ".dsc" => "text/prs.lines.tag", - ".dtd" => "application/xml-dtd", - ".dts" => "audio/vnd.dts", - ".dtshd" => "audio/vnd.dts.hd", - ".dv" => "video/x-dv", - ".dvi" => "application/x-dvi", - ".dwf" => "model/vnd.dwf", - ".dwg" => "image/vnd.dwg", - ".dxf" => "image/vnd.dxf", - ".dxp" => "application/vnd.spotfire.dxp", - ".ear" => "application/java-archive", - ".ecelp4800" => "audio/vnd.nuera.ecelp4800", - ".ecelp7470" => "audio/vnd.nuera.ecelp7470", - ".ecelp9600" => "audio/vnd.nuera.ecelp9600", - ".ecma" => "application/ecmascript", - ".edm" => "application/vnd.novadigm.edm", - ".edx" => "application/vnd.novadigm.edx", - ".efif" => "application/vnd.picsel", - ".ei6" => "application/vnd.pg.osasli", - ".eml" => "message/rfc822", - ".eol" => "audio/vnd.digital-winds", - ".eot" => "application/vnd.ms-fontobject", - ".eps" => "application/postscript", - ".es3" => "application/vnd.eszigno3+xml", - ".esf" => "application/vnd.epson.esf", - ".etx" => "text/x-setext", - ".exe" => "application/x-msdownload", - ".ext" => "application/vnd.novadigm.ext", - ".ez" => "application/andrew-inset", - ".ez2" => "application/vnd.ezpix-album", - ".ez3" => "application/vnd.ezpix-package", - ".f" => "text/x-fortran", - ".f77" => "text/x-fortran", - ".f90" => "text/x-fortran", - ".fbs" => "image/vnd.fastbidsheet", - ".fdf" => "application/vnd.fdf", - ".fe_launch" => "application/vnd.denovo.fcselayout-link", - ".fg5" => "application/vnd.fujitsu.oasysgp", - ".fli" => "video/x-fli", - ".flo" => "application/vnd.micrografx.flo", - ".flv" => "video/x-flv", - ".flw" => "application/vnd.kde.kivio", - ".flx" => "text/vnd.fmi.flexstor", - ".fly" => "text/vnd.fly", - ".fm" => "application/vnd.framemaker", - ".fnc" => "application/vnd.frogans.fnc", - ".for" => "text/x-fortran", - ".fpx" => "image/vnd.fpx", - ".fsc" => "application/vnd.fsc.weblaunch", - ".fst" => "image/vnd.fst", - ".ftc" => "application/vnd.fluxtime.clip", - ".fti" => "application/vnd.anser-web-funds-transfer-initiation", - ".fvt" => "video/vnd.fvt", - ".fzs" => "application/vnd.fuzzysheet", - ".g3" => "image/g3fax", - ".gac" => "application/vnd.groove-account", - ".gdl" => "model/vnd.gdl", - ".gem" => "application/octet-stream", - ".gemspec" => "text/x-script.ruby", - ".ghf" => "application/vnd.groove-help", - ".gif" => "image/gif", - ".gim" => "application/vnd.groove-identity-message", - ".gmx" => "application/vnd.gmx", - ".gph" => "application/vnd.flographit", - ".gqf" => "application/vnd.grafeq", - ".gram" => "application/srgs", - ".grv" => "application/vnd.groove-injector", - ".grxml" => "application/srgs+xml", - ".gtar" => "application/x-gtar", - ".gtm" => "application/vnd.groove-tool-message", - ".gtw" => "model/vnd.gtw", - ".gv" => "text/vnd.graphviz", - ".gz" => "application/x-gzip", - ".h" => "text/x-c", - ".h261" => "video/h261", - ".h263" => "video/h263", - ".h264" => "video/h264", - ".hbci" => "application/vnd.hbci", - ".hdf" => "application/x-hdf", - ".hh" => "text/x-c", - ".hlp" => "application/winhlp", - ".hpgl" => "application/vnd.hp-hpgl", - ".hpid" => "application/vnd.hp-hpid", - ".hps" => "application/vnd.hp-hps", - ".hqx" => "application/mac-binhex40", - ".htc" => "text/x-component", - ".htke" => "application/vnd.kenameaapp", - ".htm" => "text/html", - ".html" => "text/html", - ".hvd" => "application/vnd.yamaha.hv-dic", - ".hvp" => "application/vnd.yamaha.hv-voice", - ".hvs" => "application/vnd.yamaha.hv-script", - ".icc" => "application/vnd.iccprofile", - ".ice" => "x-conference/x-cooltalk", - ".ico" => "image/vnd.microsoft.icon", - ".ics" => "text/calendar", - ".ief" => "image/ief", - ".ifb" => "text/calendar", - ".ifm" => "application/vnd.shana.informed.formdata", - ".igl" => "application/vnd.igloader", - ".igs" => "model/iges", - ".igx" => "application/vnd.micrografx.igx", - ".iif" => "application/vnd.shana.informed.interchange", - ".imp" => "application/vnd.accpac.simply.imp", - ".ims" => "application/vnd.ms-ims", - ".ipk" => "application/vnd.shana.informed.package", - ".irm" => "application/vnd.ibm.rights-management", - ".irp" => "application/vnd.irepository.package+xml", - ".iso" => "application/octet-stream", - ".itp" => "application/vnd.shana.informed.formtemplate", - ".ivp" => "application/vnd.immervision-ivp", - ".ivu" => "application/vnd.immervision-ivu", - ".jad" => "text/vnd.sun.j2me.app-descriptor", - ".jam" => "application/vnd.jam", - ".jar" => "application/java-archive", - ".java" => "text/x-java-source", - ".jisp" => "application/vnd.jisp", - ".jlt" => "application/vnd.hp-jlyt", - ".jnlp" => "application/x-java-jnlp-file", - ".joda" => "application/vnd.joost.joda-archive", - ".jp2" => "image/jp2", - ".jpeg" => "image/jpeg", - ".jpg" => "image/jpeg", - ".jpgv" => "video/jpeg", - ".jpm" => "video/jpm", - ".js" => "application/javascript", - ".json" => "application/json", - ".karbon" => "application/vnd.kde.karbon", - ".kfo" => "application/vnd.kde.kformula", - ".kia" => "application/vnd.kidspiration", - ".kml" => "application/vnd.google-earth.kml+xml", - ".kmz" => "application/vnd.google-earth.kmz", - ".kne" => "application/vnd.kinar", - ".kon" => "application/vnd.kde.kontour", - ".kpr" => "application/vnd.kde.kpresenter", - ".ksp" => "application/vnd.kde.kspread", - ".ktz" => "application/vnd.kahootz", - ".kwd" => "application/vnd.kde.kword", - ".latex" => "application/x-latex", - ".lbd" => "application/vnd.llamagraphics.life-balance.desktop", - ".lbe" => "application/vnd.llamagraphics.life-balance.exchange+xml", - ".les" => "application/vnd.hhe.lesson-player", - ".link66" => "application/vnd.route66.link66+xml", - ".log" => "text/plain", - ".lostxml" => "application/lost+xml", - ".lrm" => "application/vnd.ms-lrm", - ".ltf" => "application/vnd.frogans.ltf", - ".lvp" => "audio/vnd.lucent.voice", - ".lwp" => "application/vnd.lotus-wordpro", - ".m3u" => "audio/x-mpegurl", - ".m4a" => "audio/mp4a-latm", - ".m4v" => "video/mp4", - ".ma" => "application/mathematica", - ".mag" => "application/vnd.ecowin.chart", - ".man" => "text/troff", - ".manifest" => "text/cache-manifest", - ".mathml" => "application/mathml+xml", - ".mbk" => "application/vnd.mobius.mbk", - ".mbox" => "application/mbox", - ".mc1" => "application/vnd.medcalcdata", - ".mcd" => "application/vnd.mcd", - ".mdb" => "application/x-msaccess", - ".mdi" => "image/vnd.ms-modi", - ".mdoc" => "text/troff", - ".me" => "text/troff", - ".mfm" => "application/vnd.mfmp", - ".mgz" => "application/vnd.proteus.magazine", - ".mid" => "audio/midi", - ".midi" => "audio/midi", - ".mif" => "application/vnd.mif", - ".mime" => "message/rfc822", - ".mj2" => "video/mj2", - ".mlp" => "application/vnd.dolby.mlp", - ".mmd" => "application/vnd.chipnuts.karaoke-mmd", - ".mmf" => "application/vnd.smaf", - ".mml" => "application/mathml+xml", - ".mmr" => "image/vnd.fujixerox.edmics-mmr", - ".mng" => "video/x-mng", - ".mny" => "application/x-msmoney", - ".mov" => "video/quicktime", - ".movie" => "video/x-sgi-movie", - ".mp3" => "audio/mpeg", - ".mp4" => "video/mp4", - ".mp4a" => "audio/mp4", - ".mp4s" => "application/mp4", - ".mp4v" => "video/mp4", - ".mpc" => "application/vnd.mophun.certificate", - ".mpeg" => "video/mpeg", - ".mpg" => "video/mpeg", - ".mpga" => "audio/mpeg", - ".mpkg" => "application/vnd.apple.installer+xml", - ".mpm" => "application/vnd.blueice.multipass", - ".mpn" => "application/vnd.mophun.application", - ".mpp" => "application/vnd.ms-project", - ".mpy" => "application/vnd.ibm.minipay", - ".mqy" => "application/vnd.mobius.mqy", - ".mrc" => "application/marc", - ".ms" => "text/troff", - ".mscml" => "application/mediaservercontrol+xml", - ".mseq" => "application/vnd.mseq", - ".msf" => "application/vnd.epson.msf", - ".msh" => "model/mesh", - ".msi" => "application/x-msdownload", - ".msl" => "application/vnd.mobius.msl", - ".msty" => "application/vnd.muvee.style", - ".mts" => "model/vnd.mts", - ".mus" => "application/vnd.musician", - ".mvb" => "application/x-msmediaview", - ".mwf" => "application/vnd.mfer", - ".mxf" => "application/mxf", - ".mxl" => "application/vnd.recordare.musicxml", - ".mxml" => "application/xv+xml", - ".mxs" => "application/vnd.triscape.mxs", - ".mxu" => "video/vnd.mpegurl", - ".n" => "application/vnd.nokia.n-gage.symbian.install", - ".nc" => "application/x-netcdf", - ".ngdat" => "application/vnd.nokia.n-gage.data", - ".nlu" => "application/vnd.neurolanguage.nlu", - ".nml" => "application/vnd.enliven", - ".nnd" => "application/vnd.noblenet-directory", - ".nns" => "application/vnd.noblenet-sealer", - ".nnw" => "application/vnd.noblenet-web", - ".npx" => "image/vnd.net-fpx", - ".nsf" => "application/vnd.lotus-notes", - ".oa2" => "application/vnd.fujitsu.oasys2", - ".oa3" => "application/vnd.fujitsu.oasys3", - ".oas" => "application/vnd.fujitsu.oasys", - ".obd" => "application/x-msbinder", - ".oda" => "application/oda", - ".odc" => "application/vnd.oasis.opendocument.chart", - ".odf" => "application/vnd.oasis.opendocument.formula", - ".odg" => "application/vnd.oasis.opendocument.graphics", - ".odi" => "application/vnd.oasis.opendocument.image", - ".odp" => "application/vnd.oasis.opendocument.presentation", - ".ods" => "application/vnd.oasis.opendocument.spreadsheet", - ".odt" => "application/vnd.oasis.opendocument.text", - ".oga" => "audio/ogg", - ".ogg" => "application/ogg", - ".ogv" => "video/ogg", - ".ogx" => "application/ogg", - ".org" => "application/vnd.lotus-organizer", - ".otc" => "application/vnd.oasis.opendocument.chart-template", - ".otf" => "application/vnd.oasis.opendocument.formula-template", - ".otg" => "application/vnd.oasis.opendocument.graphics-template", - ".oth" => "application/vnd.oasis.opendocument.text-web", - ".oti" => "application/vnd.oasis.opendocument.image-template", - ".otm" => "application/vnd.oasis.opendocument.text-master", - ".ots" => "application/vnd.oasis.opendocument.spreadsheet-template", - ".ott" => "application/vnd.oasis.opendocument.text-template", - ".oxt" => "application/vnd.openofficeorg.extension", - ".p" => "text/x-pascal", - ".p10" => "application/pkcs10", - ".p12" => "application/x-pkcs12", - ".p7b" => "application/x-pkcs7-certificates", - ".p7m" => "application/pkcs7-mime", - ".p7r" => "application/x-pkcs7-certreqresp", - ".p7s" => "application/pkcs7-signature", - ".pas" => "text/x-pascal", - ".pbd" => "application/vnd.powerbuilder6", - ".pbm" => "image/x-portable-bitmap", - ".pcl" => "application/vnd.hp-pcl", - ".pclxl" => "application/vnd.hp-pclxl", - ".pcx" => "image/x-pcx", - ".pdb" => "chemical/x-pdb", - ".pdf" => "application/pdf", - ".pem" => "application/x-x509-ca-cert", - ".pfr" => "application/font-tdpfr", - ".pgm" => "image/x-portable-graymap", - ".pgn" => "application/x-chess-pgn", - ".pgp" => "application/pgp-encrypted", - ".pic" => "image/x-pict", - ".pict" => "image/pict", - ".pkg" => "application/octet-stream", - ".pki" => "application/pkixcmp", - ".pkipath" => "application/pkix-pkipath", - ".pl" => "text/x-script.perl", - ".plb" => "application/vnd.3gpp.pic-bw-large", - ".plc" => "application/vnd.mobius.plc", - ".plf" => "application/vnd.pocketlearn", - ".pls" => "application/pls+xml", - ".pm" => "text/x-script.perl-module", - ".pml" => "application/vnd.ctc-posml", - ".png" => "image/png", - ".pnm" => "image/x-portable-anymap", - ".pntg" => "image/x-macpaint", - ".portpkg" => "application/vnd.macports.portpkg", - ".ppd" => "application/vnd.cups-ppd", - ".ppm" => "image/x-portable-pixmap", - ".pps" => "application/vnd.ms-powerpoint", - ".ppt" => "application/vnd.ms-powerpoint", - ".prc" => "application/vnd.palm", - ".pre" => "application/vnd.lotus-freelance", - ".prf" => "application/pics-rules", - ".ps" => "application/postscript", - ".psb" => "application/vnd.3gpp.pic-bw-small", - ".psd" => "image/vnd.adobe.photoshop", - ".ptid" => "application/vnd.pvi.ptid1", - ".pub" => "application/x-mspublisher", - ".pvb" => "application/vnd.3gpp.pic-bw-var", - ".pwn" => "application/vnd.3m.post-it-notes", - ".py" => "text/x-script.python", - ".pya" => "audio/vnd.ms-playready.media.pya", - ".pyv" => "video/vnd.ms-playready.media.pyv", - ".qam" => "application/vnd.epson.quickanime", - ".qbo" => "application/vnd.intu.qbo", - ".qfx" => "application/vnd.intu.qfx", - ".qps" => "application/vnd.publishare-delta-tree", - ".qt" => "video/quicktime", - ".qtif" => "image/x-quicktime", - ".qxd" => "application/vnd.quark.quarkxpress", - ".ra" => "audio/x-pn-realaudio", - ".rake" => "text/x-script.ruby", - ".ram" => "audio/x-pn-realaudio", - ".rar" => "application/x-rar-compressed", - ".ras" => "image/x-cmu-raster", - ".rb" => "text/x-script.ruby", - ".rcprofile" => "application/vnd.ipunplugged.rcprofile", - ".rdf" => "application/rdf+xml", - ".rdz" => "application/vnd.data-vision.rdz", - ".rep" => "application/vnd.businessobjects", - ".rgb" => "image/x-rgb", - ".rif" => "application/reginfo+xml", - ".rl" => "application/resource-lists+xml", - ".rlc" => "image/vnd.fujixerox.edmics-rlc", - ".rld" => "application/resource-lists-diff+xml", - ".rm" => "application/vnd.rn-realmedia", - ".rmp" => "audio/x-pn-realaudio-plugin", - ".rms" => "application/vnd.jcp.javame.midlet-rms", - ".rnc" => "application/relax-ng-compact-syntax", - ".roff" => "text/troff", - ".rpm" => "application/x-redhat-package-manager", - ".rpss" => "application/vnd.nokia.radio-presets", - ".rpst" => "application/vnd.nokia.radio-preset", - ".rq" => "application/sparql-query", - ".rs" => "application/rls-services+xml", - ".rsd" => "application/rsd+xml", - ".rss" => "application/rss+xml", - ".rtf" => "application/rtf", - ".rtx" => "text/richtext", - ".ru" => "text/x-script.ruby", - ".s" => "text/x-asm", - ".saf" => "application/vnd.yamaha.smaf-audio", - ".sbml" => "application/sbml+xml", - ".sc" => "application/vnd.ibm.secure-container", - ".scd" => "application/x-msschedule", - ".scm" => "application/vnd.lotus-screencam", - ".scq" => "application/scvp-cv-request", - ".scs" => "application/scvp-cv-response", - ".sdkm" => "application/vnd.solent.sdkm+xml", - ".sdp" => "application/sdp", - ".see" => "application/vnd.seemail", - ".sema" => "application/vnd.sema", - ".semd" => "application/vnd.semd", - ".semf" => "application/vnd.semf", - ".setpay" => "application/set-payment-initiation", - ".setreg" => "application/set-registration-initiation", - ".sfd" => "application/vnd.hydrostatix.sof-data", - ".sfs" => "application/vnd.spotfire.sfs", - ".sgm" => "text/sgml", - ".sgml" => "text/sgml", - ".sh" => "application/x-sh", - ".shar" => "application/x-shar", - ".shf" => "application/shf+xml", - ".sig" => "application/pgp-signature", - ".sit" => "application/x-stuffit", - ".sitx" => "application/x-stuffitx", - ".skp" => "application/vnd.koan", - ".slt" => "application/vnd.epson.salt", - ".smi" => "application/smil+xml", - ".snd" => "audio/basic", - ".so" => "application/octet-stream", - ".spf" => "application/vnd.yamaha.smaf-phrase", - ".spl" => "application/x-futuresplash", - ".spot" => "text/vnd.in3d.spot", - ".spp" => "application/scvp-vp-response", - ".spq" => "application/scvp-vp-request", - ".src" => "application/x-wais-source", - ".srx" => "application/sparql-results+xml", - ".sse" => "application/vnd.kodak-descriptor", - ".ssf" => "application/vnd.epson.ssf", - ".ssml" => "application/ssml+xml", - ".stf" => "application/vnd.wt.stf", - ".stk" => "application/hyperstudio", - ".str" => "application/vnd.pg.format", - ".sus" => "application/vnd.sus-calendar", - ".sv4cpio" => "application/x-sv4cpio", - ".sv4crc" => "application/x-sv4crc", - ".svd" => "application/vnd.svd", - ".svg" => "image/svg+xml", - ".svgz" => "image/svg+xml", - ".swf" => "application/x-shockwave-flash", - ".swi" => "application/vnd.arastra.swi", - ".t" => "text/troff", - ".tao" => "application/vnd.tao.intent-module-archive", - ".tar" => "application/x-tar", - ".tbz" => "application/x-bzip-compressed-tar", - ".tcap" => "application/vnd.3gpp2.tcap", - ".tcl" => "application/x-tcl", - ".tex" => "application/x-tex", - ".texi" => "application/x-texinfo", - ".texinfo" => "application/x-texinfo", - ".text" => "text/plain", - ".tif" => "image/tiff", - ".tiff" => "image/tiff", - ".tmo" => "application/vnd.tmobile-livetv", - ".torrent" => "application/x-bittorrent", - ".tpl" => "application/vnd.groove-tool-template", - ".tpt" => "application/vnd.trid.tpt", - ".tr" => "text/troff", - ".tra" => "application/vnd.trueapp", - ".trm" => "application/x-msterminal", - ".tsv" => "text/tab-separated-values", - ".ttf" => "application/octet-stream", - ".twd" => "application/vnd.simtech-mindmapper", - ".txd" => "application/vnd.genomatix.tuxedo", - ".txf" => "application/vnd.mobius.txf", - ".txt" => "text/plain", - ".ufd" => "application/vnd.ufdl", - ".umj" => "application/vnd.umajin", - ".unityweb" => "application/vnd.unity", - ".uoml" => "application/vnd.uoml+xml", - ".uri" => "text/uri-list", - ".ustar" => "application/x-ustar", - ".utz" => "application/vnd.uiq.theme", - ".uu" => "text/x-uuencode", - ".vcd" => "application/x-cdlink", - ".vcf" => "text/x-vcard", - ".vcg" => "application/vnd.groove-vcard", - ".vcs" => "text/x-vcalendar", - ".vcx" => "application/vnd.vcx", - ".vis" => "application/vnd.visionary", - ".viv" => "video/vnd.vivo", - ".vrml" => "model/vrml", - ".vsd" => "application/vnd.visio", - ".vsf" => "application/vnd.vsf", - ".vtu" => "model/vnd.vtu", - ".vxml" => "application/voicexml+xml", - ".war" => "application/java-archive", - ".wav" => "audio/x-wav", - ".wax" => "audio/x-ms-wax", - ".wbmp" => "image/vnd.wap.wbmp", - ".wbs" => "application/vnd.criticaltools.wbs+xml", - ".wbxml" => "application/vnd.wap.wbxml", - ".webm" => "video/webm", - ".wm" => "video/x-ms-wm", - ".wma" => "audio/x-ms-wma", - ".wmd" => "application/x-ms-wmd", - ".wmf" => "application/x-msmetafile", - ".wml" => "text/vnd.wap.wml", - ".wmlc" => "application/vnd.wap.wmlc", - ".wmls" => "text/vnd.wap.wmlscript", - ".wmlsc" => "application/vnd.wap.wmlscriptc", - ".wmv" => "video/x-ms-wmv", - ".wmx" => "video/x-ms-wmx", - ".wmz" => "application/x-ms-wmz", - ".woff" => "application/font-woff", - ".wpd" => "application/vnd.wordperfect", - ".wpl" => "application/vnd.ms-wpl", - ".wps" => "application/vnd.ms-works", - ".wqd" => "application/vnd.wqd", - ".wri" => "application/x-mswrite", - ".wrl" => "model/vrml", - ".wsdl" => "application/wsdl+xml", - ".wspolicy" => "application/wspolicy+xml", - ".wtb" => "application/vnd.webturbo", - ".wvx" => "video/x-ms-wvx", - ".x3d" => "application/vnd.hzn-3d-crossword", - ".xar" => "application/vnd.xara", - ".xbd" => "application/vnd.fujixerox.docuworks.binder", - ".xbm" => "image/x-xbitmap", - ".xdm" => "application/vnd.syncml.dm+xml", - ".xdp" => "application/vnd.adobe.xdp+xml", - ".xdw" => "application/vnd.fujixerox.docuworks", - ".xenc" => "application/xenc+xml", - ".xer" => "application/patch-ops-error+xml", - ".xfdf" => "application/vnd.adobe.xfdf", - ".xfdl" => "application/vnd.xfdl", - ".xhtml" => "application/xhtml+xml", - ".xif" => "image/vnd.xiff", - ".xls" => "application/vnd.ms-excel", - ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - ".xml" => "application/xml", - ".xo" => "application/vnd.olpc-sugar", - ".xop" => "application/xop+xml", - ".xpm" => "image/x-xpixmap", - ".xpr" => "application/vnd.is-xpr", - ".xps" => "application/vnd.ms-xpsdocument", - ".xpw" => "application/vnd.intercon.formnet", - ".xsl" => "application/xml", - ".xslt" => "application/xslt+xml", - ".xsm" => "application/vnd.syncml+xml", - ".xspf" => "application/xspf+xml", - ".xul" => "application/vnd.mozilla.xul+xml", - ".xwd" => "image/x-xwindowdump", - ".xyz" => "chemical/x-xyz", - ".yaml" => "text/yaml", - ".yml" => "text/yaml", - ".zaz" => "application/vnd.zzazz.deck+xml", - ".zip" => "application/zip", - ".zmm" => "application/vnd.handheld-entertainment+xml", - } - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/mock.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/mock.rb deleted file mode 100644 index ac7ef08..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/mock.rb +++ /dev/null @@ -1,190 +0,0 @@ -require 'uri' -require 'stringio' -require 'rack' -require 'rack/lint' -require 'rack/utils' -require 'rack/response' - -module Rack - # Rack::MockRequest helps testing your Rack application without - # actually using HTTP. - # - # After performing a request on a URL with get/post/put/patch/delete, it - # returns a MockResponse with useful helper methods for effective - # testing. - # - # You can pass a hash with additional configuration to the - # get/post/put/patch/delete. - # :input:: A String or IO-like to be used as rack.input. - # :fatal:: Raise a FatalWarning if the app writes to rack.errors. - # :lint:: If true, wrap the application in a Rack::Lint. - - class MockRequest - class FatalWarning < RuntimeError - end - - class FatalWarner - def puts(warning) - raise FatalWarning, warning - end - - def write(warning) - raise FatalWarning, warning - end - - def flush - end - - def string - "" - end - end - - DEFAULT_ENV = { - "rack.version" => Rack::VERSION, - "rack.input" => StringIO.new, - "rack.errors" => StringIO.new, - "rack.multithread" => true, - "rack.multiprocess" => true, - "rack.run_once" => false, - } - - def initialize(app) - @app = app - end - - def get(uri, opts={}) request("GET", uri, opts) end - def post(uri, opts={}) request("POST", uri, opts) end - def put(uri, opts={}) request("PUT", uri, opts) end - def patch(uri, opts={}) request("PATCH", uri, opts) end - def delete(uri, opts={}) request("DELETE", uri, opts) end - def head(uri, opts={}) request("HEAD", uri, opts) end - - def request(method="GET", uri="", opts={}) - env = self.class.env_for(uri, opts.merge(:method => method)) - - if opts[:lint] - app = Rack::Lint.new(@app) - else - app = @app - end - - errors = env["rack.errors"] - status, headers, body = app.call(env) - MockResponse.new(status, headers, body, errors) - ensure - body.close if body.respond_to?(:close) - end - - # Return the Rack environment used for a request to +uri+. - def self.env_for(uri="", opts={}) - uri = URI(uri) - uri.path = "/#{uri.path}" unless uri.path[0] == ?/ - - env = DEFAULT_ENV.dup - - env["REQUEST_METHOD"] = opts[:method] ? opts[:method].to_s.upcase : "GET" - env["SERVER_NAME"] = uri.host || "example.org" - env["SERVER_PORT"] = uri.port ? uri.port.to_s : "80" - env["QUERY_STRING"] = uri.query.to_s - env["PATH_INFO"] = (!uri.path || uri.path.empty?) ? "/" : uri.path - env["rack.url_scheme"] = uri.scheme || "http" - env["HTTPS"] = env["rack.url_scheme"] == "https" ? "on" : "off" - - env["SCRIPT_NAME"] = opts[:script_name] || "" - - if opts[:fatal] - env["rack.errors"] = FatalWarner.new - else - env["rack.errors"] = StringIO.new - end - - if params = opts[:params] - if env["REQUEST_METHOD"] == "GET" - params = Utils.parse_nested_query(params) if params.is_a?(String) - params.update(Utils.parse_nested_query(env["QUERY_STRING"])) - env["QUERY_STRING"] = Utils.build_nested_query(params) - elsif !opts.has_key?(:input) - opts["CONTENT_TYPE"] = "application/x-www-form-urlencoded" - if params.is_a?(Hash) - if data = Utils::Multipart.build_multipart(params) - opts[:input] = data - opts["CONTENT_LENGTH"] ||= data.length.to_s - opts["CONTENT_TYPE"] = "multipart/form-data; boundary=#{Utils::Multipart::MULTIPART_BOUNDARY}" - else - opts[:input] = Utils.build_nested_query(params) - end - else - opts[:input] = params - end - end - end - - empty_str = "" - empty_str.force_encoding("ASCII-8BIT") if empty_str.respond_to? :force_encoding - opts[:input] ||= empty_str - if String === opts[:input] - rack_input = StringIO.new(opts[:input]) - else - rack_input = opts[:input] - end - - rack_input.set_encoding(Encoding::BINARY) if rack_input.respond_to?(:set_encoding) - env['rack.input'] = rack_input - - env["CONTENT_LENGTH"] ||= env["rack.input"].length.to_s - - opts.each { |field, value| - env[field] = value if String === field - } - - env - end - end - - # Rack::MockResponse provides useful helpers for testing your apps. - # Usually, you don't create the MockResponse on your own, but use - # MockRequest. - - class MockResponse < Rack::Response - # Headers - attr_reader :original_headers - - # Errors - attr_accessor :errors - - def initialize(status, headers, body, errors=StringIO.new("")) - @original_headers = headers - @errors = errors.string if errors.respond_to?(:string) - @body_string = nil - - super(body, status, headers) - end - - def =~(other) - body =~ other - end - - def match(other) - body.match other - end - - def body - # FIXME: apparently users of MockResponse expect the return value of - # MockResponse#body to be a string. However, the real response object - # returns the body as a list. - # - # See spec_showstatus.rb: - # - # should "not replace existing messages" do - # ... - # res.body.should == "foo!" - # end - super.join - end - - def empty? - [201, 204, 205, 304].include? status - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart.rb deleted file mode 100644 index 6849248..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart.rb +++ /dev/null @@ -1,34 +0,0 @@ -module Rack - # A multipart form data parser, adapted from IOWA. - # - # Usually, Rack::Request#POST takes care of calling this. - module Multipart - autoload :UploadedFile, 'rack/multipart/uploaded_file' - autoload :Parser, 'rack/multipart/parser' - autoload :Generator, 'rack/multipart/generator' - - EOL = "\r\n" - MULTIPART_BOUNDARY = "AaB03x" - MULTIPART = %r|\Amultipart/.*boundary=\"?([^\";,]+)\"?|n - TOKEN = /[^\s()<>,;:\\"\/\[\]?=]+/ - CONDISP = /Content-Disposition:\s*#{TOKEN}\s*/i - DISPPARM = /;\s*(#{TOKEN})=("(?:\\"|[^"])*"|#{TOKEN})/ - RFC2183 = /^#{CONDISP}(#{DISPPARM})+$/i - BROKEN_QUOTED = /^#{CONDISP}.*;\sfilename="(.*?)"(?:\s*$|\s*;\s*#{TOKEN}=)/i - BROKEN_UNQUOTED = /^#{CONDISP}.*;\sfilename=(#{TOKEN})/i - MULTIPART_CONTENT_TYPE = /Content-Type: (.*)#{EOL}/ni - MULTIPART_CONTENT_DISPOSITION = /Content-Disposition:.*\s+name="?([^\";]*)"?/ni - MULTIPART_CONTENT_ID = /Content-ID:\s*([^#{EOL}]*)/ni - - class << self - def parse_multipart(env) - Parser.new(env).parse - end - - def build_multipart(params, first = true) - Generator.new(params, first).dump - end - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/generator.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/generator.rb deleted file mode 100644 index 1c586b7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/generator.rb +++ /dev/null @@ -1,93 +0,0 @@ -module Rack - module Multipart - class Generator - def initialize(params, first = true) - @params, @first = params, first - - if @first && !@params.is_a?(Hash) - raise ArgumentError, "value must be a Hash" - end - end - - def dump - return nil if @first && !multipart? - return flattened_params if !@first - - flattened_params.map do |name, file| - if file.respond_to?(:original_filename) - ::File.open(file.path, "rb") do |f| - f.set_encoding(Encoding::BINARY) if f.respond_to?(:set_encoding) - content_for_tempfile(f, file, name) - end - else - content_for_other(file, name) - end - end.join + "--#{MULTIPART_BOUNDARY}--\r" - end - - private - def multipart? - multipart = false - - query = lambda { |value| - case value - when Array - value.each(&query) - when Hash - value.values.each(&query) - when Rack::Multipart::UploadedFile - multipart = true - end - } - @params.values.each(&query) - - multipart - end - - def flattened_params - @flattened_params ||= begin - h = Hash.new - @params.each do |key, value| - k = @first ? key.to_s : "[#{key}]" - - case value - when Array - value.map { |v| - Multipart.build_multipart(v, false).each { |subkey, subvalue| - h["#{k}[]#{subkey}"] = subvalue - } - } - when Hash - Multipart.build_multipart(value, false).each { |subkey, subvalue| - h[k + subkey] = subvalue - } - else - h[k] = value - end - end - h - end - end - - def content_for_tempfile(io, file, name) -<<-EOF ---#{MULTIPART_BOUNDARY}\r -Content-Disposition: form-data; name="#{name}"; filename="#{Utils.escape(file.original_filename)}"\r -Content-Type: #{file.content_type}\r -Content-Length: #{::File.stat(file.path).size}\r -\r -#{io.read}\r -EOF - end - - def content_for_other(file, name) -<<-EOF ---#{MULTIPART_BOUNDARY}\r -Content-Disposition: form-data; name="#{name}"\r -\r -#{file}\r -EOF - end - end - end -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb deleted file mode 100644 index 1315c7b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/parser.rb +++ /dev/null @@ -1,176 +0,0 @@ -require 'rack/utils' - -module Rack - module Multipart - class Parser - BUFSIZE = 16384 - - def initialize(env) - @env = env - end - - def parse - return nil unless setup_parse - - fast_forward_to_first_boundary - - loop do - head, filename, content_type, name, body = - get_current_head_and_filename_and_content_type_and_name_and_body - - # Save the rest. - if i = @buf.index(rx) - body << @buf.slice!(0, i) - @buf.slice!(0, @boundary_size+2) - - @content_length = -1 if $1 == "--" - end - - filename, data = get_data(filename, body, content_type, name, head) - - Utils.normalize_params(@params, name, data) unless data.nil? - - # break if we're at the end of a buffer, but not if it is the end of a field - break if (@buf.empty? && $1 != EOL) || @content_length == -1 - end - - @io.rewind - - @params.to_params_hash - end - - private - def setup_parse - return false unless @env['CONTENT_TYPE'] =~ MULTIPART - - @boundary = "--#{$1}" - - @buf = "" - @params = Utils::KeySpaceConstrainedParams.new - - @io = @env['rack.input'] - @io.rewind - - @boundary_size = Utils.bytesize(@boundary) + EOL.size - - if @content_length = @env['CONTENT_LENGTH'] - @content_length = @content_length.to_i - @content_length -= @boundary_size - end - true - end - - def full_boundary - @boundary + EOL - end - - def rx - @rx ||= /(?:#{EOL})?#{Regexp.quote(@boundary)}(#{EOL}|--)/n - end - - def fast_forward_to_first_boundary - loop do - content = @io.read(BUFSIZE) - raise EOFError, "bad content body" unless content - @buf << content - - while @buf.gsub!(/\A([^\n]*\n)/, '') - read_buffer = $1 - return if read_buffer == full_boundary - end - - raise EOFError, "bad content body" if Utils.bytesize(@buf) >= BUFSIZE - end - end - - def get_current_head_and_filename_and_content_type_and_name_and_body - head = nil - body = '' - filename = content_type = name = nil - content = nil - - until head && @buf =~ rx - if !head && i = @buf.index(EOL+EOL) - head = @buf.slice!(0, i+2) # First \r\n - - @buf.slice!(0, 2) # Second \r\n - - content_type = head[MULTIPART_CONTENT_TYPE, 1] - name = head[MULTIPART_CONTENT_DISPOSITION, 1] || head[MULTIPART_CONTENT_ID, 1] - - filename = get_filename(head) - - if filename - body = Tempfile.new("RackMultipart") - body.binmode if body.respond_to?(:binmode) - end - - next - end - - # Save the read body part. - if head && (@boundary_size+4 < @buf.size) - body << @buf.slice!(0, @buf.size - (@boundary_size+4)) - end - - content = @io.read(@content_length && BUFSIZE >= @content_length ? @content_length : BUFSIZE) - raise EOFError, "bad content body" if content.nil? || content.empty? - - @buf << content - @content_length -= content.size if @content_length - end - - [head, filename, content_type, name, body] - end - - def get_filename(head) - filename = nil - if head =~ RFC2183 - filename = Hash[head.scan(DISPPARM)]['filename'] - filename = $1 if filename and filename =~ /^"(.*)"$/ - elsif head =~ BROKEN_QUOTED - filename = $1 - elsif head =~ BROKEN_UNQUOTED - filename = $1 - end - - if filename && filename.scan(/%.?.?/).all? { |s| s =~ /%[0-9a-fA-F]{2}/ } - filename = Utils.unescape(filename) - end - if filename && filename !~ /\\[^\\"]/ - filename = filename.gsub(/\\(.)/, '\1') - end - filename - end - - def get_data(filename, body, content_type, name, head) - data = nil - if filename == "" - # filename is blank which means no file has been selected - return data - elsif filename - body.rewind - - # Take the basename of the upload's original filename. - # This handles the full Windows paths given by Internet Explorer - # (and perhaps other broken user agents) without affecting - # those which give the lone filename. - filename = filename.split(/[\/\\]/).last - - data = {:filename => filename, :type => content_type, - :name => name, :tempfile => body, :head => head} - elsif !filename && content_type && body.is_a?(IO) - body.rewind - - # Generic multipart cases, not coming from a form - data = {:type => content_type, - :name => name, :tempfile => body, :head => head} - else - data = body - end - - [filename, data] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/uploaded_file.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/uploaded_file.rb deleted file mode 100644 index 11932b1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/multipart/uploaded_file.rb +++ /dev/null @@ -1,34 +0,0 @@ -module Rack - module Multipart - class UploadedFile - # The filename, *not* including the path, of the "uploaded" file - attr_reader :original_filename - - # The content type of the "uploaded" file - attr_accessor :content_type - - def initialize(path, content_type = "text/plain", binary = false) - raise "#{path} file does not exist" unless ::File.exist?(path) - @content_type = content_type - @original_filename = ::File.basename(path) - @tempfile = Tempfile.new(@original_filename) - @tempfile.set_encoding(Encoding::BINARY) if @tempfile.respond_to?(:set_encoding) - @tempfile.binmode if binary - FileUtils.copy_file(path, @tempfile.path) - end - - def path - @tempfile.path - end - alias_method :local_path, :path - - def respond_to?(*args) - super or @tempfile.respond_to?(*args) - end - - def method_missing(method_name, *args, &block) #:nodoc: - @tempfile.__send__(method_name, *args, &block) - end - end - end -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/nulllogger.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/nulllogger.rb deleted file mode 100644 index 77fb637..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/nulllogger.rb +++ /dev/null @@ -1,18 +0,0 @@ -module Rack - class NullLogger - def initialize(app) - @app = app - end - - def call(env) - env['rack.logger'] = self - @app.call(env) - end - - def info(progname = nil, &block); end - def debug(progname = nil, &block); end - def warn(progname = nil, &block); end - def error(progname = nil, &block); end - def fatal(progname = nil, &block); end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/recursive.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/recursive.rb deleted file mode 100644 index b431d4d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/recursive.rb +++ /dev/null @@ -1,61 +0,0 @@ -require 'uri' - -module Rack - # Rack::ForwardRequest gets caught by Rack::Recursive and redirects - # the current request to the app at +url+. - # - # raise ForwardRequest.new("/not-found") - # - - class ForwardRequest < Exception - attr_reader :url, :env - - def initialize(url, env={}) - @url = URI(url) - @env = env - - @env["PATH_INFO"] = @url.path - @env["QUERY_STRING"] = @url.query if @url.query - @env["HTTP_HOST"] = @url.host if @url.host - @env["HTTP_PORT"] = @url.port if @url.port - @env["rack.url_scheme"] = @url.scheme if @url.scheme - - super "forwarding to #{url}" - end - end - - # Rack::Recursive allows applications called down the chain to - # include data from other applications (by using - # rack['rack.recursive.include'][...] or raise a - # ForwardRequest to redirect internally. - - class Recursive - def initialize(app) - @app = app - end - - def call(env) - dup._call(env) - end - - def _call(env) - @script_name = env["SCRIPT_NAME"] - @app.call(env.merge('rack.recursive.include' => method(:include))) - rescue ForwardRequest => req - call(env.merge(req.env)) - end - - def include(env, path) - unless path.index(@script_name) == 0 && (path[@script_name.size] == ?/ || - path[@script_name.size].nil?) - raise ArgumentError, "can only include below #{@script_name}, not #{path}" - end - - env = env.merge("PATH_INFO" => path, "SCRIPT_NAME" => @script_name, - "REQUEST_METHOD" => "GET", - "CONTENT_LENGTH" => "0", "CONTENT_TYPE" => "", - "rack.input" => StringIO.new("")) - @app.call(env) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/reloader.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/reloader.rb deleted file mode 100644 index 5f64359..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/reloader.rb +++ /dev/null @@ -1,109 +0,0 @@ -# Copyright (c) 2009 Michael Fellinger m.fellinger@gmail.com -# Rack::Reloader is subject to the terms of an MIT-style license. -# See COPYING or http://www.opensource.org/licenses/mit-license.php. - -require 'pathname' - -module Rack - - # High performant source reloader - # - # This class acts as Rack middleware. - # - # What makes it especially suited for use in a production environment is that - # any file will only be checked once and there will only be made one system - # call stat(2). - # - # Please note that this will not reload files in the background, it does so - # only when actively called. - # - # It is performing a check/reload cycle at the start of every request, but - # also respects a cool down time, during which nothing will be done. - class Reloader - def initialize(app, cooldown = 10, backend = Stat) - @app = app - @cooldown = cooldown - @last = (Time.now - cooldown) - @cache = {} - @mtimes = {} - - extend backend - end - - def call(env) - if @cooldown and Time.now > @last + @cooldown - if Thread.list.size > 1 - Thread.exclusive{ reload! } - else - reload! - end - - @last = Time.now - end - - @app.call(env) - end - - def reload!(stderr = $stderr) - rotation do |file, mtime| - previous_mtime = @mtimes[file] ||= mtime - safe_load(file, mtime, stderr) if mtime > previous_mtime - end - end - - # A safe Kernel::load, issuing the hooks depending on the results - def safe_load(file, mtime, stderr = $stderr) - load(file) - stderr.puts "#{self.class}: reloaded `#{file}'" - file - rescue LoadError, SyntaxError => ex - stderr.puts ex - ensure - @mtimes[file] = mtime - end - - module Stat - def rotation - files = [$0, *$LOADED_FEATURES].uniq - paths = ['./', *$LOAD_PATH].uniq - - files.map{|file| - next if file =~ /\.(so|bundle)$/ # cannot reload compiled files - - found, stat = figure_path(file, paths) - next unless found && stat && mtime = stat.mtime - - @cache[file] = found - - yield(found, mtime) - }.compact - end - - # Takes a relative or absolute +file+ name, a couple possible +paths+ that - # the +file+ might reside in. Returns the full path and File::Stat for the - # path. - def figure_path(file, paths) - found = @cache[file] - found = file if !found and Pathname.new(file).absolute? - found, stat = safe_stat(found) - return found, stat if found - - paths.find do |possible_path| - path = ::File.join(possible_path, file) - found, stat = safe_stat(path) - return ::File.expand_path(found), stat if found - end - - return false, false - end - - def safe_stat(file) - return unless file - stat = ::File.stat(file) - return file, stat if stat.file? - rescue Errno::ENOENT, Errno::ENOTDIR, Errno::ESRCH - @cache.delete(file) and false - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/request.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/request.rb deleted file mode 100644 index e8734d7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/request.rb +++ /dev/null @@ -1,380 +0,0 @@ -require 'rack/utils' - -module Rack - # Rack::Request provides a convenient interface to a Rack - # environment. It is stateless, the environment +env+ passed to the - # constructor will be directly modified. - # - # req = Rack::Request.new(env) - # req.post? - # req.params["data"] - # - # The environment hash passed will store a reference to the Request object - # instantiated so that it will only instantiate if an instance of the Request - # object doesn't already exist. - - class Request - # The environment of the request. - attr_reader :env - - def initialize(env) - @env = env - end - - def body; @env["rack.input"] end - def script_name; @env["SCRIPT_NAME"].to_s end - def path_info; @env["PATH_INFO"].to_s end - def request_method; @env["REQUEST_METHOD"] end - def query_string; @env["QUERY_STRING"].to_s end - def content_length; @env['CONTENT_LENGTH'] end - - def content_type - content_type = @env['CONTENT_TYPE'] - content_type.nil? || content_type.empty? ? nil : content_type - end - - def session; @env['rack.session'] ||= {} end - def session_options; @env['rack.session.options'] ||= {} end - def logger; @env['rack.logger'] end - - # The media type (type/subtype) portion of the CONTENT_TYPE header - # without any media type parameters. e.g., when CONTENT_TYPE is - # "text/plain;charset=utf-8", the media-type is "text/plain". - # - # For more information on the use of media types in HTTP, see: - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 - def media_type - content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase - end - - # The media type parameters provided in CONTENT_TYPE as a Hash, or - # an empty Hash if no CONTENT_TYPE or media-type parameters were - # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8", - # this method responds with the following Hash: - # { 'charset' => 'utf-8' } - def media_type_params - return {} if content_type.nil? - Hash[*content_type.split(/\s*[;,]\s*/)[1..-1]. - collect { |s| s.split('=', 2) }. - map { |k,v| [k.downcase, v] }.flatten] - end - - # The character set of the request body if a "charset" media type - # parameter was given, or nil if no "charset" was specified. Note - # that, per RFC2616, text/* media types that specify no explicit - # charset are to be considered ISO-8859-1. - def content_charset - media_type_params['charset'] - end - - def scheme - if @env['HTTPS'] == 'on' - 'https' - elsif @env['HTTP_X_FORWARDED_SSL'] == 'on' - 'https' - elsif @env['HTTP_X_FORWARDED_SCHEME'] - @env['HTTP_X_FORWARDED_SCHEME'] - elsif @env['HTTP_X_FORWARDED_PROTO'] - @env['HTTP_X_FORWARDED_PROTO'].split(',')[0] - else - @env["rack.url_scheme"] - end - end - - def ssl? - scheme == 'https' - end - - def host_with_port - if forwarded = @env["HTTP_X_FORWARDED_HOST"] - forwarded.split(/,\s?/).last - else - @env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}" - end - end - - def port - if port = host_with_port.split(/:/)[1] - port.to_i - elsif port = @env['HTTP_X_FORWARDED_PORT'] - port.to_i - elsif @env.has_key?("HTTP_X_FORWARDED_HOST") - DEFAULT_PORTS[scheme] - else - @env["SERVER_PORT"].to_i - end - end - - def host - # Remove port number. - host_with_port.to_s.gsub(/:\d+\z/, '') - end - - def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end - def path_info=(s); @env["PATH_INFO"] = s.to_s end - - - # Checks the HTTP request method (or verb) to see if it was of type DELETE - def delete?; request_method == "DELETE" end - - # Checks the HTTP request method (or verb) to see if it was of type GET - def get?; request_method == "GET" end - - # Checks the HTTP request method (or verb) to see if it was of type HEAD - def head?; request_method == "HEAD" end - - # Checks the HTTP request method (or verb) to see if it was of type OPTIONS - def options?; request_method == "OPTIONS" end - - # Checks the HTTP request method (or verb) to see if it was of type PATCH - def patch?; request_method == "PATCH" end - - # Checks the HTTP request method (or verb) to see if it was of type POST - def post?; request_method == "POST" end - - # Checks the HTTP request method (or verb) to see if it was of type PUT - def put?; request_method == "PUT" end - - # Checks the HTTP request method (or verb) to see if it was of type TRACE - def trace?; request_method == "TRACE" end - - - # The set of form-data media-types. Requests that do not indicate - # one of the media types presents in this list will not be eligible - # for form-data / param parsing. - FORM_DATA_MEDIA_TYPES = [ - 'application/x-www-form-urlencoded', - 'multipart/form-data' - ] - - # The set of media-types. Requests that do not indicate - # one of the media types presents in this list will not be eligible - # for param parsing like soap attachments or generic multiparts - PARSEABLE_DATA_MEDIA_TYPES = [ - 'multipart/related', - 'multipart/mixed' - ] - - # Default ports depending on scheme. Used to decide whether or not - # to include the port in a generated URI. - DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 } - - # Determine whether the request body contains form-data by checking - # the request Content-Type for one of the media-types: - # "application/x-www-form-urlencoded" or "multipart/form-data". The - # list of form-data media types can be modified through the - # +FORM_DATA_MEDIA_TYPES+ array. - # - # A request body is also assumed to contain form-data when no - # Content-Type header is provided and the request_method is POST. - def form_data? - type = media_type - meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD'] - (meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type) - end - - # Determine whether the request body contains data by checking - # the request media_type against registered parse-data media-types - def parseable_data? - PARSEABLE_DATA_MEDIA_TYPES.include?(media_type) - end - - # Returns the data received in the query string. - def GET - if @env["rack.request.query_string"] == query_string - @env["rack.request.query_hash"] - else - @env["rack.request.query_string"] = query_string - @env["rack.request.query_hash"] = parse_query(query_string) - end - end - - # Returns the data received in the request body. - # - # This method support both application/x-www-form-urlencoded and - # multipart/form-data. - def POST - if @env["rack.input"].nil? - raise "Missing rack.input" - elsif @env["rack.request.form_input"].eql? @env["rack.input"] - @env["rack.request.form_hash"] - elsif form_data? || parseable_data? - @env["rack.request.form_input"] = @env["rack.input"] - unless @env["rack.request.form_hash"] = parse_multipart(env) - form_vars = @env["rack.input"].read - - # Fix for Safari Ajax postings that always append \0 - # form_vars.sub!(/\0\z/, '') # performance replacement: - form_vars.slice!(-1) if form_vars[-1] == ?\0 - - @env["rack.request.form_vars"] = form_vars - @env["rack.request.form_hash"] = parse_query(form_vars) - - @env["rack.input"].rewind - end - @env["rack.request.form_hash"] - else - {} - end - end - - # The union of GET and POST data. - # - # Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params. - def params - @params ||= self.GET.merge(self.POST) - rescue EOFError - self.GET.dup - end - - # Destructively update a parameter, whether it's in GET and/or POST. Returns nil. - # - # The parameter is updated wherever it was previous defined, so GET, POST, or both. If it wasn't previously defined, it's inserted into GET. - # - # env['rack.input'] is not touched. - def update_param(k, v) - found = false - if self.GET.has_key?(k) - found = true - self.GET[k] = v - end - if self.POST.has_key?(k) - found = true - self.POST[k] = v - end - unless found - self.GET[k] = v - end - @params = nil - nil - end - - # Destructively delete a parameter, whether it's in GET or POST. Returns the value of the deleted parameter. - # - # If the parameter is in both GET and POST, the POST value takes precedence since that's how #params works. - # - # env['rack.input'] is not touched. - def delete_param(k) - v = [ self.POST.delete(k), self.GET.delete(k) ].compact.first - @params = nil - v - end - - # shortcut for request.params[key] - def [](key) - params[key.to_s] - end - - # shortcut for request.params[key] = value - # - # Note that modifications will not be persisted in the env. Use update_param or delete_param if you want to destructively modify params. - def []=(key, value) - params[key.to_s] = value - end - - # like Hash#values_at - def values_at(*keys) - keys.map{|key| params[key] } - end - - # the referer of the client - def referer - @env['HTTP_REFERER'] - end - alias referrer referer - - def user_agent - @env['HTTP_USER_AGENT'] - end - - def cookies - hash = @env["rack.request.cookie_hash"] ||= {} - string = @env["HTTP_COOKIE"] - - return hash if string == @env["rack.request.cookie_string"] - hash.clear - - # According to RFC 2109: - # If multiple cookies satisfy the criteria above, they are ordered in - # the Cookie header such that those with more specific Path attributes - # precede those with less specific. Ordering with respect to other - # attributes (e.g., Domain) is unspecified. - cookies = Utils.parse_query(string, ';,') { |s| Rack::Utils.unescape(s) rescue s } - cookies.each { |k,v| hash[k] = Array === v ? v.first : v } - @env["rack.request.cookie_string"] = string - hash - end - - def xhr? - @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" - end - - def base_url - url = "#{scheme}://#{host}" - url << ":#{port}" if port != DEFAULT_PORTS[scheme] - url - end - - # Tries to return a remake of the original request URL as a string. - def url - base_url + fullpath - end - - def path - script_name + path_info - end - - def fullpath - query_string.empty? ? path : "#{path}?#{query_string}" - end - - def accept_encoding - @env["HTTP_ACCEPT_ENCODING"].to_s.split(/\s*,\s*/).map do |part| - encoding, parameters = part.split(/\s*;\s*/, 2) - quality = 1.0 - if parameters and /\Aq=([\d.]+)/ =~ parameters - quality = $1.to_f - end - [encoding, quality] - end - end - - def trusted_proxy?(ip) - ip =~ /\A127\.0\.0\.1\Z|\A(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|\A::1\Z|\Afd[0-9a-f]{2}:.+|\Alocalhost\Z|\Aunix\Z|\Aunix:/i - end - - def ip - remote_addrs = split_ip_addresses(@env['REMOTE_ADDR']) - remote_addrs = reject_trusted_ip_addresses(remote_addrs) - - return remote_addrs.first if remote_addrs.any? - - forwarded_ips = split_ip_addresses(@env['HTTP_X_FORWARDED_FOR']) - - if client_ip = @env['HTTP_CLIENT_IP'] - # If forwarded_ips doesn't include the client_ip, it might be an - # ip spoofing attempt, so we ignore HTTP_CLIENT_IP - return client_ip if forwarded_ips.include?(client_ip) - end - - return reject_trusted_ip_addresses(forwarded_ips).last || @env["REMOTE_ADDR"] - end - - protected - def split_ip_addresses(ip_addresses) - ip_addresses ? ip_addresses.strip.split(/[,\s]+/) : [] - end - - def reject_trusted_ip_addresses(ip_addresses) - ip_addresses.reject { |ip| trusted_proxy?(ip) } - end - - def parse_query(qs) - Utils.parse_nested_query(qs) - end - - def parse_multipart(env) - Rack::Multipart.parse_multipart(env) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/response.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/response.rb deleted file mode 100644 index 2beba7a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/response.rb +++ /dev/null @@ -1,155 +0,0 @@ -require 'rack/request' -require 'rack/utils' -require 'time' - -module Rack - # Rack::Response provides a convenient interface to create a Rack - # response. - # - # It allows setting of headers and cookies, and provides useful - # defaults (a OK response containing HTML). - # - # You can use Response#write to iteratively generate your response, - # but note that this is buffered by Rack::Response until you call - # +finish+. +finish+ however can take a block inside which calls to - # +write+ are synchronous with the Rack response. - # - # Your application's +call+ should end returning Response#finish. - - class Response - attr_accessor :length - - def initialize(body=[], status=200, header={}) - @status = status.to_i - @header = Utils::HeaderHash.new.merge(header) - - @chunked = "chunked" == @header['Transfer-Encoding'] - @writer = lambda { |x| @body << x } - @block = nil - @length = 0 - - @body = [] - - if body.respond_to? :to_str - write body.to_str - elsif body.respond_to?(:each) - body.each { |part| - write part.to_s - } - else - raise TypeError, "stringable or iterable required" - end - - yield self if block_given? - end - - attr_reader :header - attr_accessor :status, :body - - def [](key) - header[key] - end - - def []=(key, value) - header[key] = value - end - - def set_cookie(key, value) - Utils.set_cookie_header!(header, key, value) - end - - def delete_cookie(key, value={}) - Utils.delete_cookie_header!(header, key, value) - end - - def redirect(target, status=302) - self.status = status - self["Location"] = target - end - - def finish(&block) - @block = block - - if [204, 205, 304].include?(status.to_i) - header.delete "Content-Type" - header.delete "Content-Length" - close - [status.to_i, header, []] - else - [status.to_i, header, BodyProxy.new(self){}] - end - end - alias to_a finish # For *response - alias to_ary finish # For implicit-splat on Ruby 1.9.2 - - def each(&callback) - @body.each(&callback) - @writer = callback - @block.call(self) if @block - end - - # Append to body and update Content-Length. - # - # NOTE: Do not mix #write and direct #body access! - # - def write(str) - s = str.to_s - @length += Rack::Utils.bytesize(s) unless @chunked - @writer.call s - - header["Content-Length"] = @length.to_s unless @chunked - str - end - - def close - body.close if body.respond_to?(:close) - end - - def empty? - @block == nil && @body.empty? - end - - alias headers header - - module Helpers - def invalid?; status < 100 || status >= 600; end - - def informational?; status >= 100 && status < 200; end - def successful?; status >= 200 && status < 300; end - def redirection?; status >= 300 && status < 400; end - def client_error?; status >= 400 && status < 500; end - def server_error?; status >= 500 && status < 600; end - - def ok?; status == 200; end - def bad_request?; status == 400; end - def forbidden?; status == 403; end - def not_found?; status == 404; end - def method_not_allowed?; status == 405; end - def unprocessable?; status == 422; end - - def redirect?; [301, 302, 303, 307].include? status; end - - # Headers - attr_reader :headers, :original_headers - - def include?(header) - !!headers[header] - end - - def content_type - headers["Content-Type"] - end - - def content_length - cl = headers["Content-Length"] - cl ? cl.to_i : cl - end - - def location - headers["Location"] - end - end - - include Helpers - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/rewindable_input.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/rewindable_input.rb deleted file mode 100644 index 15ecc58..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/rewindable_input.rb +++ /dev/null @@ -1,104 +0,0 @@ -# -*- encoding: binary -*- -require 'tempfile' -require 'rack/utils' - -module Rack - # Class which can make any IO object rewindable, including non-rewindable ones. It does - # this by buffering the data into a tempfile, which is rewindable. - # - # rack.input is required to be rewindable, so if your input stream IO is non-rewindable - # by nature (e.g. a pipe or a socket) then you can wrap it in an object of this class - # to easily make it rewindable. - # - # Don't forget to call #close when you're done. This frees up temporary resources that - # RewindableInput uses, though it does *not* close the original IO object. - class RewindableInput - def initialize(io) - @io = io - @rewindable_io = nil - @unlinked = false - end - - def gets - make_rewindable unless @rewindable_io - @rewindable_io.gets - end - - def read(*args) - make_rewindable unless @rewindable_io - @rewindable_io.read(*args) - end - - def each(&block) - make_rewindable unless @rewindable_io - @rewindable_io.each(&block) - end - - def rewind - make_rewindable unless @rewindable_io - @rewindable_io.rewind - end - - # Closes this RewindableInput object without closing the originally - # wrapped IO oject. Cleans up any temporary resources that this RewindableInput - # has created. - # - # This method may be called multiple times. It does nothing on subsequent calls. - def close - if @rewindable_io - if @unlinked - @rewindable_io.close - else - @rewindable_io.close! - end - @rewindable_io = nil - end - end - - private - - # Ruby's Tempfile class has a bug. Subclass it and fix it. - class Tempfile < ::Tempfile - def _close - @tmpfile.close if @tmpfile - @data[1] = nil if @data - @tmpfile = nil - end - end - - def make_rewindable - # Buffer all data into a tempfile. Since this tempfile is private to this - # RewindableInput object, we chmod it so that nobody else can read or write - # it. On POSIX filesystems we also unlink the file so that it doesn't - # even have a file entry on the filesystem anymore, though we can still - # access it because we have the file handle open. - @rewindable_io = Tempfile.new('RackRewindableInput') - @rewindable_io.chmod(0000) - @rewindable_io.set_encoding(Encoding::BINARY) if @rewindable_io.respond_to?(:set_encoding) - @rewindable_io.binmode - if filesystem_has_posix_semantics? - # Use ::File.unlink as 1.9.1 Tempfile has a bug where unlink closes the file! - ::File.unlink @rewindable_io.path - raise 'Unlink failed. IO closed.' if @rewindable_io.closed? - @unlinked = true - end - - buffer = "" - while @io.read(1024 * 4, buffer) - entire_buffer_written_out = false - while !entire_buffer_written_out - written = @rewindable_io.write(buffer) - entire_buffer_written_out = written == Rack::Utils.bytesize(buffer) - if !entire_buffer_written_out - buffer.slice!(0 .. written - 1) - end - end - end - @rewindable_io.rewind - end - - def filesystem_has_posix_semantics? - RUBY_PLATFORM !~ /(mswin|mingw|cygwin|java)/ - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/runtime.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/runtime.rb deleted file mode 100644 index 1bd411f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/runtime.rb +++ /dev/null @@ -1,27 +0,0 @@ -module Rack - # Sets an "X-Runtime" response header, indicating the response - # time of the request, in seconds - # - # You can put it right before the application to see the processing - # time, or before all the other middlewares to include time for them, - # too. - class Runtime - def initialize(app, name = nil) - @app = app - @header_name = "X-Runtime" - @header_name << "-#{name}" if name - end - - def call(env) - start_time = Time.now - status, headers, body = @app.call(env) - request_time = Time.now - start_time - - if !headers.has_key?(@header_name) - headers[@header_name] = "%0.6f" % request_time - end - - [status, headers, body] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/sendfile.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/sendfile.rb deleted file mode 100644 index bc04ca2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/sendfile.rb +++ /dev/null @@ -1,155 +0,0 @@ -require 'rack/file' - -module Rack - - # = Sendfile - # - # The Sendfile middleware intercepts responses whose body is being - # served from a file and replaces it with a server specific X-Sendfile - # header. The web server is then responsible for writing the file contents - # to the client. This can dramatically reduce the amount of work required - # by the Ruby backend and takes advantage of the web server's optimized file - # delivery code. - # - # In order to take advantage of this middleware, the response body must - # respond to +to_path+ and the request must include an X-Sendfile-Type - # header. Rack::File and other components implement +to_path+ so there's - # rarely anything you need to do in your application. The X-Sendfile-Type - # header is typically set in your web servers configuration. The following - # sections attempt to document - # - # === Nginx - # - # Nginx supports the X-Accel-Redirect header. This is similar to X-Sendfile - # but requires parts of the filesystem to be mapped into a private URL - # hierarachy. - # - # The following example shows the Nginx configuration required to create - # a private "/files/" area, enable X-Accel-Redirect, and pass the special - # X-Sendfile-Type and X-Accel-Mapping headers to the backend: - # - # location ~ /files/(.*) { - # internal; - # alias /var/www/$1; - # } - # - # location / { - # proxy_redirect off; - # - # proxy_set_header Host $host; - # proxy_set_header X-Real-IP $remote_addr; - # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - # - # proxy_set_header X-Sendfile-Type X-Accel-Redirect; - # proxy_set_header X-Accel-Mapping /var/www/=/files/; - # - # proxy_pass http://127.0.0.1:8080/; - # } - # - # Note that the X-Sendfile-Type header must be set exactly as shown above. - # The X-Accel-Mapping header should specify the location on the file system, - # followed by an equals sign (=), followed name of the private URL pattern - # that it maps to. The middleware performs a simple substitution on the - # resulting path. - # - # See Also: http://wiki.codemongers.com/NginxXSendfile - # - # === lighttpd - # - # Lighttpd has supported some variation of the X-Sendfile header for some - # time, although only recent version support X-Sendfile in a reverse proxy - # configuration. - # - # $HTTP["host"] == "example.com" { - # proxy-core.protocol = "http" - # proxy-core.balancer = "round-robin" - # proxy-core.backends = ( - # "127.0.0.1:8000", - # "127.0.0.1:8001", - # ... - # ) - # - # proxy-core.allow-x-sendfile = "enable" - # proxy-core.rewrite-request = ( - # "X-Sendfile-Type" => (".*" => "X-Sendfile") - # ) - # } - # - # See Also: http://redmine.lighttpd.net/wiki/lighttpd/Docs:ModProxyCore - # - # === Apache - # - # X-Sendfile is supported under Apache 2.x using a separate module: - # - # https://tn123.org/mod_xsendfile/ - # - # Once the module is compiled and installed, you can enable it using - # XSendFile config directive: - # - # RequestHeader Set X-Sendfile-Type X-Sendfile - # ProxyPassReverse / http://localhost:8001/ - # XSendFile on - # - # === Mapping parameter - # - # The third parameter allows for an overriding extension of the - # X-Accel-Mapping header. Mappings should be provided in tuples of internal to - # external. The internal values may contain regular expression syntax, they - # will be matched with case indifference. - - class Sendfile - F = ::File - - def initialize(app, variation=nil, mappings=[]) - @app = app - @variation = variation - @mappings = mappings.map do |internal, external| - [/^#{internal}/i, external] - end - end - - def call(env) - status, headers, body = @app.call(env) - if body.respond_to?(:to_path) - case type = variation(env) - when 'X-Accel-Redirect' - path = F.expand_path(body.to_path) - if url = map_accel_path(env, path) - headers['Content-Length'] = '0' - headers[type] = url - body.close if body.respond_to?(:close) - body = [] - else - env['rack.errors'].puts "X-Accel-Mapping header missing" - end - when 'X-Sendfile', 'X-Lighttpd-Send-File' - path = F.expand_path(body.to_path) - headers['Content-Length'] = '0' - headers[type] = path - body.close if body.respond_to?(:close) - body = [] - when '', nil - else - env['rack.errors'].puts "Unknown x-sendfile variation: '#{variation}'.\n" - end - end - [status, headers, body] - end - - private - def variation(env) - @variation || - env['sendfile.type'] || - env['HTTP_X_SENDFILE_TYPE'] - end - - def map_accel_path(env, path) - if mapping = @mappings.find { |internal,_| internal =~ path } - path.sub(*mapping) - elsif mapping = env['HTTP_X_ACCEL_MAPPING'] - internal, external = mapping.split('=', 2).map{ |p| p.strip } - path.sub(/^#{internal}/i, external) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/server.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/server.rb deleted file mode 100644 index dfaed3f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/server.rb +++ /dev/null @@ -1,362 +0,0 @@ -require 'optparse' - -module Rack - class Server - class Options - def parse!(args) - options = {} - opt_parser = OptionParser.new("", 24, ' ') do |opts| - opts.banner = "Usage: rackup [ruby options] [rack options] [rackup config]" - - opts.separator "" - opts.separator "Ruby options:" - - lineno = 1 - opts.on("-e", "--eval LINE", "evaluate a LINE of code") { |line| - eval line, TOPLEVEL_BINDING, "-e", lineno - lineno += 1 - } - - opts.on("-b", "--builder BUILDER_LINE", "evaluate a BUILDER_LINE of code as a builder script") { |line| - options[:builder] = line - } - - opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") { - options[:debug] = true - } - opts.on("-w", "--warn", "turn warnings on for your script") { - options[:warn] = true - } - - opts.on("-I", "--include PATH", - "specify $LOAD_PATH (may be used more than once)") { |path| - (options[:include] ||= []).concat(path.split(":")) - } - - opts.on("-r", "--require LIBRARY", - "require the library, before executing your script") { |library| - options[:require] = library - } - - opts.separator "" - opts.separator "Rack options:" - opts.on("-s", "--server SERVER", "serve using SERVER (thin/puma/webrick/mongrel)") { |s| - options[:server] = s - } - - opts.on("-o", "--host HOST", "listen on HOST (default: 0.0.0.0)") { |host| - options[:Host] = host - } - - opts.on("-p", "--port PORT", "use PORT (default: 9292)") { |port| - options[:Port] = port - } - - opts.on("-O", "--option NAME[=VALUE]", "pass VALUE to the server as option NAME. If no VALUE, sets it to true. Run '#{$0} -s SERVER -h' to get a list of options for SERVER") { |name| - name, value = name.split('=', 2) - value = true if value.nil? - options[name.to_sym] = value - } - - opts.on("-E", "--env ENVIRONMENT", "use ENVIRONMENT for defaults (default: development)") { |e| - options[:environment] = e - } - - opts.on("-D", "--daemonize", "run daemonized in the background") { |d| - options[:daemonize] = d ? true : false - } - - opts.on("-P", "--pid FILE", "file to store PID (default: rack.pid)") { |f| - options[:pid] = ::File.expand_path(f) - } - - opts.separator "" - opts.separator "Common options:" - - opts.on_tail("-h", "-?", "--help", "Show this message") do - puts opts - puts handler_opts(options) - - exit - end - - opts.on_tail("--version", "Show version") do - puts "Rack #{Rack.version} (Release: #{Rack.release})" - exit - end - end - - begin - opt_parser.parse! args - rescue OptionParser::InvalidOption => e - warn e.message - abort opt_parser.to_s - end - - options[:config] = args.last if args.last - options - end - - def handler_opts(options) - begin - info = [] - server = Rack::Handler.get(options[:server]) || Rack::Handler.default(options) - if server && server.respond_to?(:valid_options) - info << "" - info << "Server-specific options for #{server.name}:" - - has_options = false - server.valid_options.each do |name, description| - next if name.to_s.match(/^(Host|Port)[^a-zA-Z]/) # ignore handler's host and port options, we do our own. - info << " -O %-21s %s" % [name, description] - has_options = true - end - return "" if !has_options - end - info.join("\n") - rescue NameError - return "Warning: Could not find handler specified (#{options[:server] || 'default'}) to determine handler-specific options" - end - end - end - - # Start a new rack server (like running rackup). This will parse ARGV and - # provide standard ARGV rackup options, defaulting to load 'config.ru'. - # - # Providing an options hash will prevent ARGV parsing and will not include - # any default options. - # - # This method can be used to very easily launch a CGI application, for - # example: - # - # Rack::Server.start( - # :app => lambda do |e| - # [200, {'Content-Type' => 'text/html'}, ['hello world']] - # end, - # :server => 'cgi' - # ) - # - # Further options available here are documented on Rack::Server#initialize - def self.start(options = nil) - new(options).start - end - - attr_writer :options - - # Options may include: - # * :app - # a rack application to run (overrides :config) - # * :config - # a rackup configuration file path to load (.ru) - # * :environment - # this selects the middleware that will be wrapped around - # your application. Default options available are: - # - development: CommonLogger, ShowExceptions, and Lint - # - deployment: CommonLogger - # - none: no extra middleware - # note: when the server is a cgi server, CommonLogger is not included. - # * :server - # choose a specific Rack::Handler, e.g. cgi, fcgi, webrick - # * :daemonize - # if true, the server will daemonize itself (fork, detach, etc) - # * :pid - # path to write a pid file after daemonize - # * :Host - # the host address to bind to (used by supporting Rack::Handler) - # * :Port - # the port to bind to (used by supporting Rack::Handler) - # * :AccessLog - # webrick acess log options (or supporting Rack::Handler) - # * :debug - # turn on debug output ($DEBUG = true) - # * :warn - # turn on warnings ($-w = true) - # * :include - # add given paths to $LOAD_PATH - # * :require - # require the given libraries - def initialize(options = nil) - @options = options - @app = options[:app] if options && options[:app] - end - - def options - @options ||= parse_options(ARGV) - end - - def default_options - { - :environment => ENV['RACK_ENV'] || "development", - :pid => nil, - :Port => 9292, - :Host => "0.0.0.0", - :AccessLog => [], - :config => "config.ru" - } - end - - def app - @app ||= options[:builder] ? build_app_from_string : build_app_and_options_from_config - end - - def self.logging_middleware - lambda { |server| - server.server.name =~ /CGI/ ? nil : [Rack::CommonLogger, $stderr] - } - end - - def self.middleware - @middleware ||= begin - m = Hash.new {|h,k| h[k] = []} - m["deployment"].concat [ - [Rack::ContentLength], - [Rack::Chunked], - logging_middleware - ] - m["development"].concat m["deployment"] + [[Rack::ShowExceptions], [Rack::Lint]] - m - end - end - - def middleware - self.class.middleware - end - - def start &blk - if options[:warn] - $-w = true - end - - if includes = options[:include] - $LOAD_PATH.unshift(*includes) - end - - if library = options[:require] - require library - end - - if options[:debug] - $DEBUG = true - require 'pp' - p options[:server] - pp wrapped_app - pp app - end - - check_pid! if options[:pid] - - # Touch the wrapped app, so that the config.ru is loaded before - # daemonization (i.e. before chdir, etc). - wrapped_app - - daemonize_app if options[:daemonize] - - write_pid if options[:pid] - - trap(:INT) do - if server.respond_to?(:shutdown) - server.shutdown - else - exit - end - end - - server.run wrapped_app, options, &blk - end - - def server - @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default(options) - end - - private - def build_app_and_options_from_config - if !::File.exist? options[:config] - abort "configuration #{options[:config]} not found" - end - - app, options = Rack::Builder.parse_file(self.options[:config], opt_parser) - self.options.merge! options - app - end - - def build_app_from_string - Rack::Builder.new_from_string(self.options[:builder]) - end - - def parse_options(args) - options = default_options - - # Don't evaluate CGI ISINDEX parameters. - # http://www.meb.uni-bonn.de/docs/cgi/cl.html - args.clear if ENV.include?("REQUEST_METHOD") - - options.merge! opt_parser.parse!(args) - options[:config] = ::File.expand_path(options[:config]) - ENV["RACK_ENV"] = options[:environment] - options - end - - def opt_parser - Options.new - end - - def build_app(app) - middleware[options[:environment]].reverse_each do |middleware| - middleware = middleware.call(self) if middleware.respond_to?(:call) - next unless middleware - klass, *args = middleware - app = klass.new(app, *args) - end - app - end - - def wrapped_app - @wrapped_app ||= build_app app - end - - def daemonize_app - if RUBY_VERSION < "1.9" - exit if fork - Process.setsid - exit if fork - Dir.chdir "/" - STDIN.reopen "/dev/null" - STDOUT.reopen "/dev/null", "a" - STDERR.reopen "/dev/null", "a" - else - Process.daemon - end - end - - def write_pid - ::File.open(options[:pid], ::File::CREAT | ::File::EXCL | ::File::WRONLY ){ |f| f.write("#{Process.pid}") } - at_exit { ::File.delete(options[:pid]) if ::File.exist?(options[:pid]) } - rescue Errno::EEXIST - check_pid! - retry - end - - def check_pid! - case pidfile_process_status - when :running, :not_owned - $stderr.puts "A server is already running. Check #{options[:pid]}." - exit(1) - when :dead - ::File.delete(options[:pid]) - end - end - - def pidfile_process_status - return :exited unless ::File.exist?(options[:pid]) - - pid = ::File.read(options[:pid]).to_i - Process.kill(0, pid) - :running - rescue Errno::ESRCH - :dead - rescue Errno::EPERM - :not_owned - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/abstract/id.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/abstract/id.rb deleted file mode 100644 index 0e0ad35..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/abstract/id.rb +++ /dev/null @@ -1,398 +0,0 @@ -# AUTHOR: blink ; blink#ruby-lang@irc.freenode.net -# bugrep: Andreas Zehnder - -require 'time' -require 'rack/request' -require 'rack/response' -begin - require 'securerandom' -rescue LoadError - # We just won't get securerandom -end - -module Rack - - module Session - - module Abstract - ENV_SESSION_KEY = 'rack.session'.freeze - ENV_SESSION_OPTIONS_KEY = 'rack.session.options'.freeze - - # SessionHash is responsible to lazily load the session from store. - - class SessionHash - include Enumerable - attr_writer :id - - def self.find(env) - env[ENV_SESSION_KEY] - end - - def self.set(env, session) - env[ENV_SESSION_KEY] = session - end - - def self.set_options(env, options) - env[ENV_SESSION_OPTIONS_KEY] = options.dup - end - - def initialize(store, env) - @store = store - @env = env - @loaded = false - end - - def id - return @id if @loaded or instance_variable_defined?(:@id) - @id = @store.send(:extract_session_id, @env) - end - - def options - @env[ENV_SESSION_OPTIONS_KEY] - end - - def each(&block) - load_for_read! - @data.each(&block) - end - - def [](key) - load_for_read! - @data[key.to_s] - end - alias :fetch :[] - - def has_key?(key) - load_for_read! - @data.has_key?(key.to_s) - end - alias :key? :has_key? - alias :include? :has_key? - - def []=(key, value) - load_for_write! - @data[key.to_s] = value - end - alias :store :[]= - - def clear - load_for_write! - @data.clear - end - - def destroy - clear - @id = @store.send(:destroy_session, @env, id, options) - end - - def to_hash - load_for_read! - @data.dup - end - - def update(hash) - load_for_write! - @data.update(stringify_keys(hash)) - end - alias :merge! :update - - def replace(hash) - load_for_write! - @data.replace(stringify_keys(hash)) - end - - def delete(key) - load_for_write! - @data.delete(key.to_s) - end - - def inspect - if loaded? - @data.inspect - else - "#<#{self.class}:0x#{self.object_id.to_s(16)} not yet loaded>" - end - end - - def exists? - return @exists if instance_variable_defined?(:@exists) - @data = {} - @exists = @store.send(:session_exists?, @env) - end - - def loaded? - @loaded - end - - def empty? - load_for_read! - @data.empty? - end - - def keys - @data.keys - end - - def values - @data.values - end - - private - - def load_for_read! - load! if !loaded? && exists? - end - - def load_for_write! - load! unless loaded? - end - - def load! - @id, session = @store.send(:load_session, @env) - @data = stringify_keys(session) - @loaded = true - end - - def stringify_keys(other) - hash = {} - other.each do |key, value| - hash[key.to_s] = value - end - hash - end - end - - # ID sets up a basic framework for implementing an id based sessioning - # service. Cookies sent to the client for maintaining sessions will only - # contain an id reference. Only #get_session and #set_session are - # required to be overwritten. - # - # All parameters are optional. - # * :key determines the name of the cookie, by default it is - # 'rack.session' - # * :path, :domain, :expire_after, :secure, and :httponly set the related - # cookie options as by Rack::Response#add_cookie - # * :skip will not a set a cookie in the response nor update the session state - # * :defer will not set a cookie in the response but still update the session - # state if it is used with a backend - # * :renew (implementation dependent) will prompt the generation of a new - # session id, and migration of data to be referenced at the new id. If - # :defer is set, it will be overridden and the cookie will be set. - # * :sidbits sets the number of bits in length that a generated session - # id will be. - # - # These options can be set on a per request basis, at the location of - # env['rack.session.options']. Additionally the id of the session can be - # found within the options hash at the key :id. It is highly not - # recommended to change its value. - # - # Is Rack::Utils::Context compatible. - # - # Not included by default; you must require 'rack/session/abstract/id' - # to use. - - class ID - DEFAULT_OPTIONS = { - :key => 'rack.session', - :path => '/', - :domain => nil, - :expire_after => nil, - :secure => false, - :httponly => true, - :defer => false, - :renew => false, - :sidbits => 128, - :cookie_only => true, - :secure_random => (::SecureRandom rescue false) - } - - attr_reader :key, :default_options - - def initialize(app, options={}) - @app = app - @default_options = self.class::DEFAULT_OPTIONS.merge(options) - @key = @default_options.delete(:key) - @cookie_only = @default_options.delete(:cookie_only) - initialize_sid - end - - def call(env) - context(env) - end - - def context(env, app=@app) - prepare_session(env) - status, headers, body = app.call(env) - commit_session(env, status, headers, body) - end - - private - - def initialize_sid - @sidbits = @default_options[:sidbits] - @sid_secure = @default_options[:secure_random] - @sid_length = @sidbits / 4 - end - - # Generate a new session id using Ruby #rand. The size of the - # session id is controlled by the :sidbits option. - # Monkey patch this to use custom methods for session id generation. - - def generate_sid(secure = @sid_secure) - if secure - secure.hex(@sid_length) - else - "%0#{@sid_length}x" % Kernel.rand(2**@sidbits - 1) - end - rescue NotImplementedError - generate_sid(false) - end - - # Sets the lazy session at 'rack.session' and places options and session - # metadata into 'rack.session.options'. - - def prepare_session(env) - session_was = env[ENV_SESSION_KEY] - env[ENV_SESSION_KEY] = session_class.new(self, env) - env[ENV_SESSION_OPTIONS_KEY] = @default_options.dup - env[ENV_SESSION_KEY].merge! session_was if session_was - end - - # Extracts the session id from provided cookies and passes it and the - # environment to #get_session. - - def load_session(env) - sid = current_session_id(env) - sid, session = get_session(env, sid) - [sid, session || {}] - end - - # Extract session id from request object. - - def extract_session_id(env) - request = Rack::Request.new(env) - sid = request.cookies[@key] - sid ||= request.params[@key] unless @cookie_only - sid - end - - # Returns the current session id from the SessionHash. - - def current_session_id(env) - env[ENV_SESSION_KEY].id - end - - # Check if the session exists or not. - - def session_exists?(env) - value = current_session_id(env) - value && !value.empty? - end - - # Session should be commited if it was loaded, any of specific options like :renew, :drop - # or :expire_after was given and the security permissions match. Skips if skip is given. - - def commit_session?(env, session, options) - if options[:skip] - false - else - has_session = loaded_session?(session) || forced_session_update?(session, options) - has_session && security_matches?(env, options) - end - end - - def loaded_session?(session) - !session.is_a?(session_class) || session.loaded? - end - - def forced_session_update?(session, options) - force_options?(options) && session && !session.empty? - end - - def force_options?(options) - options.values_at(:renew, :drop, :defer, :expire_after).any? - end - - def security_matches?(env, options) - return true unless options[:secure] - request = Rack::Request.new(env) - request.ssl? - end - - # Acquires the session from the environment and the session id from - # the session options and passes them to #set_session. If successful - # and the :defer option is not true, a cookie will be added to the - # response with the session's id. - - def commit_session(env, status, headers, body) - session = env[ENV_SESSION_KEY] - options = session.options - - if options[:drop] || options[:renew] - session_id = destroy_session(env, session.id || generate_sid, options) - return [status, headers, body] unless session_id - end - - return [status, headers, body] unless commit_session?(env, session, options) - - session.send(:load!) unless loaded_session?(session) - session_id ||= session.id - session_data = session.to_hash.delete_if { |k,v| v.nil? } - - if not data = set_session(env, session_id, session_data, options) - env["rack.errors"].puts("Warning! #{self.class.name} failed to save session. Content dropped.") - elsif options[:defer] and not options[:renew] - env["rack.errors"].puts("Defering cookie for #{session_id}") if $VERBOSE - else - cookie = Hash.new - cookie[:value] = data - cookie[:expires] = Time.now + options[:expire_after] if options[:expire_after] - set_cookie(env, headers, cookie.merge!(options)) - end - - [status, headers, body] - end - - # Sets the cookie back to the client with session id. We skip the cookie - # setting if the value didn't change (sid is the same) or expires was given. - - def set_cookie(env, headers, cookie) - request = Rack::Request.new(env) - if request.cookies[@key] != cookie[:value] || cookie[:expires] - Utils.set_cookie_header!(headers, @key, cookie) - end - end - - # Allow subclasses to prepare_session for different Session classes - - def session_class - SessionHash - end - - # All thread safety and session retrival proceedures should occur here. - # Should return [session_id, session]. - # If nil is provided as the session id, generation of a new valid id - # should occur within. - - def get_session(env, sid) - raise '#get_session not implemented.' - end - - # All thread safety and session storage proceedures should occur here. - # Must return the session id if the session was saved successfully, or - # false if the session could not be saved. - - def set_session(env, sid, session, options) - raise '#set_session not implemented.' - end - - # All thread safety and session destroy proceedures should occur here. - # Should return a new session id or nil if options[:drop] - - def destroy_session(env, sid, options) - raise '#destroy_session not implemented' - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/cookie.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/cookie.rb deleted file mode 100644 index 5aa80cb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/cookie.rb +++ /dev/null @@ -1,178 +0,0 @@ -require 'openssl' -require 'rack/request' -require 'rack/response' -require 'rack/session/abstract/id' - -module Rack - - module Session - - # Rack::Session::Cookie provides simple cookie based session management. - # By default, the session is a Ruby Hash stored as base64 encoded marshalled - # data set to :key (default: rack.session). The object that encodes the - # session data is configurable and must respond to +encode+ and +decode+. - # Both methods must take a string and return a string. - # - # When the secret key is set, cookie data is checked for data integrity. - # The old secret key is also accepted and allows graceful secret rotation. - # - # Example: - # - # use Rack::Session::Cookie, :key => 'rack.session', - # :domain => 'foo.com', - # :path => '/', - # :expire_after => 2592000, - # :secret => 'change_me', - # :old_secret => 'also_change_me' - # - # All parameters are optional. - # - # Example of a cookie with no encoding: - # - # Rack::Session::Cookie.new(application, { - # :coder => Rack::Session::Cookie::Identity.new - # }) - # - # Example of a cookie with custom encoding: - # - # Rack::Session::Cookie.new(application, { - # :coder => Class.new { - # def encode(str); str.reverse; end - # def decode(str); str.reverse; end - # }.new - # }) - # - - class Cookie < Abstract::ID - # Encode session cookies as Base64 - class Base64 - def encode(str) - [str].pack('m') - end - - def decode(str) - str.unpack('m').first - end - - # Encode session cookies as Marshaled Base64 data - class Marshal < Base64 - def encode(str) - super(::Marshal.dump(str)) - end - - def decode(str) - return unless str - ::Marshal.load(super(str)) rescue nil - end - end - - # N.B. Unlike other encoding methods, the contained objects must be a - # valid JSON composite type, either a Hash or an Array. - class JSON < Base64 - def encode(obj) - super(::Rack::Utils::OkJson.encode(obj)) - end - - def decode(str) - return unless str - ::Rack::Utils::OkJson.decode(super(str)) rescue nil - end - end - end - - # Use no encoding for session cookies - class Identity - def encode(str); str; end - def decode(str); str; end - end - - # Reverse string encoding. (trollface) - class Reverse - def encode(str); str.reverse; end - def decode(str); str.reverse; end - end - - attr_reader :coder - - def initialize(app, options={}) - @secrets = options.values_at(:secret, :old_secret).compact - warn <<-MSG unless @secrets.size >= 1 - SECURITY WARNING: No secret option provided to Rack::Session::Cookie. - This poses a security threat. It is strongly recommended that you - provide a secret to prevent exploits that may be possible from crafted - cookies. This will not be supported in future versions of Rack, and - future versions will even invalidate your existing user cookies. - - Called from: #{caller[0]}. - MSG - @coder = options[:coder] ||= Base64::Marshal.new - super(app, options.merge!(:cookie_only => true)) - end - - private - - def get_session(env, sid) - data = unpacked_cookie_data(env) - data = persistent_session_id!(data) - [data["session_id"], data] - end - - def extract_session_id(env) - unpacked_cookie_data(env)["session_id"] - end - - def unpacked_cookie_data(env) - env["rack.session.unpacked_cookie_data"] ||= begin - request = Rack::Request.new(env) - session_data = request.cookies[@key] - - if @secrets.size > 0 && session_data - session_data, digest = session_data.split("--") - session_data = nil unless digest_match?(session_data, digest) - end - - coder.decode(session_data) || {} - end - end - - def persistent_session_id!(data, sid=nil) - data ||= {} - data["session_id"] ||= sid || generate_sid - data - end - - def set_session(env, session_id, session, options) - session = session.merge("session_id" => session_id) - session_data = coder.encode(session) - - if @secrets.first - session_data << "--#{generate_hmac(session_data, @secrets.first)}" - end - - if session_data.size > (4096 - @key.size) - env["rack.errors"].puts("Warning! Rack::Session::Cookie data size exceeds 4K.") - nil - else - session_data - end - end - - def destroy_session(env, session_id, options) - # Nothing to do here, data is in the client - generate_sid unless options[:drop] - end - - def digest_match?(data, digest) - return unless data && digest - @secrets.any? do |secret| - Rack::Utils.secure_compare(digest, generate_hmac(data, secret)) - end - end - - def generate_hmac(data, secret) - OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA1.new, secret, data) - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/memcache.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/memcache.rb deleted file mode 100644 index 53261fd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/memcache.rb +++ /dev/null @@ -1,93 +0,0 @@ -# AUTHOR: blink ; blink#ruby-lang@irc.freenode.net - -require 'rack/session/abstract/id' -require 'memcache' - -module Rack - module Session - # Rack::Session::Memcache provides simple cookie based session management. - # Session data is stored in memcached. The corresponding session key is - # maintained in the cookie. - # You may treat Session::Memcache as you would Session::Pool with the - # following caveats. - # - # * Setting :expire_after to 0 would note to the Memcache server to hang - # onto the session data until it would drop it according to it's own - # specifications. However, the cookie sent to the client would expire - # immediately. - # - # Note that memcache does drop data before it may be listed to expire. For - # a full description of behaviour, please see memcache's documentation. - - class Memcache < Abstract::ID - attr_reader :mutex, :pool - - DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge \ - :namespace => 'rack:session', - :memcache_server => 'localhost:11211' - - def initialize(app, options={}) - super - - @mutex = Mutex.new - mserv = @default_options[:memcache_server] - mopts = @default_options.reject{|k,v| !MemCache::DEFAULT_OPTIONS.include? k } - - @pool = options[:cache] || MemCache.new(mserv, mopts) - unless @pool.active? and @pool.servers.any?{|c| c.alive? } - raise 'No memcache servers' - end - end - - def generate_sid - loop do - sid = super - break sid unless @pool.get(sid, true) - end - end - - def get_session(env, sid) - with_lock(env, [nil, {}]) do - unless sid and session = @pool.get(sid) - sid, session = generate_sid, {} - unless /^STORED/ =~ @pool.add(sid, session) - raise "Session collision on '#{sid.inspect}'" - end - end - [sid, session] - end - end - - def set_session(env, session_id, new_session, options) - expiry = options[:expire_after] - expiry = expiry.nil? ? 0 : expiry + 1 - - with_lock(env, false) do - @pool.set session_id, new_session, expiry - session_id - end - end - - def destroy_session(env, session_id, options) - with_lock(env) do - @pool.delete(session_id) - generate_sid unless options[:drop] - end - end - - def with_lock(env, default=nil) - @mutex.lock if env['rack.multithread'] - yield - rescue MemCache::MemCacheError, Errno::ECONNREFUSED - if $VERBOSE - warn "#{self} is unable to find memcached server." - warn $!.inspect - end - default - ensure - @mutex.unlock if @mutex.locked? - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/pool.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/pool.rb deleted file mode 100644 index d4774fe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/session/pool.rb +++ /dev/null @@ -1,79 +0,0 @@ -# AUTHOR: blink ; blink#ruby-lang@irc.freenode.net -# THANKS: -# apeiros, for session id generation, expiry setup, and threadiness -# sergio, threadiness and bugreps - -require 'rack/session/abstract/id' -require 'thread' - -module Rack - module Session - # Rack::Session::Pool provides simple cookie based session management. - # Session data is stored in a hash held by @pool. - # In the context of a multithreaded environment, sessions being - # committed to the pool is done in a merging manner. - # - # The :drop option is available in rack.session.options if you wish to - # explicitly remove the session from the session cache. - # - # Example: - # myapp = MyRackApp.new - # sessioned = Rack::Session::Pool.new(myapp, - # :domain => 'foo.com', - # :expire_after => 2592000 - # ) - # Rack::Handler::WEBrick.run sessioned - - class Pool < Abstract::ID - attr_reader :mutex, :pool - DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge :drop => false - - def initialize(app, options={}) - super - @pool = Hash.new - @mutex = Mutex.new - end - - def generate_sid - loop do - sid = super - break sid unless @pool.key? sid - end - end - - def get_session(env, sid) - with_lock(env, [nil, {}]) do - unless sid and session = @pool[sid] - sid, session = generate_sid, {} - @pool.store sid, session - end - [sid, session] - end - end - - def set_session(env, session_id, new_session, options) - with_lock(env, false) do - @pool.store session_id, new_session - session_id - end - end - - def destroy_session(env, session_id, options) - with_lock(env) do - @pool.delete(session_id) - generate_sid unless options[:drop] - end - end - - def with_lock(env, default=nil) - @mutex.lock if env['rack.multithread'] - yield - rescue - default - ensure - @mutex.unlock if @mutex.locked? - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/showexceptions.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/showexceptions.rb deleted file mode 100644 index c91ca07..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/showexceptions.rb +++ /dev/null @@ -1,378 +0,0 @@ -require 'ostruct' -require 'erb' -require 'rack/request' -require 'rack/utils' - -module Rack - # Rack::ShowExceptions catches all exceptions raised from the app it - # wraps. It shows a useful backtrace with the sourcefile and - # clickable context, the whole Rack environment and the request - # data. - # - # Be careful when you use this on public-facing sites as it could - # reveal information helpful to attackers. - - class ShowExceptions - CONTEXT = 7 - - def initialize(app) - @app = app - @template = ERB.new(TEMPLATE) - end - - def call(env) - @app.call(env) - rescue StandardError, LoadError, SyntaxError => e - exception_string = dump_exception(e) - - env["rack.errors"].puts(exception_string) - env["rack.errors"].flush - - if prefers_plain_text?(env) - content_type = "text/plain" - body = [exception_string] - else - content_type = "text/html" - body = pretty(env, e) - end - - [500, - {"Content-Type" => content_type, - "Content-Length" => Rack::Utils.bytesize(body.join).to_s}, - body] - end - - def prefers_plain_text?(env) - env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" && (!env["HTTP_ACCEPT"] || !env["HTTP_ACCEPT"].include?("text/html")) - end - - def dump_exception(exception) - string = "#{exception.class}: #{exception.message}\n" - string << exception.backtrace.map { |l| "\t#{l}" }.join("\n") - string - end - - def pretty(env, exception) - req = Rack::Request.new(env) - - # This double assignment is to prevent an "unused variable" warning on - # Ruby 1.9.3. Yes, it is dumb, but I don't like Ruby yelling at me. - path = path = (req.script_name + req.path_info).squeeze("/") - - # This double assignment is to prevent an "unused variable" warning on - # Ruby 1.9.3. Yes, it is dumb, but I don't like Ruby yelling at me. - frames = frames = exception.backtrace.map { |line| - frame = OpenStruct.new - if line =~ /(.*?):(\d+)(:in `(.*)')?/ - frame.filename = $1 - frame.lineno = $2.to_i - frame.function = $4 - - begin - lineno = frame.lineno-1 - lines = ::File.readlines(frame.filename) - frame.pre_context_lineno = [lineno-CONTEXT, 0].max - frame.pre_context = lines[frame.pre_context_lineno...lineno] - frame.context_line = lines[lineno].chomp - frame.post_context_lineno = [lineno+CONTEXT, lines.size].min - frame.post_context = lines[lineno+1..frame.post_context_lineno] - rescue - end - - frame - else - nil - end - }.compact - - [@template.result(binding)] - end - - def h(obj) # :nodoc: - case obj - when String - Utils.escape_html(obj) - else - Utils.escape_html(obj.inspect) - end - end - - # :stopdoc: - -# adapted from Django -# Copyright (c) 2005, the Lawrence Journal-World -# Used under the modified BSD license: -# http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 -TEMPLATE = <<'HTML' - - - - - - <%=h exception.class %> at <%=h path %> - - - - - -
-

<%=h exception.class %> at <%=h path %>

-

<%=h exception.message %>

- - - - - - -
Ruby -<% if first = frames.first %> - <%=h first.filename %>: in <%=h first.function %>, line <%=h frames.first.lineno %> -<% else %> - unknown location -<% end %> -
Web<%=h req.request_method %> <%=h(req.host + path)%>
- -

Jump to:

- -
- -
-

Traceback (innermost first)

-
    -<% frames.each { |frame| %> -
  • - <%=h frame.filename %>: in <%=h frame.function %> - - <% if frame.context_line %> -
    - <% if frame.pre_context %> -
      - <% frame.pre_context.each { |line| %> -
    1. <%=h line %>
    2. - <% } %> -
    - <% end %> - -
      -
    1. <%=h frame.context_line %>...
    - - <% if frame.post_context %> -
      - <% frame.post_context.each { |line| %> -
    1. <%=h line %>
    2. - <% } %> -
    - <% end %> -
    - <% end %> -
  • -<% } %> -
-
- -
-

Request information

- -

GET

- <% if req.GET and not req.GET.empty? %> - - - - - - - - - <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %> - - - - - <% } %> - -
VariableValue
<%=h key %>
<%=h val.inspect %>
- <% else %> -

No GET data.

- <% end %> - -

POST

- <% if req.POST and not req.POST.empty? %> - - - - - - - - - <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %> - - - - - <% } %> - -
VariableValue
<%=h key %>
<%=h val.inspect %>
- <% else %> -

No POST data.

- <% end %> - - - - <% unless req.cookies.empty? %> - - - - - - - - - <% req.cookies.each { |key, val| %> - - - - - <% } %> - -
VariableValue
<%=h key %>
<%=h val.inspect %>
- <% else %> -

No cookie data.

- <% end %> - -

Rack ENV

- - - - - - - - - <% env.sort_by { |k, v| k.to_s }.each { |key, val| %> - - - - - <% } %> - -
VariableValue
<%=h key %>
<%=h val %>
- -
- -
-

- You're seeing this error because you use Rack::ShowExceptions. -

-
- - - -HTML - - # :startdoc: - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/showstatus.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/showstatus.rb deleted file mode 100644 index 5a9506f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/showstatus.rb +++ /dev/null @@ -1,113 +0,0 @@ -require 'erb' -require 'rack/request' -require 'rack/utils' - -module Rack - # Rack::ShowStatus catches all empty responses and replaces them - # with a site explaining the error. - # - # Additional details can be put into rack.showstatus.detail - # and will be shown as HTML. If such details exist, the error page - # is always rendered, even if the reply was not empty. - - class ShowStatus - def initialize(app) - @app = app - @template = ERB.new(TEMPLATE) - end - - def call(env) - status, headers, body = @app.call(env) - headers = Utils::HeaderHash.new(headers) - empty = headers['Content-Length'].to_i <= 0 - - # client or server error, or explicit message - if (status.to_i >= 400 && empty) || env["rack.showstatus.detail"] - # This double assignment is to prevent an "unused variable" warning on - # Ruby 1.9.3. Yes, it is dumb, but I don't like Ruby yelling at me. - req = req = Rack::Request.new(env) - - message = Rack::Utils::HTTP_STATUS_CODES[status.to_i] || status.to_s - - # This double assignment is to prevent an "unused variable" warning on - # Ruby 1.9.3. Yes, it is dumb, but I don't like Ruby yelling at me. - detail = detail = env["rack.showstatus.detail"] || message - - body = @template.result(binding) - size = Rack::Utils.bytesize(body) - [status, headers.merge("Content-Type" => "text/html", "Content-Length" => size.to_s), [body]] - else - [status, headers, body] - end - end - - def h(obj) # :nodoc: - case obj - when String - Utils.escape_html(obj) - else - Utils.escape_html(obj.inspect) - end - end - - # :stopdoc: - -# adapted from Django -# Copyright (c) 2005, the Lawrence Journal-World -# Used under the modified BSD license: -# http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5 -TEMPLATE = <<'HTML' - - - - - <%=h message %> at <%=h req.script_name + req.path_info %> - - - - -
-

<%=h message %> (<%= status.to_i %>)

- - - - - - - - - -
Request Method:<%=h req.request_method %>
Request URL:<%=h req.url %>
-
-
-

<%= detail %>

-
- -
-

- You're seeing this error because you use Rack::ShowStatus. -

-
- - -HTML - - # :startdoc: - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/static.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/static.rb deleted file mode 100644 index 46bc66d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/static.rb +++ /dev/null @@ -1,153 +0,0 @@ -module Rack - - # The Rack::Static middleware intercepts requests for static files - # (javascript files, images, stylesheets, etc) based on the url prefixes or - # route mappings passed in the options, and serves them using a Rack::File - # object. This allows a Rack stack to serve both static and dynamic content. - # - # Examples: - # - # Serve all requests beginning with /media from the "media" folder located - # in the current directory (ie media/*): - # - # use Rack::Static, :urls => ["/media"] - # - # Serve all requests beginning with /css or /images from the folder "public" - # in the current directory (ie public/css/* and public/images/*): - # - # use Rack::Static, :urls => ["/css", "/images"], :root => "public" - # - # Serve all requests to / with "index.html" from the folder "public" in the - # current directory (ie public/index.html): - # - # use Rack::Static, :urls => {"/" => 'index.html'}, :root => 'public' - # - # Serve all requests normally from the folder "public" in the current - # directory but uses index.html as default route for "/" - # - # use Rack::Static, :urls => [""], :root => 'public', :index => - # 'index.html' - # - # Set custom HTTP Headers for based on rules: - # - # use Rack::Static, :root => 'public', - # :header_rules => [ - # [rule, {header_field => content, header_field => content}], - # [rule, {header_field => content}] - # ] - # - # Rules for selecting files: - # - # 1) All files - # Provide the :all symbol - # :all => Matches every file - # - # 2) Folders - # Provide the folder path as a string - # '/folder' or '/folder/subfolder' => Matches files in a certain folder - # - # 3) File Extensions - # Provide the file extensions as an array - # ['css', 'js'] or %w(css js) => Matches files ending in .css or .js - # - # 4) Regular Expressions / Regexp - # Provide a regular expression - # %r{\.(?:css|js)\z} => Matches files ending in .css or .js - # /\.(?:eot|ttf|otf|woff|svg)\z/ => Matches files ending in - # the most common web font formats (.eot, .ttf, .otf, .woff, .svg) - # Note: This Regexp is available as a shortcut, using the :fonts rule - # - # 5) Font Shortcut - # Provide the :fonts symbol - # :fonts => Uses the Regexp rule stated right above to match all common web font endings - # - # Rule Ordering: - # Rules are applied in the order that they are provided. - # List rather general rules above special ones. - # - # Complete example use case including HTTP header rules: - # - # use Rack::Static, :root => 'public', - # :header_rules => [ - # # Cache all static files in public caches (e.g. Rack::Cache) - # # as well as in the browser - # [:all, {'Cache-Control' => 'public, max-age=31536000'}], - # - # # Provide web fonts with cross-origin access-control-headers - # # Firefox requires this when serving assets using a Content Delivery Network - # [:fonts, {'Access-Control-Allow-Origin' => '*'}] - # ] - # - class Static - - def initialize(app, options={}) - @app = app - @urls = options[:urls] || ["/favicon.ico"] - @index = options[:index] - root = options[:root] || Dir.pwd - - # HTTP Headers - @header_rules = options[:header_rules] || [] - # Allow for legacy :cache_control option while prioritizing global header_rules setting - @header_rules.insert(0, [:all, {'Cache-Control' => options[:cache_control]}]) if options[:cache_control] - @headers = {} - - @file_server = Rack::File.new(root, @headers) - end - - def overwrite_file_path(path) - @urls.kind_of?(Hash) && @urls.key?(path) || @index && path =~ /\/$/ - end - - def route_file(path) - @urls.kind_of?(Array) && @urls.any? { |url| path.index(url) == 0 } - end - - def can_serve(path) - route_file(path) || overwrite_file_path(path) - end - - def call(env) - path = env["PATH_INFO"] - - if can_serve(path) - env["PATH_INFO"] = (path =~ /\/$/ ? path + @index : @urls[path]) if overwrite_file_path(path) - @path = env["PATH_INFO"] - apply_header_rules - @file_server.call(env) - else - @app.call(env) - end - end - - # Convert HTTP header rules to HTTP headers - def apply_header_rules - @header_rules.each do |rule, headers| - apply_rule(rule, headers) - end - end - - def apply_rule(rule, headers) - case rule - when :all # All files - set_headers(headers) - when :fonts # Fonts Shortcut - set_headers(headers) if @path.match(/\.(?:ttf|otf|eot|woff|svg)\z/) - when String # Folder - path = ::Rack::Utils.unescape(@path) - set_headers(headers) if (path.start_with?(rule) || path.start_with?('/' + rule)) - when Array # Extension/Extensions - extensions = rule.join('|') - set_headers(headers) if @path.match(/\.(#{extensions})\z/) - when Regexp # Flexible Regexp - set_headers(headers) if @path.match(rule) - else - end - end - - def set_headers(headers) - headers.each { |field, content| @headers[field] = content } - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/urlmap.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/urlmap.rb deleted file mode 100644 index d301ce9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/urlmap.rb +++ /dev/null @@ -1,76 +0,0 @@ -module Rack - # Rack::URLMap takes a hash mapping urls or paths to apps, and - # dispatches accordingly. Support for HTTP/1.1 host names exists if - # the URLs start with http:// or https://. - # - # URLMap modifies the SCRIPT_NAME and PATH_INFO such that the part - # relevant for dispatch is in the SCRIPT_NAME, and the rest in the - # PATH_INFO. This should be taken care of when you need to - # reconstruct the URL in order to create links. - # - # URLMap dispatches in such a way that the longest paths are tried - # first, since they are most specific. - - class URLMap - NEGATIVE_INFINITY = -1.0 / 0.0 - INFINITY = 1.0 / 0.0 - - def initialize(map = {}) - remap(map) - end - - def remap(map) - @mapping = map.map { |location, app| - if location =~ %r{\Ahttps?://(.*?)(/.*)} - host, location = $1, $2 - else - host = nil - end - - unless location[0] == ?/ - raise ArgumentError, "paths need to start with /" - end - - location = location.chomp('/') - match = Regexp.new("^#{Regexp.quote(location).gsub('/', '/+')}(.*)", nil, 'n') - - [host, location, match, app] - }.sort_by do |(host, location, _, _)| - [host ? -host.size : INFINITY, -location.size] - end - end - - def call(env) - path = env["PATH_INFO"] - script_name = env['SCRIPT_NAME'] - hHost = env['HTTP_HOST'] - sName = env['SERVER_NAME'] - sPort = env['SERVER_PORT'] - - @mapping.each do |host, location, match, app| - unless hHost == host \ - || sName == host \ - || (!host && (hHost == sName || hHost == sName+':'+sPort)) - next - end - - next unless m = match.match(path.to_s) - - rest = m[1] - next unless !rest || rest.empty? || rest[0] == ?/ - - env['SCRIPT_NAME'] = (script_name + location) - env['PATH_INFO'] = rest - - return app.call(env) - end - - [404, {"Content-Type" => "text/plain", "X-Cascade" => "pass"}, ["Not Found: #{path}"]] - - ensure - env['PATH_INFO'] = path - env['SCRIPT_NAME'] = script_name - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/utils.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/utils.rb deleted file mode 100644 index 561e46e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/utils.rb +++ /dev/null @@ -1,628 +0,0 @@ -# -*- encoding: binary -*- -require 'fileutils' -require 'set' -require 'tempfile' -require 'rack/multipart' -require 'time' - -major, minor, patch = RUBY_VERSION.split('.').map { |v| v.to_i } - -if major == 1 && minor < 9 - require 'rack/backports/uri/common_18' -elsif major == 1 && minor == 9 && patch == 2 && RUBY_PATCHLEVEL <= 320 && RUBY_ENGINE != 'jruby' - require 'rack/backports/uri/common_192' -elsif major == 1 && minor == 9 && patch == 3 && RUBY_PATCHLEVEL < 125 - require 'rack/backports/uri/common_193' -else - require 'uri/common' -end - -module Rack - # Rack::Utils contains a grab-bag of useful methods for writing web - # applications adopted from all kinds of Ruby libraries. - - module Utils - # URI escapes. (CGI style space to +) - def escape(s) - URI.encode_www_form_component(s) - end - module_function :escape - - # Like URI escaping, but with %20 instead of +. Strictly speaking this is - # true URI escaping. - def escape_path(s) - escape(s).gsub('+', '%20') - end - module_function :escape_path - - # Unescapes a URI escaped string with +encoding+. +encoding+ will be the - # target encoding of the string returned, and it defaults to UTF-8 - if defined?(::Encoding) - def unescape(s, encoding = Encoding::UTF_8) - URI.decode_www_form_component(s, encoding) - end - else - def unescape(s, encoding = nil) - URI.decode_www_form_component(s, encoding) - end - end - module_function :unescape - - DEFAULT_SEP = /[&;] */n - - class << self - attr_accessor :key_space_limit - end - - # The default number of bytes to allow parameter keys to take up. - # This helps prevent a rogue client from flooding a Request. - self.key_space_limit = 65536 - - # Stolen from Mongrel, with some small modifications: - # Parses a query string by breaking it up at the '&' - # and ';' characters. You can also use this to parse - # cookies by changing the characters used in the second - # parameter (which defaults to '&;'). - def parse_query(qs, d = nil, &unescaper) - unescaper ||= method(:unescape) - - params = KeySpaceConstrainedParams.new - - (qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p| - next if p.empty? - k, v = p.split('=', 2).map(&unescaper) - - if cur = params[k] - if cur.class == Array - params[k] << v - else - params[k] = [cur, v] - end - else - params[k] = v - end - end - - return params.to_params_hash - end - module_function :parse_query - - def parse_nested_query(qs, d = nil) - params = KeySpaceConstrainedParams.new - - (qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p| - k, v = p.split('=', 2).map { |s| unescape(s) } - - normalize_params(params, k, v) - end - - return params.to_params_hash - end - module_function :parse_nested_query - - def normalize_params(params, name, v = nil) - name =~ %r(\A[\[\]]*([^\[\]]+)\]*) - k = $1 || '' - after = $' || '' - - return if k.empty? - - if after == "" - params[k] = v - elsif after == "[]" - params[k] ||= [] - raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array) - params[k] << v - elsif after =~ %r(^\[\]\[([^\[\]]+)\]$) || after =~ %r(^\[\](.+)$) - child_key = $1 - params[k] ||= [] - raise TypeError, "expected Array (got #{params[k].class.name}) for param `#{k}'" unless params[k].is_a?(Array) - if params_hash_type?(params[k].last) && !params[k].last.key?(child_key) - normalize_params(params[k].last, child_key, v) - else - params[k] << normalize_params(params.class.new, child_key, v) - end - else - params[k] ||= params.class.new - raise TypeError, "expected Hash (got #{params[k].class.name}) for param `#{k}'" unless params_hash_type?(params[k]) - params[k] = normalize_params(params[k], after, v) - end - - return params - end - module_function :normalize_params - - def params_hash_type?(obj) - obj.kind_of?(KeySpaceConstrainedParams) || obj.kind_of?(Hash) - end - module_function :params_hash_type? - - def build_query(params) - params.map { |k, v| - if v.class == Array - build_query(v.map { |x| [k, x] }) - else - v.nil? ? escape(k) : "#{escape(k)}=#{escape(v)}" - end - }.join("&") - end - module_function :build_query - - def build_nested_query(value, prefix = nil) - case value - when Array - value.map { |v| - build_nested_query(v, "#{prefix}[]") - }.join("&") - when Hash - value.map { |k, v| - build_nested_query(v, prefix ? "#{prefix}[#{escape(k)}]" : escape(k)) - }.join("&") - when String - raise ArgumentError, "value must be a Hash" if prefix.nil? - "#{prefix}=#{escape(value)}" - else - prefix - end - end - module_function :build_nested_query - - def q_values(q_value_header) - q_value_header.to_s.split(/\s*,\s*/).map do |part| - value, parameters = part.split(/\s*;\s*/, 2) - quality = 1.0 - if md = /\Aq=([\d.]+)/.match(parameters) - quality = md[1].to_f - end - [value, quality] - end - end - module_function :q_values - - def best_q_match(q_value_header, available_mimes) - values = q_values(q_value_header) - - values.map do |req_mime, quality| - match = available_mimes.first { |am| Rack::Mime.match?(am, req_mime) } - next unless match - [match, quality] - end.compact.sort_by do |match, quality| - (match.split('/', 2).count('*') * -10) + quality - end.last.first - end - module_function :best_q_match - - ESCAPE_HTML = { - "&" => "&", - "<" => "<", - ">" => ">", - "'" => "'", - '"' => """, - "/" => "/" - } - if //.respond_to?(:encoding) - ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys) - else - # On 1.8, there is a kcode = 'u' bug that allows for XSS otherwhise - # TODO doesn't apply to jruby, so a better condition above might be preferable? - ESCAPE_HTML_PATTERN = /#{Regexp.union(*ESCAPE_HTML.keys)}/n - end - - # Escape ampersands, brackets and quotes to their HTML/XML entities. - def escape_html(string) - string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] } - end - module_function :escape_html - - def select_best_encoding(available_encodings, accept_encoding) - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html - - expanded_accept_encoding = - accept_encoding.map { |m, q| - if m == "*" - (available_encodings - accept_encoding.map { |m2, _| m2 }).map { |m2| [m2, q] } - else - [[m, q]] - end - }.inject([]) { |mem, list| - mem + list - } - - encoding_candidates = expanded_accept_encoding.sort_by { |_, q| -q }.map { |m, _| m } - - unless encoding_candidates.include?("identity") - encoding_candidates.push("identity") - end - - expanded_accept_encoding.find_all { |m, q| - q == 0.0 - }.each { |m, _| - encoding_candidates.delete(m) - } - - return (encoding_candidates & available_encodings)[0] - end - module_function :select_best_encoding - - def set_cookie_header!(header, key, value) - case value - when Hash - domain = "; domain=" + value[:domain] if value[:domain] - path = "; path=" + value[:path] if value[:path] - max_age = "; max-age=" + value[:max_age] if value[:max_age] - # There is an RFC mess in the area of date formatting for Cookies. Not - # only are there contradicting RFCs and examples within RFC text, but - # there are also numerous conflicting names of fields and partially - # cross-applicable specifications. - # - # These are best described in RFC 2616 3.3.1. This RFC text also - # specifies that RFC 822 as updated by RFC 1123 is preferred. That is a - # fixed length format with space-date delimeted fields. - # - # See also RFC 1123 section 5.2.14. - # - # RFC 6265 also specifies "sane-cookie-date" as RFC 1123 date, defined - # in RFC 2616 3.3.1. RFC 6265 also gives examples that clearly denote - # the space delimited format. These formats are compliant with RFC 2822. - # - # For reference, all involved RFCs are: - # RFC 822 - # RFC 1123 - # RFC 2109 - # RFC 2616 - # RFC 2822 - # RFC 2965 - # RFC 6265 - expires = "; expires=" + - rfc2822(value[:expires].clone.gmtime) if value[:expires] - secure = "; secure" if value[:secure] - httponly = "; HttpOnly" if value[:httponly] - value = value[:value] - end - value = [value] unless Array === value - cookie = escape(key) + "=" + - value.map { |v| escape v }.join("&") + - "#{domain}#{path}#{max_age}#{expires}#{secure}#{httponly}" - - case header["Set-Cookie"] - when nil, '' - header["Set-Cookie"] = cookie - when String - header["Set-Cookie"] = [header["Set-Cookie"], cookie].join("\n") - when Array - header["Set-Cookie"] = (header["Set-Cookie"] + [cookie]).join("\n") - end - - nil - end - module_function :set_cookie_header! - - def delete_cookie_header!(header, key, value = {}) - case header["Set-Cookie"] - when nil, '' - cookies = [] - when String - cookies = header["Set-Cookie"].split("\n") - when Array - cookies = header["Set-Cookie"] - end - - cookies.reject! { |cookie| - if value[:domain] - cookie =~ /\A#{escape(key)}=.*domain=#{value[:domain]}/ - elsif value[:path] - cookie =~ /\A#{escape(key)}=.*path=#{value[:path]}/ - else - cookie =~ /\A#{escape(key)}=/ - end - } - - header["Set-Cookie"] = cookies.join("\n") - - set_cookie_header!(header, key, - {:value => '', :path => nil, :domain => nil, - :max_age => '0', - :expires => Time.at(0) }.merge(value)) - - nil - end - module_function :delete_cookie_header! - - # Return the bytesize of String; uses String#size under Ruby 1.8 and - # String#bytesize under 1.9. - if ''.respond_to?(:bytesize) - def bytesize(string) - string.bytesize - end - else - def bytesize(string) - string.size - end - end - module_function :bytesize - - def rfc2822(time) - time.rfc2822 - end - module_function :rfc2822 - - # Modified version of stdlib time.rb Time#rfc2822 to use '%d-%b-%Y' instead - # of '% %b %Y'. - # It assumes that the time is in GMT to comply to the RFC 2109. - # - # NOTE: I'm not sure the RFC says it requires GMT, but is ambigous enough - # that I'm certain someone implemented only that option. - # Do not use %a and %b from Time.strptime, it would use localized names for - # weekday and month. - # - def rfc2109(time) - wday = Time::RFC2822_DAY_NAME[time.wday] - mon = Time::RFC2822_MONTH_NAME[time.mon - 1] - time.strftime("#{wday}, %d-#{mon}-%Y %H:%M:%S GMT") - end - module_function :rfc2109 - - # Parses the "Range:" header, if present, into an array of Range objects. - # Returns nil if the header is missing or syntactically invalid. - # Returns an empty array if none of the ranges are satisfiable. - def byte_ranges(env, size) - # See - http_range = env['HTTP_RANGE'] - return nil unless http_range && http_range =~ /bytes=([^;]+)/ - ranges = [] - $1.split(/,\s*/).each do |range_spec| - return nil unless range_spec =~ /(\d*)-(\d*)/ - r0,r1 = $1, $2 - if r0.empty? - return nil if r1.empty? - # suffix-byte-range-spec, represents trailing suffix of file - r0 = size - r1.to_i - r0 = 0 if r0 < 0 - r1 = size - 1 - else - r0 = r0.to_i - if r1.empty? - r1 = size - 1 - else - r1 = r1.to_i - return nil if r1 < r0 # backwards range is syntactically invalid - r1 = size-1 if r1 >= size - end - end - ranges << (r0..r1) if r0 <= r1 - end - ranges - end - module_function :byte_ranges - - # Constant time string comparison. - def secure_compare(a, b) - return false unless bytesize(a) == bytesize(b) - - l = a.unpack("C*") - - r, i = 0, -1 - b.each_byte { |v| r |= v ^ l[i+=1] } - r == 0 - end - module_function :secure_compare - - # Context allows the use of a compatible middleware at different points - # in a request handling stack. A compatible middleware must define - # #context which should take the arguments env and app. The first of which - # would be the request environment. The second of which would be the rack - # application that the request would be forwarded to. - class Context - attr_reader :for, :app - - def initialize(app_f, app_r) - raise 'running context does not respond to #context' unless app_f.respond_to? :context - @for, @app = app_f, app_r - end - - def call(env) - @for.context(env, @app) - end - - def recontext(app) - self.class.new(@for, app) - end - - def context(env, app=@app) - recontext(app).call(env) - end - end - - # A case-insensitive Hash that preserves the original case of a - # header when set. - class HeaderHash < Hash - def self.new(hash={}) - HeaderHash === hash ? hash : super(hash) - end - - def initialize(hash={}) - super() - @names = {} - hash.each { |k, v| self[k] = v } - end - - def each - super do |k, v| - yield(k, v.respond_to?(:to_ary) ? v.to_ary.join("\n") : v) - end - end - - def to_hash - hash = {} - each { |k,v| hash[k] = v } - hash - end - - def [](k) - super(k) || super(@names[k.downcase]) - end - - def []=(k, v) - canonical = k.downcase - delete k if @names[canonical] && @names[canonical] != k # .delete is expensive, don't invoke it unless necessary - @names[k] = @names[canonical] = k - super k, v - end - - def delete(k) - canonical = k.downcase - result = super @names.delete(canonical) - @names.delete_if { |name,| name.downcase == canonical } - result - end - - def include?(k) - @names.include?(k) || @names.include?(k.downcase) - end - - alias_method :has_key?, :include? - alias_method :member?, :include? - alias_method :key?, :include? - - def merge!(other) - other.each { |k, v| self[k] = v } - self - end - - def merge(other) - hash = dup - hash.merge! other - end - - def replace(other) - clear - other.each { |k, v| self[k] = v } - self - end - end - - class KeySpaceConstrainedParams - def initialize(limit = Utils.key_space_limit) - @limit = limit - @size = 0 - @params = {} - end - - def [](key) - @params[key] - end - - def []=(key, value) - @size += key.size if key && !@params.key?(key) - raise RangeError, 'exceeded available parameter key space' if @size > @limit - @params[key] = value - end - - def key?(key) - @params.key?(key) - end - - def to_params_hash - hash = @params - hash.keys.each do |key| - value = hash[key] - if value.kind_of?(self.class) - hash[key] = value.to_params_hash - elsif value.kind_of?(Array) - value.map! {|x| x.kind_of?(self.class) ? x.to_params_hash : x} - end - end - hash - end - end - - # Every standard HTTP code mapped to the appropriate message. - # Generated with: - # irb -ropen-uri -rnokogiri - # > Nokogiri::XML(open("http://www.iana.org/assignments/http-status-codes/http-status-codes.xml")).css("record").each{|r| - # puts "#{r.css('value').text} => '#{r.css('description').text}'"} - HTTP_STATUS_CODES = { - 100 => 'Continue', - 101 => 'Switching Protocols', - 102 => 'Processing', - 200 => 'OK', - 201 => 'Created', - 202 => 'Accepted', - 203 => 'Non-Authoritative Information', - 204 => 'No Content', - 205 => 'Reset Content', - 206 => 'Partial Content', - 207 => 'Multi-Status', - 208 => 'Already Reported', - 226 => 'IM Used', - 300 => 'Multiple Choices', - 301 => 'Moved Permanently', - 302 => 'Found', - 303 => 'See Other', - 304 => 'Not Modified', - 305 => 'Use Proxy', - 306 => 'Reserved', - 307 => 'Temporary Redirect', - 308 => 'Permanent Redirect', - 400 => 'Bad Request', - 401 => 'Unauthorized', - 402 => 'Payment Required', - 403 => 'Forbidden', - 404 => 'Not Found', - 405 => 'Method Not Allowed', - 406 => 'Not Acceptable', - 407 => 'Proxy Authentication Required', - 408 => 'Request Timeout', - 409 => 'Conflict', - 410 => 'Gone', - 411 => 'Length Required', - 412 => 'Precondition Failed', - 413 => 'Request Entity Too Large', - 414 => 'Request-URI Too Long', - 415 => 'Unsupported Media Type', - 416 => 'Requested Range Not Satisfiable', - 417 => 'Expectation Failed', - 422 => 'Unprocessable Entity', - 423 => 'Locked', - 424 => 'Failed Dependency', - 425 => 'Reserved for WebDAV advanced collections expired proposal', - 426 => 'Upgrade Required', - 427 => 'Unassigned', - 428 => 'Precondition Required', - 429 => 'Too Many Requests', - 430 => 'Unassigned', - 431 => 'Request Header Fields Too Large', - 500 => 'Internal Server Error', - 501 => 'Not Implemented', - 502 => 'Bad Gateway', - 503 => 'Service Unavailable', - 504 => 'Gateway Timeout', - 505 => 'HTTP Version Not Supported', - 506 => 'Variant Also Negotiates (Experimental)', - 507 => 'Insufficient Storage', - 508 => 'Loop Detected', - 509 => 'Unassigned', - 510 => 'Not Extended', - 511 => 'Network Authentication Required' - } - - # Responses with HTTP status codes that should not have an entity body - STATUS_WITH_NO_ENTITY_BODY = Set.new((100..199).to_a << 204 << 205 << 304) - - SYMBOL_TO_STATUS_CODE = Hash[*HTTP_STATUS_CODES.map { |code, message| - [message.downcase.gsub(/\s|-/, '_').to_sym, code] - }.flatten] - - def status_code(status) - if status.is_a?(Symbol) - SYMBOL_TO_STATUS_CODE[status] || 500 - else - status.to_i - end - end - module_function :status_code - - Multipart = Rack::Multipart - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/utils/okjson.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/utils/okjson.rb deleted file mode 100644 index dcf80e5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/lib/rack/utils/okjson.rb +++ /dev/null @@ -1,599 +0,0 @@ -# encoding: UTF-8 -# -# Copyright 2011, 2012 Keith Rarick -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. - -# See https://github.com/kr/okjson for updates. -# Imported from the above repo @ d4e8643ad92e14b37d11326855499c7e4108ed17 -# Namespace modified for vendoring under Rack::Utils - -require 'stringio' - -# Some parts adapted from -# http://golang.org/src/pkg/json/decode.go and -# http://golang.org/src/pkg/utf8/utf8.go -module Rack::Utils::OkJson - Upstream = 'LTD7LBKLZWFF7OZK' - extend self - - - # Decodes a json document in string s and - # returns the corresponding ruby value. - # String s must be valid UTF-8. If you have - # a string in some other encoding, convert - # it first. - # - # String values in the resulting structure - # will be UTF-8. - def decode(s) - ts = lex(s) - v, ts = textparse(ts) - if ts.length > 0 - raise Error, 'trailing garbage' - end - v - end - - - # Parses a "json text" in the sense of RFC 4627. - # Returns the parsed value and any trailing tokens. - # Note: this is almost the same as valparse, - # except that it does not accept atomic values. - def textparse(ts) - if ts.length < 0 - raise Error, 'empty' - end - - typ, _, val = ts[0] - case typ - when '{' then objparse(ts) - when '[' then arrparse(ts) - else - raise Error, "unexpected #{val.inspect}" - end - end - - - # Parses a "value" in the sense of RFC 4627. - # Returns the parsed value and any trailing tokens. - def valparse(ts) - if ts.length < 0 - raise Error, 'empty' - end - - typ, _, val = ts[0] - case typ - when '{' then objparse(ts) - when '[' then arrparse(ts) - when :val,:str then [val, ts[1..-1]] - else - raise Error, "unexpected #{val.inspect}" - end - end - - - # Parses an "object" in the sense of RFC 4627. - # Returns the parsed value and any trailing tokens. - def objparse(ts) - ts = eat('{', ts) - obj = {} - - if ts[0][0] == '}' - return obj, ts[1..-1] - end - - k, v, ts = pairparse(ts) - obj[k] = v - - if ts[0][0] == '}' - return obj, ts[1..-1] - end - - loop do - ts = eat(',', ts) - - k, v, ts = pairparse(ts) - obj[k] = v - - if ts[0][0] == '}' - return obj, ts[1..-1] - end - end - end - - - # Parses a "member" in the sense of RFC 4627. - # Returns the parsed values and any trailing tokens. - def pairparse(ts) - (typ, _, k), ts = ts[0], ts[1..-1] - if typ != :str - raise Error, "unexpected #{k.inspect}" - end - ts = eat(':', ts) - v, ts = valparse(ts) - [k, v, ts] - end - - - # Parses an "array" in the sense of RFC 4627. - # Returns the parsed value and any trailing tokens. - def arrparse(ts) - ts = eat('[', ts) - arr = [] - - if ts[0][0] == ']' - return arr, ts[1..-1] - end - - v, ts = valparse(ts) - arr << v - - if ts[0][0] == ']' - return arr, ts[1..-1] - end - - loop do - ts = eat(',', ts) - - v, ts = valparse(ts) - arr << v - - if ts[0][0] == ']' - return arr, ts[1..-1] - end - end - end - - - def eat(typ, ts) - if ts[0][0] != typ - raise Error, "expected #{typ} (got #{ts[0].inspect})" - end - ts[1..-1] - end - - - # Scans s and returns a list of json tokens, - # excluding white space (as defined in RFC 4627). - def lex(s) - ts = [] - while s.length > 0 - typ, lexeme, val = tok(s) - if typ == nil - raise Error, "invalid character at #{s[0,10].inspect}" - end - if typ != :space - ts << [typ, lexeme, val] - end - s = s[lexeme.length..-1] - end - ts - end - - - # Scans the first token in s and - # returns a 3-element list, or nil - # if s does not begin with a valid token. - # - # The first list element is one of - # '{', '}', ':', ',', '[', ']', - # :val, :str, and :space. - # - # The second element is the lexeme. - # - # The third element is the value of the - # token for :val and :str, otherwise - # it is the lexeme. - def tok(s) - case s[0] - when ?{ then ['{', s[0,1], s[0,1]] - when ?} then ['}', s[0,1], s[0,1]] - when ?: then [':', s[0,1], s[0,1]] - when ?, then [',', s[0,1], s[0,1]] - when ?[ then ['[', s[0,1], s[0,1]] - when ?] then [']', s[0,1], s[0,1]] - when ?n then nulltok(s) - when ?t then truetok(s) - when ?f then falsetok(s) - when ?" then strtok(s) - when Spc then [:space, s[0,1], s[0,1]] - when ?\t then [:space, s[0,1], s[0,1]] - when ?\n then [:space, s[0,1], s[0,1]] - when ?\r then [:space, s[0,1], s[0,1]] - else numtok(s) - end - end - - - def nulltok(s); s[0,4] == 'null' ? [:val, 'null', nil] : [] end - def truetok(s); s[0,4] == 'true' ? [:val, 'true', true] : [] end - def falsetok(s); s[0,5] == 'false' ? [:val, 'false', false] : [] end - - - def numtok(s) - m = /-?([1-9][0-9]+|[0-9])([.][0-9]+)?([eE][+-]?[0-9]+)?/.match(s) - if m && m.begin(0) == 0 - if m[3] && !m[2] - [:val, m[0], Integer(m[1])*(10**Integer(m[3][1..-1]))] - elsif m[2] - [:val, m[0], Float(m[0])] - else - [:val, m[0], Integer(m[0])] - end - else - [] - end - end - - - def strtok(s) - m = /"([^"\\]|\\["\/\\bfnrt]|\\u[0-9a-fA-F]{4})*"/.match(s) - if ! m - raise Error, "invalid string literal at #{abbrev(s)}" - end - [:str, m[0], unquote(m[0])] - end - - - def abbrev(s) - t = s[0,10] - p = t['`'] - t = t[0,p] if p - t = t + '...' if t.length < s.length - '`' + t + '`' - end - - - # Converts a quoted json string literal q into a UTF-8-encoded string. - # The rules are different than for Ruby, so we cannot use eval. - # Unquote will raise an error if q contains control characters. - def unquote(q) - q = q[1...-1] - a = q.dup # allocate a big enough string - rubydoesenc = false - # In ruby >= 1.9, a[w] is a codepoint, not a byte. - if a.class.method_defined?(:force_encoding) - a.force_encoding('UTF-8') - rubydoesenc = true - end - r, w = 0, 0 - while r < q.length - c = q[r] - case true - when c == ?\\ - r += 1 - if r >= q.length - raise Error, "string literal ends with a \"\\\": \"#{q}\"" - end - - case q[r] - when ?",?\\,?/,?' - a[w] = q[r] - r += 1 - w += 1 - when ?b,?f,?n,?r,?t - a[w] = Unesc[q[r]] - r += 1 - w += 1 - when ?u - r += 1 - uchar = begin - hexdec4(q[r,4]) - rescue RuntimeError => e - raise Error, "invalid escape sequence \\u#{q[r,4]}: #{e}" - end - r += 4 - if surrogate? uchar - if q.length >= r+6 - uchar1 = hexdec4(q[r+2,4]) - uchar = subst(uchar, uchar1) - if uchar != Ucharerr - # A valid pair; consume. - r += 6 - end - end - end - if rubydoesenc - a[w] = '' << uchar - w += 1 - else - w += ucharenc(a, w, uchar) - end - else - raise Error, "invalid escape char #{q[r]} in \"#{q}\"" - end - when c == ?", c < Spc - raise Error, "invalid character in string literal \"#{q}\"" - else - # Copy anything else byte-for-byte. - # Valid UTF-8 will remain valid UTF-8. - # Invalid UTF-8 will remain invalid UTF-8. - # In ruby >= 1.9, c is a codepoint, not a byte, - # in which case this is still what we want. - a[w] = c - r += 1 - w += 1 - end - end - a[0,w] - end - - - # Encodes unicode character u as UTF-8 - # bytes in string a at position i. - # Returns the number of bytes written. - def ucharenc(a, i, u) - case true - when u <= Uchar1max - a[i] = (u & 0xff).chr - 1 - when u <= Uchar2max - a[i+0] = (Utag2 | ((u>>6)&0xff)).chr - a[i+1] = (Utagx | (u&Umaskx)).chr - 2 - when u <= Uchar3max - a[i+0] = (Utag3 | ((u>>12)&0xff)).chr - a[i+1] = (Utagx | ((u>>6)&Umaskx)).chr - a[i+2] = (Utagx | (u&Umaskx)).chr - 3 - else - a[i+0] = (Utag4 | ((u>>18)&0xff)).chr - a[i+1] = (Utagx | ((u>>12)&Umaskx)).chr - a[i+2] = (Utagx | ((u>>6)&Umaskx)).chr - a[i+3] = (Utagx | (u&Umaskx)).chr - 4 - end - end - - - def hexdec4(s) - if s.length != 4 - raise Error, 'short' - end - (nibble(s[0])<<12) | (nibble(s[1])<<8) | (nibble(s[2])<<4) | nibble(s[3]) - end - - - def subst(u1, u2) - if Usurr1 <= u1 && u1 < Usurr2 && Usurr2 <= u2 && u2 < Usurr3 - return ((u1-Usurr1)<<10) | (u2-Usurr2) + Usurrself - end - return Ucharerr - end - - - def surrogate?(u) - Usurr1 <= u && u < Usurr3 - end - - - def nibble(c) - case true - when ?0 <= c && c <= ?9 then c.ord - ?0.ord - when ?a <= c && c <= ?z then c.ord - ?a.ord + 10 - when ?A <= c && c <= ?Z then c.ord - ?A.ord + 10 - else - raise Error, "invalid hex code #{c}" - end - end - - - # Encodes x into a json text. It may contain only - # Array, Hash, String, Numeric, true, false, nil. - # (Note, this list excludes Symbol.) - # X itself must be an Array or a Hash. - # No other value can be encoded, and an error will - # be raised if x contains any other value, such as - # Nan, Infinity, Symbol, and Proc, or if a Hash key - # is not a String. - # Strings contained in x must be valid UTF-8. - def encode(x) - case x - when Hash then objenc(x) - when Array then arrenc(x) - else - raise Error, 'root value must be an Array or a Hash' - end - end - - - def valenc(x) - case x - when Hash then objenc(x) - when Array then arrenc(x) - when String then strenc(x) - when Numeric then numenc(x) - when true then "true" - when false then "false" - when nil then "null" - else - raise Error, "cannot encode #{x.class}: #{x.inspect}" - end - end - - - def objenc(x) - '{' + x.map{|k,v| keyenc(k) + ':' + valenc(v)}.join(',') + '}' - end - - - def arrenc(a) - '[' + a.map{|x| valenc(x)}.join(',') + ']' - end - - - def keyenc(k) - case k - when String then strenc(k) - else - raise Error, "Hash key is not a string: #{k.inspect}" - end - end - - - def strenc(s) - t = StringIO.new - t.putc(?") - r = 0 - - # In ruby >= 1.9, s[r] is a codepoint, not a byte. - rubydoesenc = s.class.method_defined?(:encoding) - - while r < s.length - case s[r] - when ?" then t.print('\\"') - when ?\\ then t.print('\\\\') - when ?\b then t.print('\\b') - when ?\f then t.print('\\f') - when ?\n then t.print('\\n') - when ?\r then t.print('\\r') - when ?\t then t.print('\\t') - else - c = s[r] - case true - when rubydoesenc - begin - c.ord # will raise an error if c is invalid UTF-8 - t.write(c) - rescue - t.write(Ustrerr) - end - when Spc <= c && c <= ?~ - t.putc(c) - else - n = ucharcopy(t, s, r) # ensure valid UTF-8 output - r += n - 1 # r is incremented below - end - end - r += 1 - end - t.putc(?") - t.string - end - - - def numenc(x) - if ((x.nan? || x.infinite?) rescue false) - raise Error, "Numeric cannot be represented: #{x}" - end - "#{x}" - end - - - # Copies the valid UTF-8 bytes of a single character - # from string s at position i to I/O object t, and - # returns the number of bytes copied. - # If no valid UTF-8 char exists at position i, - # ucharcopy writes Ustrerr and returns 1. - def ucharcopy(t, s, i) - n = s.length - i - raise Utf8Error if n < 1 - - c0 = s[i].ord - - # 1-byte, 7-bit sequence? - if c0 < Utagx - t.putc(c0) - return 1 - end - - raise Utf8Error if c0 < Utag2 # unexpected continuation byte? - - raise Utf8Error if n < 2 # need continuation byte - c1 = s[i+1].ord - raise Utf8Error if c1 < Utagx || Utag2 <= c1 - - # 2-byte, 11-bit sequence? - if c0 < Utag3 - raise Utf8Error if ((c0&Umask2)<<6 | (c1&Umaskx)) <= Uchar1max - t.putc(c0) - t.putc(c1) - return 2 - end - - # need second continuation byte - raise Utf8Error if n < 3 - - c2 = s[i+2].ord - raise Utf8Error if c2 < Utagx || Utag2 <= c2 - - # 3-byte, 16-bit sequence? - if c0 < Utag4 - u = (c0&Umask3)<<12 | (c1&Umaskx)<<6 | (c2&Umaskx) - raise Utf8Error if u <= Uchar2max - t.putc(c0) - t.putc(c1) - t.putc(c2) - return 3 - end - - # need third continuation byte - raise Utf8Error if n < 4 - c3 = s[i+3].ord - raise Utf8Error if c3 < Utagx || Utag2 <= c3 - - # 4-byte, 21-bit sequence? - if c0 < Utag5 - u = (c0&Umask4)<<18 | (c1&Umaskx)<<12 | (c2&Umaskx)<<6 | (c3&Umaskx) - raise Utf8Error if u <= Uchar3max - t.putc(c0) - t.putc(c1) - t.putc(c2) - t.putc(c3) - return 4 - end - - raise Utf8Error - rescue Utf8Error - t.write(Ustrerr) - return 1 - end - - - class Utf8Error < ::StandardError - end - - - class Error < ::StandardError - end - - - Utagx = 0x80 # 1000 0000 - Utag2 = 0xc0 # 1100 0000 - Utag3 = 0xe0 # 1110 0000 - Utag4 = 0xf0 # 1111 0000 - Utag5 = 0xF8 # 1111 1000 - Umaskx = 0x3f # 0011 1111 - Umask2 = 0x1f # 0001 1111 - Umask3 = 0x0f # 0000 1111 - Umask4 = 0x07 # 0000 0111 - Uchar1max = (1<<7) - 1 - Uchar2max = (1<<11) - 1 - Uchar3max = (1<<16) - 1 - Ucharerr = 0xFFFD # unicode "replacement char" - Ustrerr = "\xef\xbf\xbd" # unicode "replacement char" - Usurrself = 0x10000 - Usurr1 = 0xd800 - Usurr2 = 0xdc00 - Usurr3 = 0xe000 - - Spc = ' '[0] - Unesc = {?b=>?\b, ?f=>?\f, ?n=>?\n, ?r=>?\r, ?t=>?\t} -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/rack.gemspec b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/rack.gemspec deleted file mode 100644 index 388d6ed..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/rack.gemspec +++ /dev/null @@ -1,33 +0,0 @@ -Gem::Specification.new do |s| - s.name = "rack" - s.version = "1.5.2" - s.platform = Gem::Platform::RUBY - s.summary = "a modular Ruby webserver interface" - s.license = "MIT" - - s.description = <<-EOF -Rack provides a minimal, modular and adaptable interface for developing -web applications in Ruby. By wrapping HTTP requests and responses in -the simplest way possible, it unifies and distills the API for web -servers, web frameworks, and software in between (the so-called -middleware) into a single method call. - -Also see http://rack.github.com/. -EOF - - s.files = Dir['{bin/*,contrib/*,example/*,lib/**/*,test/**/*}'] + - %w(COPYING KNOWN-ISSUES rack.gemspec Rakefile README.rdoc SPEC) - s.bindir = 'bin' - s.executables << 'rackup' - s.require_path = 'lib' - s.extra_rdoc_files = ['README.rdoc', 'KNOWN-ISSUES'] - s.test_files = Dir['test/spec_*.rb'] - - s.author = 'Christian Neukirchen' - s.email = 'chneukirchen@gmail.com' - s.homepage = 'http://rack.github.com/' - s.rubyforge_project = 'rack' - - s.add_development_dependency 'bacon' - s.add_development_dependency 'rake' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/anything.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/anything.rb deleted file mode 100644 index c07f82c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/anything.rb +++ /dev/null @@ -1,5 +0,0 @@ -class Anything - def self.call(env) - [200, {'Content-Type' => 'text/plain'}, ['OK']] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/comment.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/comment.ru deleted file mode 100644 index 0722f0a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/comment.ru +++ /dev/null @@ -1,4 +0,0 @@ -=begin - -=end -run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] } diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/end.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/end.ru deleted file mode 100644 index 7f36d8c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/end.ru +++ /dev/null @@ -1,5 +0,0 @@ -run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] } -__END__ -Should not be evaluated -Neither should -This diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/line.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/line.ru deleted file mode 100644 index f4c84ad..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/line.ru +++ /dev/null @@ -1 +0,0 @@ -run lambda{ |env| [200, {'Content-Type' => 'text/plain'}, [__LINE__.to_s]] } diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/options.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/options.ru deleted file mode 100644 index 8562da6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/builder/options.ru +++ /dev/null @@ -1,2 +0,0 @@ -#\ -d -run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] } diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/folder/test.js b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/folder/test.js deleted file mode 100644 index 6874e45..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/folder/test.js +++ /dev/null @@ -1 +0,0 @@ -### TestFile ### diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/fonts/font.eot b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/fonts/font.eot deleted file mode 100644 index 6874e45..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/fonts/font.eot +++ /dev/null @@ -1 +0,0 @@ -### TestFile ### diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/images/image.png b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/images/image.png deleted file mode 100644 index 6874e45..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/images/image.png +++ /dev/null @@ -1 +0,0 @@ -### TestFile ### diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/index.html b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/index.html deleted file mode 100644 index 6874e45..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/index.html +++ /dev/null @@ -1 +0,0 @@ -### TestFile ### diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/javascripts/app.js b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/javascripts/app.js deleted file mode 100644 index 6874e45..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/javascripts/app.js +++ /dev/null @@ -1 +0,0 @@ -### TestFile ### diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/stylesheets/app.css b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/stylesheets/app.css deleted file mode 100644 index 6874e45..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/assets/stylesheets/app.css +++ /dev/null @@ -1 +0,0 @@ -### TestFile ### diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/lighttpd.conf b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/lighttpd.conf deleted file mode 100755 index c195f78..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/lighttpd.conf +++ /dev/null @@ -1,26 +0,0 @@ -server.modules = ("mod_fastcgi", "mod_cgi") -server.document-root = "." -server.errorlog = var.CWD + "/lighttpd.errors" -server.port = 9203 -server.bind = "127.0.0.1" - -server.event-handler = "select" - -cgi.assign = ("/test" => "", -# ".ru" => "" - ) - -fastcgi.server = ( - "test.fcgi" => ("localhost" => - ("min-procs" => 1, - "socket" => "/tmp/rack-test-fcgi", - "bin-path" => "test.fcgi")), - "test.ru" => ("localhost" => - ("min-procs" => 1, - "socket" => "/tmp/rack-test-ru-fcgi", - "bin-path" => CWD + "/rackup_stub.rb test.ru")), - "sample_rackup.ru" => ("localhost" => - ("min-procs" => 1, - "socket" => "/tmp/rack-test-rackup-fcgi", - "bin-path" => CWD + "/rackup_stub.rb sample_rackup.ru")), - ) diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/rackup_stub.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/rackup_stub.rb deleted file mode 100755 index a216cdc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/rackup_stub.rb +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env ruby -# -*- ruby -*- - -$:.unshift '../../lib' -require 'rack' -Rack::Server.start diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/sample_rackup.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/sample_rackup.ru deleted file mode 100755 index a73df81..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/sample_rackup.ru +++ /dev/null @@ -1,5 +0,0 @@ -# -*- ruby -*- - -require '../testrequest' - -run Rack::Lint.new(TestRequest.new) diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test deleted file mode 100755 index e4837a4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env ruby -# -*- ruby -*- - -$: << File.join(File.dirname(__FILE__), "..", "..", "lib") - -require 'rack' -require '../testrequest' - -Rack::Handler::CGI.run(Rack::Lint.new(TestRequest.new)) diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test+directory/test+file b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test+directory/test+file deleted file mode 100644 index f4273fb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test+directory/test+file +++ /dev/null @@ -1 +0,0 @@ -this file has plusses! diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test.fcgi b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test.fcgi deleted file mode 100755 index 5e104fc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test.fcgi +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env ruby -# -*- ruby -*- - -$:.unshift '../../lib' -require 'rack' -require '../testrequest' - -Rack::Handler::FastCGI.run(Rack::Lint.new(TestRequest.new)) diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test.ru deleted file mode 100755 index 7913ef7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/cgi/test.ru +++ /dev/null @@ -1,5 +0,0 @@ -#!../../bin/rackup -# -*- ruby -*- - -require '../testrequest' -run Rack::Lint.new(TestRequest.new) diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/gemloader.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/gemloader.rb deleted file mode 100644 index 22be697..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/gemloader.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'rubygems' -project = 'rack' -gemspec = File.expand_path("#{project}.gemspec", Dir.pwd) -Gem::Specification.load(gemspec).dependencies.each do |dep| - begin - gem dep.name, *dep.requirement.as_list - rescue Gem::LoadError - warn "Cannot load #{dep.name} #{dep.requirement.to_s}" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/bad_robots b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/bad_robots deleted file mode 100644 index 7e5bd41..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/bad_robots +++ /dev/null @@ -1,259 +0,0 @@ ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="bbbbbbbbbbbbbbb" - -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa -aaaaaaaaaaaaaaaaaaaa - ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="ccccccc" - -ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="file.name" - -INPUTMSG.gz ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="file.content_type" - -application/octet-stream ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="file.path" - -/var/tmp/uploads/4/0001728414 ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="file.md5" - -aa73198feb4b4c1c3186f5e7466cbbcc ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="file.size" - -13212 ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="size" - -80892 ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="mail_server_id" - -<1111111111.22222222.3333333333333.JavaMail.app@ffff-aaaa.dddd> - ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="addresses" - -{"campsy_programmer@pinkedum.com":{"domain":"pinkedum.com","name":"Campsy Programmer","type":["env_sender"],"mailbox":"campsy_programmer"},"tex@rapidcity.com":{"domain":"rapidcity.com","name":"Big Tex","type":["env_recipients","to"],"mailbox":"tex"},"group-digests@linkedin.com":{"domain":"linkedin.com","name":"Group Members","type":["from"],"mailbox":"group-digests"}} ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="received_on" - -2009-11-15T14:21:11Z ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="id" - -dbfd9804d26d11deab24e3037639bf77 ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon -Content-Disposition: form-data; name="ip_address" - -127.0.0.1 ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/binary b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/binary deleted file mode 100644 index a3bd67c..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/binary and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/content_type_and_no_filename b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/content_type_and_no_filename deleted file mode 100644 index bd4c89b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/content_type_and_no_filename +++ /dev/null @@ -1,6 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="text" -Content-Type: text/plain; charset=US-ASCII - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/empty b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/empty deleted file mode 100644 index f0f7983..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/empty +++ /dev/null @@ -1,10 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="submit-name" - -Larry ---AaB03x -Content-Disposition: form-data; name="files"; filename="file1.txt" -Content-Type: text/plain - - ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/fail_16384_nofile b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/fail_16384_nofile deleted file mode 100644 index bdcd332..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/fail_16384_nofile +++ /dev/null @@ -1,814 +0,0 @@ -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="_method" - -put -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="authenticity_token" - -XCUgSyYsZ+iHQunq/yCSKFzjeVmsXV/WcphHQ0J+05I= -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[SESE]" - -BooBar -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[BBBBBBBBB]" - -18 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[CCCCCCCCCCCCCCCCCCC]" - -0 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[STARTFOO]" - -2009-11-04 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[ENDFOO]" - -2009-12-01 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[DDDDDDDD]" - -0 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[DDDDDDDD]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[EEEEEEEEEE]" - -10000 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[FFFFFFFFF]" - -boskoizcool -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[GGGGGGGGGGG]" - -0 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[GGGGGGGGGGG]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[YYYYYYYYYYYYYYY]" - -5.00 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[ZZZZZZZZZZZZZ]" - -mille -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[XXXXXXXXXXXXXXXXXXXXX]" - -0 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][9]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][10]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][11]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][12]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][13]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][14]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][15]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][16]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][17]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][18]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][19]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][20]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][21]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][22]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][23]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][0]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][1]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][2]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][3]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][4]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][5]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][6]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][7]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][1][8]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][9]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][10]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][11]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][12]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][13]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][14]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][15]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][16]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][17]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][18]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][19]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][20]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][21]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][22]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][23]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][0]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][1]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][2]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][3]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][4]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][5]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][6]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][7]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][2][8]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][9]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][10]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][11]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][12]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][13]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][14]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][15]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][16]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][17]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][18]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][19]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][20]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][21]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][22]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][23]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][0]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][1]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][2]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][3]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][4]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][5]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][6]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][7]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][3][8]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][9]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][10]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][11]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][12]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][13]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][14]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][15]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][16]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][17]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][18]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][19]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][20]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][21]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][22]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][23]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][0]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][1]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][2]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][3]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][4]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][5]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][6]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][7]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][4][8]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][9]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][10]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][11]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][12]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][13]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][14]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][15]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][16]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][17]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][18]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][19]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][20]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][21]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][22]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][23]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][0]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][1]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][2]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][3]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][4]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][5]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][6]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][7]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][5][8]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][9]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][10]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][11]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][12]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][13]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][14]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][15]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][16]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][17]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][18]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][19]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][20]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][21]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][22]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][23]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][0]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][1]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][2]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][3]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][4]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][5]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][6]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][7]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][6][8]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][9]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][10]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][11]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][12]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][13]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][14]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][15]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][16]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][17]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][18]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][19]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][20]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][21]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][22]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][23]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][0]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][1]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][2]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][3]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][4]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][5]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][6]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][7]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[VVVVVVVVVVVVVVVVVVVVVVV][0][8]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[WWWWWWWWWWWWWWWWWWWWWWWWW][678][ZEZE]" - -PLAPLAPLAINCINCINC -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[WWWWWWWWWWWWWWWWWWWWWWWWW][678][123412341234e]" - -SITE -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[WWWWWWWWWWWWWWWWWWWWWWWWW][678][12345678901]" - -56 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_type]" - -none -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_wizard][has_hashashas_has]" - -0 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_wizard][frefrefre_fre_freee]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_wizard][frefrefre_fre_frefre]" - -forever -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_wizard][self_block]" - -0 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_wizard][GGG_RULES][][COUCOUN]" - - -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_wizard][GGG_RULES][][REGREG]" - - -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_wizard][GGG_RULES][][c1c1]" - - -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA_TARTARTAR_wizard_rule" - - -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[TARTARTAR_rule]" - - -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[selection_selection]" - -R -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[PLAPLAPLA_MEMMEMMEMM_ATTRATTRER][new][-1][selection_selection]" - -1 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[PLAPLAPLA_MEMMEMMEMM_ATTRATTRER][new][-1][ba_unit_id]" - -1015 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[PLAPLAPLA_MEMMEMMEMM_ATTRATTRER][new][-2][selection_selection]" - -2 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[PLAPLAPLA_MEMMEMMEMM_ATTRATTRER][new][-2][ba_unit_id]" - -1017 -------WebKitFormBoundaryWsY0GnpbI5U7ztzo -Content-Disposition: form-data; name="AAAAAAAAAAAAAAAAAAA[tile_name]" - - -------WebKitFormBoundaryWsY0GnpbI5U7ztzo-- - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/file1.txt b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/file1.txt deleted file mode 100644 index 0839b2e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/file1.txt +++ /dev/null @@ -1 +0,0 @@ -contents \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_and_modification_param b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_and_modification_param deleted file mode 100644 index 20893f4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_and_modification_param +++ /dev/null @@ -1,7 +0,0 @@ ---AaB03x -Content-Type: image/jpeg -Content-Disposition: attachment; name="files"; filename=genome.jpeg; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"; -Content-Description: a complete map of the human genome - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_escaped_quotes b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_escaped_quotes deleted file mode 100644 index 0a332df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_escaped_quotes +++ /dev/null @@ -1,6 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="files"; filename="escape \"quotes" -Content-Type: application/octet-stream - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_escaped_quotes_and_modification_param b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_escaped_quotes_and_modification_param deleted file mode 100644 index 7619bd5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_escaped_quotes_and_modification_param +++ /dev/null @@ -1,7 +0,0 @@ ---AaB03x -Content-Type: image/jpeg -Content-Disposition: attachment; name="files"; filename=""human" genome.jpeg"; modification-date="Wed, 12 Feb 1997 16:29:51 -0500"; -Content-Description: a complete map of the human genome - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_percent_escaped_quotes b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_percent_escaped_quotes deleted file mode 100644 index 7db0641..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_percent_escaped_quotes +++ /dev/null @@ -1,6 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="files"; filename="escape %22quotes" -Content-Type: application/octet-stream - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages deleted file mode 100644 index f63dd22..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages +++ /dev/null @@ -1,6 +0,0 @@ -------WebKitFormBoundary2NHc7OhsgU68l3Al -Content-Disposition: form-data; name="document[attachment]"; filename="100% of a photo.jpeg" -Content-Type: image/jpeg - -contents -------WebKitFormBoundary2NHc7OhsgU68l3Al-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages2 b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages2 deleted file mode 100644 index 83eac36..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages2 +++ /dev/null @@ -1,6 +0,0 @@ -------WebKitFormBoundary2NHc7OhsgU68l3Al -Content-Disposition: form-data; name="document[attachment]"; filename="100%a" -Content-Type: image/jpeg - -contents -------WebKitFormBoundary2NHc7OhsgU68l3Al-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages3 b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages3 deleted file mode 100644 index 4dba3c8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_percentages3 +++ /dev/null @@ -1,6 +0,0 @@ -------WebKitFormBoundary2NHc7OhsgU68l3Al -Content-Disposition: form-data; name="document[attachment]"; filename="100%" -Content-Type: image/jpeg - -contents -------WebKitFormBoundary2NHc7OhsgU68l3Al-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_quotes b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_quotes deleted file mode 100644 index 9a291e8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/filename_with_unescaped_quotes +++ /dev/null @@ -1,6 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="files"; filename="escape "quotes" -Content-Type: application/octet-stream - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/ie b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/ie deleted file mode 100644 index eae06ab..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/ie +++ /dev/null @@ -1,6 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="files"; filename="C:\Documents and Settings\Administrator\Desktop\file1.txt" -Content-Type: text/plain - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/mixed_files b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/mixed_files deleted file mode 100644 index 624d804..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/mixed_files +++ /dev/null @@ -1,21 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="foo" - -bar ---AaB03x -Content-Disposition: form-data; name="files" -Content-Type: multipart/mixed, boundary=BbC04y - ---BbC04y -Content-Disposition: attachment; filename="file.txt" -Content-Type: text/plain - -contents ---BbC04y -Content-Disposition: attachment; filename="flowers.jpg" -Content-Type: image/jpeg -Content-Transfer-Encoding: binary - -contents ---BbC04y-- ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/nested b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/nested deleted file mode 100644 index 5197882..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/nested +++ /dev/null @@ -1,10 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="foo[submit-name]" - -Larry ---AaB03x -Content-Disposition: form-data; name="foo[files]"; filename="file1.txt" -Content-Type: text/plain - -contents ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/none b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/none deleted file mode 100644 index d66f473..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/none +++ /dev/null @@ -1,9 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="submit-name" - -Larry ---AaB03x -Content-Disposition: form-data; name="files"; filename="" - - ---AaB03x-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/semicolon b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/semicolon deleted file mode 100644 index 00fd68a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/semicolon +++ /dev/null @@ -1,6 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="files"; filename="fi;le1.txt" -Content-Type: text/plain - -contents ---AaB03x-- \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/text b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/text deleted file mode 100644 index 01376d0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/text +++ /dev/null @@ -1,15 +0,0 @@ ---AaB03x -Content-Disposition: form-data; name="submit-name" - -Larry ---AaB03x -Content-Disposition: form-data; name="submit-name-with-content" -Content-Type: text/plain - -Berry ---AaB03x -Content-Disposition: form-data; name="files"; filename="file1.txt" -Content-Type: text/plain - -contents ---AaB03x-- \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/webkit b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/webkit deleted file mode 100644 index 1375af3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/multipart/webkit +++ /dev/null @@ -1,32 +0,0 @@ -------WebKitFormBoundaryWLHCs9qmcJJoyjKR -Content-Disposition: form-data; name="_method" - -put -------WebKitFormBoundaryWLHCs9qmcJJoyjKR -Content-Disposition: form-data; name="profile[blog]" - - -------WebKitFormBoundaryWLHCs9qmcJJoyjKR -Content-Disposition: form-data; name="profile[public_email]" - - -------WebKitFormBoundaryWLHCs9qmcJJoyjKR -Content-Disposition: form-data; name="profile[interests]" - - -------WebKitFormBoundaryWLHCs9qmcJJoyjKR -Content-Disposition: form-data; name="profile[bio]" - -hello - -"quote" -------WebKitFormBoundaryWLHCs9qmcJJoyjKR -Content-Disposition: form-data; name="media"; filename="" -Content-Type: application/octet-stream - - -------WebKitFormBoundaryWLHCs9qmcJJoyjKR -Content-Disposition: form-data; name="commit" - -Save -------WebKitFormBoundaryWLHCs9qmcJJoyjKR-- diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/rackup/config.ru b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/rackup/config.ru deleted file mode 100644 index f1e2e1f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/rackup/config.ru +++ /dev/null @@ -1,31 +0,0 @@ -require "#{File.dirname(__FILE__)}/../testrequest" - -$stderr = File.open("#{File.dirname(__FILE__)}/log_output", "w") - -class EnvMiddleware - def initialize(app) - @app = app - end - - def call(env) - # provides a way to test that lint is present - if env["PATH_INFO"] == "/broken_lint" - return [200, {}, ["Broken Lint"]] - # provides a way to kill the process without knowing the pid - elsif env["PATH_INFO"] == "/die" - exit! - end - - env["test.$DEBUG"] = $DEBUG - env["test.$EVAL"] = BUKKIT if defined?(BUKKIT) - env["test.$VERBOSE"] = $VERBOSE - env["test.$LOAD_PATH"] = $LOAD_PATH - env["test.stderr"] = File.expand_path($stderr.path) - env["test.Ping"] = defined?(Ping) - env["test.pid"] = Process.pid - @app.call(env) - end -end - -use EnvMiddleware -run TestRequest.new diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/registering_handler/rack/handler/registering_myself.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/registering_handler/rack/handler/registering_myself.rb deleted file mode 100644 index 1635efa..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/registering_handler/rack/handler/registering_myself.rb +++ /dev/null @@ -1,8 +0,0 @@ -module Rack - module Handler - class RegisteringMyself - end - - register :registering_myself, RegisteringMyself - end -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_auth_basic.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_auth_basic.rb deleted file mode 100644 index af8e779..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_auth_basic.rb +++ /dev/null @@ -1,81 +0,0 @@ -require 'rack/auth/basic' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Auth::Basic do - def realm - 'WallysWorld' - end - - def unprotected_app - Rack::Lint.new lambda { |env| - [ 200, {'Content-Type' => 'text/plain'}, ["Hi #{env['REMOTE_USER']}"] ] - } - end - - def protected_app - app = Rack::Auth::Basic.new(unprotected_app) { |username, password| 'Boss' == username } - app.realm = realm - app - end - - before do - @request = Rack::MockRequest.new(protected_app) - end - - def request_with_basic_auth(username, password, &block) - request 'HTTP_AUTHORIZATION' => 'Basic ' + ["#{username}:#{password}"].pack("m*"), &block - end - - def request(headers = {}) - yield @request.get('/', headers) - end - - def assert_basic_auth_challenge(response) - response.should.be.a.client_error - response.status.should.equal 401 - response.should.include 'WWW-Authenticate' - response.headers['WWW-Authenticate'].should =~ /Basic realm="#{Regexp.escape(realm)}"/ - response.body.should.be.empty - end - - should 'challenge correctly when no credentials are specified' do - request do |response| - assert_basic_auth_challenge response - end - end - - should 'rechallenge if incorrect credentials are specified' do - request_with_basic_auth 'joe', 'password' do |response| - assert_basic_auth_challenge response - end - end - - should 'return application output if correct credentials are specified' do - request_with_basic_auth 'Boss', 'password' do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Boss' - end - end - - should 'return 400 Bad Request if different auth scheme used' do - request 'HTTP_AUTHORIZATION' => 'Digest params' do |response| - response.should.be.a.client_error - response.status.should.equal 400 - response.should.not.include 'WWW-Authenticate' - end - end - - should 'return 400 Bad Request for a malformed authorization header' do - request 'HTTP_AUTHORIZATION' => '' do |response| - response.should.be.a.client_error - response.status.should.equal 400 - response.should.not.include 'WWW-Authenticate' - end - end - - it 'takes realm as optional constructor arg' do - app = Rack::Auth::Basic.new(unprotected_app, realm) { true } - realm.should == app.realm - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_auth_digest.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_auth_digest.rb deleted file mode 100644 index 040be2e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_auth_digest.rb +++ /dev/null @@ -1,259 +0,0 @@ -require 'rack/auth/digest/md5' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Auth::Digest::MD5 do - def realm - 'WallysWorld' - end - - def unprotected_app - Rack::Lint.new lambda { |env| - friend = Rack::Utils.parse_query(env["QUERY_STRING"])["friend"] - [ 200, {'Content-Type' => 'text/plain'}, ["Hi #{env['REMOTE_USER']}#{friend ? " and #{friend}" : ''}"] ] - } - end - - def protected_app - Rack::Auth::Digest::MD5.new(unprotected_app, :realm => realm, :opaque => 'this-should-be-secret') do |username| - { 'Alice' => 'correct-password' }[username] - end - end - - def protected_app_with_hashed_passwords - app = Rack::Auth::Digest::MD5.new(unprotected_app) do |username| - username == 'Alice' ? Digest::MD5.hexdigest("Alice:#{realm}:correct-password") : nil - end - app.realm = realm - app.opaque = 'this-should-be-secret' - app.passwords_hashed = true - app - end - - def partially_protected_app - Rack::URLMap.new({ - '/' => unprotected_app, - '/protected' => protected_app - }) - end - - def protected_app_with_method_override - Rack::MethodOverride.new(protected_app) - end - - before do - @request = Rack::MockRequest.new(protected_app) - end - - def request(method, path, headers = {}, &block) - response = @request.request(method, path, headers) - block.call(response) if block - return response - end - - class MockDigestRequest - def initialize(params) - @params = params - end - def method_missing(sym) - if @params.has_key? k = sym.to_s - return @params[k] - end - super - end - def method - @params['method'] - end - def response(password) - Rack::Auth::Digest::MD5.new(nil).send :digest, self, password - end - end - - def request_with_digest_auth(method, path, username, password, options = {}, &block) - request_options = {} - request_options[:input] = options.delete(:input) if options.include? :input - - response = request(method, path, request_options) - - return response unless response.status == 401 - - if wait = options.delete(:wait) - sleep wait - end - - challenge = response['WWW-Authenticate'].split(' ', 2).last - - params = Rack::Auth::Digest::Params.parse(challenge) - - params['username'] = username - params['nc'] = '00000001' - params['cnonce'] = 'nonsensenonce' - params['uri'] = path - - params['method'] = method - - params.update options - - params['response'] = MockDigestRequest.new(params).response(password) - - request(method, path, request_options.merge('HTTP_AUTHORIZATION' => "Digest #{params}"), &block) - end - - def assert_digest_auth_challenge(response) - response.should.be.a.client_error - response.status.should.equal 401 - response.should.include 'WWW-Authenticate' - response.headers['WWW-Authenticate'].should =~ /^Digest / - response.body.should.be.empty - end - - def assert_bad_request(response) - response.should.be.a.client_error - response.status.should.equal 400 - response.should.not.include 'WWW-Authenticate' - end - - should 'challenge when no credentials are specified' do - request 'GET', '/' do |response| - assert_digest_auth_challenge response - end - end - - should 'return application output if correct credentials given' do - request_with_digest_auth 'GET', '/', 'Alice', 'correct-password' do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice' - end - end - - should 'return application output if correct credentials given (hashed passwords)' do - @request = Rack::MockRequest.new(protected_app_with_hashed_passwords) - - request_with_digest_auth 'GET', '/', 'Alice', 'correct-password' do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice' - end - end - - should 'rechallenge if incorrect username given' do - request_with_digest_auth 'GET', '/', 'Bob', 'correct-password' do |response| - assert_digest_auth_challenge response - end - end - - should 'rechallenge if incorrect password given' do - request_with_digest_auth 'GET', '/', 'Alice', 'wrong-password' do |response| - assert_digest_auth_challenge response - end - end - - should 'rechallenge if incorrect user and blank password given' do - request_with_digest_auth 'GET', '/', 'Bob', '' do |response| - assert_digest_auth_challenge response - end - end - - should 'not rechallenge if nonce is not stale' do - begin - Rack::Auth::Digest::Nonce.time_limit = 10 - - request_with_digest_auth 'GET', '/', 'Alice', 'correct-password', :wait => 1 do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice' - response.headers['WWW-Authenticate'].should.not =~ /\bstale=true\b/ - end - ensure - Rack::Auth::Digest::Nonce.time_limit = nil - end - end - - should 'rechallenge with stale parameter if nonce is stale' do - begin - Rack::Auth::Digest::Nonce.time_limit = 1 - - request_with_digest_auth 'GET', '/', 'Alice', 'correct-password', :wait => 2 do |response| - assert_digest_auth_challenge response - response.headers['WWW-Authenticate'].should =~ /\bstale=true\b/ - end - ensure - Rack::Auth::Digest::Nonce.time_limit = nil - end - end - - should 'return 400 Bad Request if incorrect qop given' do - request_with_digest_auth 'GET', '/', 'Alice', 'correct-password', 'qop' => 'auth-int' do |response| - assert_bad_request response - end - end - - should 'return 400 Bad Request if incorrect uri given' do - request_with_digest_auth 'GET', '/', 'Alice', 'correct-password', 'uri' => '/foo' do |response| - assert_bad_request response - end - end - - should 'return 400 Bad Request if different auth scheme used' do - request 'GET', '/', 'HTTP_AUTHORIZATION' => 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==' do |response| - assert_bad_request response - end - end - - should 'not require credentials for unprotected path' do - @request = Rack::MockRequest.new(partially_protected_app) - request 'GET', '/' do |response| - response.should.be.ok - end - end - - should 'challenge when no credentials are specified for protected path' do - @request = Rack::MockRequest.new(partially_protected_app) - request 'GET', '/protected' do |response| - assert_digest_auth_challenge response - end - end - - should 'return application output if correct credentials given for protected path' do - @request = Rack::MockRequest.new(partially_protected_app) - request_with_digest_auth 'GET', '/protected', 'Alice', 'correct-password' do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice' - end - end - - should 'return application output when used with a query string and path as uri' do - @request = Rack::MockRequest.new(partially_protected_app) - request_with_digest_auth 'GET', '/protected?friend=Mike', 'Alice', 'correct-password' do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice and Mike' - end - end - - should 'return application output when used with a query string and fullpath as uri' do - @request = Rack::MockRequest.new(partially_protected_app) - qs_uri = '/protected?friend=Mike' - request_with_digest_auth 'GET', qs_uri, 'Alice', 'correct-password', 'uri' => qs_uri do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice and Mike' - end - end - - should 'return application output if correct credentials given for POST' do - request_with_digest_auth 'POST', '/', 'Alice', 'correct-password' do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice' - end - end - - should 'return application output if correct credentials given for PUT (using method override of POST)' do - @request = Rack::MockRequest.new(protected_app_with_method_override) - request_with_digest_auth 'POST', '/', 'Alice', 'correct-password', :input => "_method=put" do |response| - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Alice' - end - end - - it 'takes realm as optional constructor arg' do - app = Rack::Auth::Digest::MD5.new(unprotected_app, realm) { true } - realm.should == app.realm - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_body_proxy.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_body_proxy.rb deleted file mode 100644 index c65e10d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_body_proxy.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'rack/body_proxy' -require 'stringio' - -describe Rack::BodyProxy do - should 'call each on the wrapped body' do - called = false - proxy = Rack::BodyProxy.new(['foo']) { } - proxy.each do |str| - called = true - str.should.equal 'foo' - end - called.should.equal true - end - - should 'call close on the wrapped body' do - body = StringIO.new - proxy = Rack::BodyProxy.new(body) { } - proxy.close - body.should.be.closed - end - - should 'only call close on the wrapped body if it responds to close' do - body = [] - proxy = Rack::BodyProxy.new(body) { } - proc { proxy.close }.should.not.raise - end - - should 'call the passed block on close' do - called = false - proxy = Rack::BodyProxy.new([]) { called = true } - called.should.equal false - proxy.close - called.should.equal true - end - - should 'call the passed block on close even if there is an exception' do - object = Object.new - def object.close() raise "No!" end - called = false - - begin - proxy = Rack::BodyProxy.new(object) { called = true } - called.should.equal false - proxy.close - rescue RuntimeError => e - end - - raise "Expected exception to have been raised" unless e - called.should.equal true - end - - should 'not close more than one time' do - count = 0 - proxy = Rack::BodyProxy.new([]) { count += 1; raise "Block invoked more than 1 time!" if count > 1 } - 2.times { proxy.close } - count.should.equal 1 - end - - should 'be closed when the callback is triggered' do - closed = false - proxy = Rack::BodyProxy.new([]) { closed = proxy.closed? } - proxy.close - closed.should.equal true - end - - should 'provide an #each method' do - Rack::BodyProxy.method_defined?(:each).should.equal true - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_builder.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_builder.rb deleted file mode 100644 index a2fd568..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_builder.rb +++ /dev/null @@ -1,214 +0,0 @@ -require 'rack/builder' -require 'rack/lint' -require 'rack/mock' -require 'rack/showexceptions' -require 'rack/urlmap' - -class NothingMiddleware - def initialize(app) - @app = app - end - def call(env) - @@env = env - response = @app.call(env) - response - end - def self.env - @@env - end -end - -describe Rack::Builder do - def builder(&block) - Rack::Lint.new Rack::Builder.new(&block) - end - - def builder_to_app(&block) - Rack::Lint.new Rack::Builder.new(&block).to_app - end - - it "supports mapping" do - app = builder_to_app do - map '/' do |outer_env| - run lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, ['root']] } - end - map '/sub' do - run lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, ['sub']] } - end - end - Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'root' - Rack::MockRequest.new(app).get("/sub").body.to_s.should.equal 'sub' - end - - it "doesn't dupe env even when mapping" do - app = builder_to_app do - use NothingMiddleware - map '/' do |outer_env| - run lambda { |inner_env| - inner_env['new_key'] = 'new_value' - [200, {"Content-Type" => "text/plain"}, ['root']] - } - end - end - Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'root' - NothingMiddleware.env['new_key'].should.equal 'new_value' - end - - it "chains apps by default" do - app = builder_to_app do - use Rack::ShowExceptions - run lambda { |env| raise "bzzzt" } - end - - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - end - - it "has implicit #to_app" do - app = builder do - use Rack::ShowExceptions - run lambda { |env| raise "bzzzt" } - end - - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - end - - it "supports blocks on use" do - app = builder do - use Rack::ShowExceptions - use Rack::Auth::Basic do |username, password| - 'secret' == password - end - - run lambda { |env| [200, {"Content-Type" => "text/plain"}, ['Hi Boss']] } - end - - response = Rack::MockRequest.new(app).get("/") - response.should.be.client_error - response.status.should.equal 401 - - # with auth... - response = Rack::MockRequest.new(app).get("/", - 'HTTP_AUTHORIZATION' => 'Basic ' + ["joe:secret"].pack("m*")) - response.status.should.equal 200 - response.body.to_s.should.equal 'Hi Boss' - end - - it "has explicit #to_app" do - app = builder do - use Rack::ShowExceptions - run lambda { |env| raise "bzzzt" } - end - - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - end - - it "can mix map and run for endpoints" do - app = builder do - map '/sub' do - run lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, ['sub']] } - end - run lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, ['root']] } - end - - Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'root' - Rack::MockRequest.new(app).get("/sub").body.to_s.should.equal 'sub' - end - - it "accepts middleware-only map blocks" do - app = builder do - map('/foo') { use Rack::ShowExceptions } - run lambda { |env| raise "bzzzt" } - end - - proc { Rack::MockRequest.new(app).get("/") }.should.raise(RuntimeError) - Rack::MockRequest.new(app).get("/foo").should.be.server_error - end - - should "initialize apps once" do - app = builder do - class AppClass - def initialize - @called = 0 - end - def call(env) - raise "bzzzt" if @called > 0 - @called += 1 - [200, {'Content-Type' => 'text/plain'}, ['OK']] - end - end - - use Rack::ShowExceptions - run AppClass.new - end - - Rack::MockRequest.new(app).get("/").status.should.equal 200 - Rack::MockRequest.new(app).get("/").should.be.server_error - end - - it "allows use after run" do - app = builder do - run lambda { |env| raise "bzzzt" } - use Rack::ShowExceptions - end - - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - Rack::MockRequest.new(app).get("/").should.be.server_error - end - - it 'complains about a missing run' do - proc do - Rack::Lint.new Rack::Builder.app { use Rack::ShowExceptions } - end.should.raise(RuntimeError) - end - - describe "parse_file" do - def config_file(name) - File.join(File.dirname(__FILE__), 'builder', name) - end - - it "parses commented options" do - app, options = Rack::Builder.parse_file config_file('options.ru') - options[:debug].should.be.true - Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'OK' - end - - it "removes __END__ before evaluating app" do - app, options = Rack::Builder.parse_file config_file('end.ru') - options = nil # ignored, prevents warning - Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'OK' - end - - it "supports multi-line comments" do - lambda { - Rack::Builder.parse_file config_file('comment.ru') - }.should.not.raise(SyntaxError) - end - - it "requires anything not ending in .ru" do - $: << File.dirname(__FILE__) - app, * = Rack::Builder.parse_file 'builder/anything' - Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'OK' - $:.pop - end - - it "sets __LINE__ correctly" do - app, options = Rack::Builder.parse_file config_file('line.ru') - options = nil # ignored, prevents warning - Rack::MockRequest.new(app).get("/").body.to_s.should.equal '1' - end - end - - describe 'new_from_string' do - it "builds a rack app from string" do - app, = Rack::Builder.new_from_string "run lambda{|env| [200, {'Content-Type' => 'text/plane'}, ['OK']] }" - Rack::MockRequest.new(app).get("/").body.to_s.should.equal 'OK' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_cascade.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_cascade.rb deleted file mode 100644 index 38a18da..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_cascade.rb +++ /dev/null @@ -1,61 +0,0 @@ -require 'rack/cascade' -require 'rack/file' -require 'rack/lint' -require 'rack/urlmap' -require 'rack/mock' - -describe Rack::Cascade do - def cascade(*args) - Rack::Lint.new Rack::Cascade.new(*args) - end - - docroot = File.expand_path(File.dirname(__FILE__)) - app1 = Rack::File.new(docroot) - - app2 = Rack::URLMap.new("/crash" => lambda { |env| raise "boom" }) - - app3 = Rack::URLMap.new("/foo" => lambda { |env| - [200, { "Content-Type" => "text/plain"}, [""]]}) - - should "dispatch onward on 404 and 405 by default" do - cascade = cascade([app1, app2, app3]) - Rack::MockRequest.new(cascade).get("/cgi/test").should.be.ok - Rack::MockRequest.new(cascade).get("/foo").should.be.ok - Rack::MockRequest.new(cascade).get("/toobad").should.be.not_found - Rack::MockRequest.new(cascade).get("/cgi/../..").should.be.client_error - - # Put is not allowed by Rack::File so it'll 405. - Rack::MockRequest.new(cascade).put("/foo").should.be.ok - end - - should "dispatch onward on whatever is passed" do - cascade = cascade([app1, app2, app3], [404, 403]) - Rack::MockRequest.new(cascade).get("/cgi/../bla").should.be.not_found - end - - should "return 404 if empty" do - Rack::MockRequest.new(cascade([])).get('/').should.be.not_found - end - - should "append new app" do - cascade = Rack::Cascade.new([], [404, 403]) - Rack::MockRequest.new(cascade).get('/').should.be.not_found - cascade << app2 - Rack::MockRequest.new(cascade).get('/cgi/test').should.be.not_found - Rack::MockRequest.new(cascade).get('/cgi/../bla').should.be.not_found - cascade << app1 - Rack::MockRequest.new(cascade).get('/cgi/test').should.be.ok - Rack::MockRequest.new(cascade).get('/cgi/../..').should.be.client_error - Rack::MockRequest.new(cascade).get('/foo').should.be.not_found - cascade << app3 - Rack::MockRequest.new(cascade).get('/foo').should.be.ok - end - - should "close the body on cascade" do - body = StringIO.new - closer = lambda { |env| [404, {}, body] } - cascade = Rack::Cascade.new([closer, app3], [404]) - Rack::MockRequest.new(cascade).get("/foo").should.be.ok - body.should.be.closed - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_cgi.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_cgi.rb deleted file mode 100644 index 8c90ec8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_cgi.rb +++ /dev/null @@ -1,102 +0,0 @@ -begin -require File.expand_path('../testrequest', __FILE__) -require 'rack/handler/cgi' - -describe Rack::Handler::CGI do - extend TestRequest::Helpers - - @host = '127.0.0.1' - @port = 9203 - - if `which lighttpd` && !$?.success? - raise "lighttpd not found" - end - - # Keep this first. - $pid = fork { - ENV['RACK_ENV'] = 'deployment' - ENV['RUBYLIB'] = [ - File.expand_path('../../lib', __FILE__), - ENV['RUBYLIB'], - ].compact.join(':') - - Dir.chdir(File.expand_path("../cgi", __FILE__)) do - exec "lighttpd -D -f lighttpd.conf" - end - } - - should "respond" do - sleep 1 - GET("/test") - response.should.not.be.nil - end - - should "be a lighttpd" do - GET("/test") - status.should.equal 200 - response["SERVER_SOFTWARE"].should =~ /lighttpd/ - response["HTTP_VERSION"].should.equal "HTTP/1.1" - response["SERVER_PROTOCOL"].should.equal "HTTP/1.1" - response["SERVER_PORT"].should.equal @port.to_s - response["SERVER_NAME"].should.equal @host - end - - should "have rack headers" do - GET("/test") - response["rack.version"].should.equal([1,2]) - response["rack.multithread"].should.be.false - response["rack.multiprocess"].should.be.true - response["rack.run_once"].should.be.true - end - - should "have CGI headers on GET" do - GET("/test") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/" - response["PATH_INFO"].should.be.nil - response["QUERY_STRING"].should.equal "" - response["test.postdata"].should.equal "" - - GET("/test/foo?quux=1") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/" - response["PATH_INFO"].should.equal "/foo" - response["QUERY_STRING"].should.equal "quux=1" - end - - should "have CGI headers on POST" do - POST("/test", {"rack-form-data" => "23"}, {'X-test-header' => '42'}) - status.should.equal 200 - response["REQUEST_METHOD"].should.equal "POST" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/" - response["QUERY_STRING"].should.equal "" - response["HTTP_X_TEST_HEADER"].should.equal "42" - response["test.postdata"].should.equal "rack-form-data=23" - end - - should "support HTTP auth" do - GET("/test", {:user => "ruth", :passwd => "secret"}) - response["HTTP_AUTHORIZATION"].should.equal "Basic cnV0aDpzZWNyZXQ=" - end - - should "set status" do - GET("/test?secret") - status.should.equal 403 - response["rack.url_scheme"].should.equal "http" - end - - # Keep this last. - should "shutdown" do - Process.kill 15, $pid - Process.wait($pid).should == $pid - end -end - -rescue RuntimeError - $stderr.puts "Skipping Rack::Handler::CGI tests (lighttpd is required). Install lighttpd and try again." -rescue NotImplementedError - $stderr.puts "Your Ruby implemenation or platform does not support fork. Skipping Rack::Handler::CGI tests." -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_chunked.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_chunked.rb deleted file mode 100644 index 12f2158..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_chunked.rb +++ /dev/null @@ -1,85 +0,0 @@ -require 'rack/chunked' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Chunked do - def chunked(app) - proc do |env| - app = Rack::Chunked.new(app) - response = Rack::Lint.new(app).call(env) - # we want to use body like an array, but it only has #each - response[2] = response[2].to_enum.to_a - response - end - end - - before do - @env = Rack::MockRequest. - env_for('/', 'HTTP_VERSION' => '1.1', 'REQUEST_METHOD' => 'GET') - end - - should 'chunk responses with no Content-Length' do - app = lambda { |env| [200, {"Content-Type" => "text/plain"}, ['Hello', ' ', 'World!']] } - response = Rack::MockResponse.new(*chunked(app).call(@env)) - response.headers.should.not.include 'Content-Length' - response.headers['Transfer-Encoding'].should.equal 'chunked' - response.body.should.equal "5\r\nHello\r\n1\r\n \r\n6\r\nWorld!\r\n0\r\n\r\n" - end - - should 'chunks empty bodies properly' do - app = lambda { |env| [200, {"Content-Type" => "text/plain"}, []] } - response = Rack::MockResponse.new(*chunked(app).call(@env)) - response.headers.should.not.include 'Content-Length' - response.headers['Transfer-Encoding'].should.equal 'chunked' - response.body.should.equal "0\r\n\r\n" - end - - should 'chunks encoded bodies properly' do - body = ["\uFFFEHello", " ", "World"].map {|t| t.encode("UTF-16LE") } - app = lambda { |env| [200, {"Content-Type" => "text/plain"}, body] } - response = Rack::MockResponse.new(*chunked(app).call(@env)) - response.headers.should.not.include 'Content-Length' - response.headers['Transfer-Encoding'].should.equal 'chunked' - response.body.encoding.to_s.should.equal "ASCII-8BIT" - response.body.should.equal "c\r\n\xFE\xFFH\x00e\x00l\x00l\x00o\x00\r\n2\r\n \x00\r\na\r\nW\x00o\x00r\x00l\x00d\x00\r\n0\r\n\r\n".force_encoding("BINARY") - end if RUBY_VERSION >= "1.9" - - should 'not modify response when Content-Length header present' do - app = lambda { |env| - [200, {"Content-Type" => "text/plain", 'Content-Length'=>'12'}, ['Hello', ' ', 'World!']] - } - status, headers, body = chunked(app).call(@env) - status.should.equal 200 - headers.should.not.include 'Transfer-Encoding' - headers.should.include 'Content-Length' - body.join.should.equal 'Hello World!' - end - - should 'not modify response when client is HTTP/1.0' do - app = lambda { |env| [200, {"Content-Type" => "text/plain"}, ['Hello', ' ', 'World!']] } - @env['HTTP_VERSION'] = 'HTTP/1.0' - status, headers, body = chunked(app).call(@env) - status.should.equal 200 - headers.should.not.include 'Transfer-Encoding' - body.join.should.equal 'Hello World!' - end - - should 'not modify response when Transfer-Encoding header already present' do - app = lambda { |env| - [200, {"Content-Type" => "text/plain", 'Transfer-Encoding' => 'identity'}, ['Hello', ' ', 'World!']] - } - status, headers, body = chunked(app).call(@env) - status.should.equal 200 - headers['Transfer-Encoding'].should.equal 'identity' - body.join.should.equal 'Hello World!' - end - - [100, 204, 205, 304].each do |status_code| - should "not modify response when status code is #{status_code}" do - app = lambda { |env| [status_code, {}, []] } - status, headers, _ = chunked(app).call(@env) - status.should.equal status_code - headers.should.not.include 'Transfer-Encoding' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_commonlogger.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_commonlogger.rb deleted file mode 100644 index d88e19c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_commonlogger.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'rack/commonlogger' -require 'rack/lint' -require 'rack/mock' - -describe Rack::CommonLogger do - obj = 'foobar' - length = obj.size - - app = Rack::Lint.new lambda { |env| - [200, - {"Content-Type" => "text/html", "Content-Length" => length.to_s}, - [obj]]} - app_without_length = Rack::Lint.new lambda { |env| - [200, - {"Content-Type" => "text/html"}, - []]} - app_with_zero_length = Rack::Lint.new lambda { |env| - [200, - {"Content-Type" => "text/html", "Content-Length" => "0"}, - []]} - - should "log to rack.errors by default" do - res = Rack::MockRequest.new(Rack::CommonLogger.new(app)).get("/") - - res.errors.should.not.be.empty - res.errors.should =~ /"GET \/ " 200 #{length} / - end - - should "log to anything with +write+" do - log = StringIO.new - Rack::MockRequest.new(Rack::CommonLogger.new(app, log)).get("/") - - log.string.should =~ /"GET \/ " 200 #{length} / - end - - should "log - content length if header is missing" do - res = Rack::MockRequest.new(Rack::CommonLogger.new(app_without_length)).get("/") - - res.errors.should.not.be.empty - res.errors.should =~ /"GET \/ " 200 - / - end - - should "log - content length if header is zero" do - res = Rack::MockRequest.new(Rack::CommonLogger.new(app_with_zero_length)).get("/") - - res.errors.should.not.be.empty - res.errors.should =~ /"GET \/ " 200 - / - end - - def length - 123 - end - - def self.obj - "hello world" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_conditionalget.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_conditionalget.rb deleted file mode 100644 index 8b365eb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_conditionalget.rb +++ /dev/null @@ -1,102 +0,0 @@ -require 'time' -require 'rack/conditionalget' -require 'rack/mock' - -describe Rack::ConditionalGet do - def conditional_get(app) - Rack::Lint.new Rack::ConditionalGet.new(app) - end - - should "set a 304 status and truncate body when If-Modified-Since hits" do - timestamp = Time.now.httpdate - app = conditional_get(lambda { |env| - [200, {'Last-Modified'=>timestamp}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - get("/", 'HTTP_IF_MODIFIED_SINCE' => timestamp) - - response.status.should.equal 304 - response.body.should.be.empty - end - - should "set a 304 status and truncate body when If-Modified-Since hits and is higher than current time" do - app = conditional_get(lambda { |env| - [200, {'Last-Modified'=>(Time.now - 3600).httpdate}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - get("/", 'HTTP_IF_MODIFIED_SINCE' => Time.now.httpdate) - - response.status.should.equal 304 - response.body.should.be.empty - end - - should "set a 304 status and truncate body when If-None-Match hits" do - app = conditional_get(lambda { |env| - [200, {'Etag'=>'1234'}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - get("/", 'HTTP_IF_NONE_MATCH' => '1234') - - response.status.should.equal 304 - response.body.should.be.empty - end - - should "not set a 304 status if If-Modified-Since hits but Etag does not" do - timestamp = Time.now.httpdate - app = conditional_get(lambda { |env| - [200, {'Last-Modified'=>timestamp, 'Etag'=>'1234', 'Content-Type' => 'text/plain'}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - get("/", 'HTTP_IF_MODIFIED_SINCE' => timestamp, 'HTTP_IF_NONE_MATCH' => '4321') - - response.status.should.equal 200 - response.body.should.equal 'TEST' - end - - should "set a 304 status and truncate body when both If-None-Match and If-Modified-Since hits" do - timestamp = Time.now.httpdate - app = conditional_get(lambda { |env| - [200, {'Last-Modified'=>timestamp, 'Etag'=>'1234'}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - get("/", 'HTTP_IF_MODIFIED_SINCE' => timestamp, 'HTTP_IF_NONE_MATCH' => '1234') - - response.status.should.equal 304 - response.body.should.be.empty - end - - should "not affect non-GET/HEAD requests" do - app = conditional_get(lambda { |env| - [200, {'Etag'=>'1234', 'Content-Type' => 'text/plain'}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - post("/", 'HTTP_IF_NONE_MATCH' => '1234') - - response.status.should.equal 200 - response.body.should.equal 'TEST' - end - - should "not affect non-200 requests" do - app = conditional_get(lambda { |env| - [302, {'Etag'=>'1234', 'Content-Type' => 'text/plain'}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - get("/", 'HTTP_IF_NONE_MATCH' => '1234') - - response.status.should.equal 302 - response.body.should.equal 'TEST' - end - - should "not affect requests with malformed HTTP_IF_NONE_MATCH" do - bad_timestamp = Time.now.strftime('%Y-%m-%d %H:%M:%S %z') - app = conditional_get(lambda { |env| - [200,{'Last-Modified'=>(Time.now - 3600).httpdate, 'Content-Type' => 'text/plain'}, ['TEST']] }) - - response = Rack::MockRequest.new(app). - get("/", 'HTTP_IF_MODIFIED_SINCE' => bad_timestamp) - - response.status.should.equal 200 - response.body.should.equal 'TEST' - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_config.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_config.rb deleted file mode 100644 index 29bca0a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_config.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'rack/builder' -require 'rack/config' -require 'rack/content_length' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Config do - should "accept a block that modifies the environment" do - app = Rack::Builder.new do - use Rack::Lint - use Rack::Config do |env| - env['greeting'] = 'hello' - end - run lambda { |env| - [200, {'Content-Type' => 'text/plain'}, [env['greeting'] || '']] - } - end - - response = Rack::MockRequest.new(app).get('/') - response.body.should.equal('hello') - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_content_length.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_content_length.rb deleted file mode 100644 index 4b80a0f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_content_length.rb +++ /dev/null @@ -1,83 +0,0 @@ -require 'rack/content_length' -require 'rack/lint' -require 'rack/mock' - -describe Rack::ContentLength do - def content_length(app) - Rack::Lint.new Rack::ContentLength.new(app) - end - - def request - Rack::MockRequest.env_for - end - - should "set Content-Length on Array bodies if none is set" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] } - response = content_length(app).call(request) - response[1]['Content-Length'].should.equal '13' - end - - should "not set Content-Length on variable length bodies" do - body = lambda { "Hello World!" } - def body.each ; yield call ; end - - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, body] } - response = content_length(app).call(request) - response[1]['Content-Length'].should.be.nil - end - - should "not change Content-Length if it is already set" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Content-Length' => '1'}, "Hello, World!"] } - response = content_length(app).call(request) - response[1]['Content-Length'].should.equal '1' - end - - should "not set Content-Length on 304 responses" do - app = lambda { |env| [304, {}, []] } - response = content_length(app).call(request) - response[1]['Content-Length'].should.equal nil - end - - should "not set Content-Length when Transfer-Encoding is chunked" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Transfer-Encoding' => 'chunked'}, []] } - response = content_length(app).call(request) - response[1]['Content-Length'].should.equal nil - end - - # Using "Connection: close" for this is fairly contended. It might be useful - # to have some other way to signal this. - # - # should "not force a Content-Length when Connection:close" do - # app = lambda { |env| [200, {'Connection' => 'close'}, []] } - # response = content_length(app).call({}) - # response[1]['Content-Length'].should.equal nil - # end - - should "close bodies that need to be closed" do - body = Struct.new(:body) do - attr_reader :closed - def each; body.join; end - def close; @closed = true; end - def to_ary; end - end.new(%w[one two three]) - - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, body] } - content_length(app).call(request) - body.closed.should.equal true - end - - should "support single-execute bodies" do - body = Struct.new(:body) do - def each - yield body.shift until body.empty? - end - def to_ary; end - end.new(%w[one two three]) - - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, body] } - response = content_length(app).call(request) - expected = %w[one two three] - response[1]['Content-Length'].should.equal expected.join.size.to_s - response[2].to_enum.to_a.should.equal expected - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_content_type.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_content_type.rb deleted file mode 100644 index 308611b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_content_type.rb +++ /dev/null @@ -1,45 +0,0 @@ -require 'rack/content_type' -require 'rack/lint' -require 'rack/mock' - -describe Rack::ContentType do - def content_type(app, *args) - Rack::Lint.new Rack::ContentType.new(app, *args) - end - - def request - Rack::MockRequest.env_for - end - - should "set Content-Type to default text/html if none is set" do - app = lambda { |env| [200, {}, "Hello, World!"] } - headers = content_type(app).call(request)[1] - headers['Content-Type'].should.equal 'text/html' - end - - should "set Content-Type to chosen default if none is set" do - app = lambda { |env| [200, {}, "Hello, World!"] } - headers = - content_type(app, 'application/octet-stream').call(request)[1] - headers['Content-Type'].should.equal 'application/octet-stream' - end - - should "not change Content-Type if it is already set" do - app = lambda { |env| [200, {'Content-Type' => 'foo/bar'}, "Hello, World!"] } - headers = content_type(app).call(request)[1] - headers['Content-Type'].should.equal 'foo/bar' - end - - should "detect Content-Type case insensitive" do - app = lambda { |env| [200, {'CONTENT-Type' => 'foo/bar'}, "Hello, World!"] } - headers = content_type(app).call(request)[1] - headers.to_a.select { |k,v| k.downcase == "content-type" }. - should.equal [["CONTENT-Type","foo/bar"]] - end - - should "not set Content-Type on 304 responses" do - app = lambda { |env| [304, {}, []] } - response = content_type(app, "text/html").call(request) - response[1]['Content-Type'].should.equal nil - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_deflater.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_deflater.rb deleted file mode 100644 index 6f5137c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_deflater.rb +++ /dev/null @@ -1,204 +0,0 @@ -require 'stringio' -require 'time' # for Time#httpdate -require 'rack/deflater' -require 'rack/lint' -require 'rack/mock' -require 'zlib' - -describe Rack::Deflater do - def deflater(app) - Rack::Lint.new Rack::Deflater.new(app) - end - - def build_response(status, body, accept_encoding, headers = {}) - body = [body] if body.respond_to? :to_str - app = lambda do |env| - res = [status, {}, body] - res[1]["Content-Type"] = "text/plain" unless res[0] == 304 - res - end - request = Rack::MockRequest.env_for("", headers.merge("HTTP_ACCEPT_ENCODING" => accept_encoding)) - response = deflater(app).call(request) - - return response - end - - def inflate(buf) - inflater = Zlib::Inflate.new(-Zlib::MAX_WBITS) - inflater.inflate(buf) << inflater.finish - end - - should "be able to deflate bodies that respond to each" do - body = Object.new - class << body; def each; yield("foo"); yield("bar"); end; end - - response = build_response(200, body, "deflate") - - response[0].should.equal(200) - response[1].should.equal({ - "Content-Encoding" => "deflate", - "Vary" => "Accept-Encoding", - "Content-Type" => "text/plain" - }) - buf = '' - response[2].each { |part| buf << part } - inflate(buf).should.equal("foobar") - end - - should "flush deflated chunks to the client as they become ready" do - body = Object.new - class << body; def each; yield("foo"); yield("bar"); end; end - - response = build_response(200, body, "deflate") - - response[0].should.equal(200) - response[1].should.equal({ - "Content-Encoding" => "deflate", - "Vary" => "Accept-Encoding", - "Content-Type" => "text/plain" - }) - buf = [] - inflater = Zlib::Inflate.new(-Zlib::MAX_WBITS) - response[2].each { |part| buf << inflater.inflate(part) } - buf << inflater.finish - buf.delete_if { |part| part.empty? } - buf.join.should.equal("foobar") - end - - # TODO: This is really just a special case of the above... - should "be able to deflate String bodies" do - response = build_response(200, "Hello world!", "deflate") - - response[0].should.equal(200) - response[1].should.equal({ - "Content-Encoding" => "deflate", - "Vary" => "Accept-Encoding", - "Content-Type" => "text/plain" - }) - buf = '' - response[2].each { |part| buf << part } - inflate(buf).should.equal("Hello world!") - end - - should "be able to gzip bodies that respond to each" do - body = Object.new - class << body; def each; yield("foo"); yield("bar"); end; end - - response = build_response(200, body, "gzip") - - response[0].should.equal(200) - response[1].should.equal({ - "Content-Encoding" => "gzip", - "Vary" => "Accept-Encoding", - "Content-Type" => "text/plain" - }) - - buf = '' - response[2].each { |part| buf << part } - io = StringIO.new(buf) - gz = Zlib::GzipReader.new(io) - gz.read.should.equal("foobar") - gz.close - end - - should "flush gzipped chunks to the client as they become ready" do - body = Object.new - class << body; def each; yield("foo"); yield("bar"); end; end - - response = build_response(200, body, "gzip") - - response[0].should.equal(200) - response[1].should.equal({ - "Content-Encoding" => "gzip", - "Vary" => "Accept-Encoding", - "Content-Type" => "text/plain" - }) - buf = [] - inflater = Zlib::Inflate.new(Zlib::MAX_WBITS + 32) - response[2].each { |part| buf << inflater.inflate(part) } - buf << inflater.finish - buf.delete_if { |part| part.empty? } - buf.join.should.equal("foobar") - end - - should "be able to fallback to no deflation" do - response = build_response(200, "Hello world!", "superzip") - - response[0].should.equal(200) - response[1].should.equal({ "Vary" => "Accept-Encoding", "Content-Type" => "text/plain" }) - response[2].to_enum.to_a.should.equal(["Hello world!"]) - end - - should "be able to skip when there is no response entity body" do - response = build_response(304, [], "gzip") - - response[0].should.equal(304) - response[1].should.equal({}) - response[2].to_enum.to_a.should.equal([]) - end - - should "handle the lack of an acceptable encoding" do - response1 = build_response(200, "Hello world!", "identity;q=0", "PATH_INFO" => "/") - response1[0].should.equal(406) - response1[1].should.equal({"Content-Type" => "text/plain", "Content-Length" => "71"}) - response1[2].to_enum.to_a.should.equal(["An acceptable encoding for the requested resource / could not be found."]) - - response2 = build_response(200, "Hello world!", "identity;q=0", "SCRIPT_NAME" => "/foo", "PATH_INFO" => "/bar") - response2[0].should.equal(406) - response2[1].should.equal({"Content-Type" => "text/plain", "Content-Length" => "78"}) - response2[2].to_enum.to_a.should.equal(["An acceptable encoding for the requested resource /foo/bar could not be found."]) - end - - should "handle gzip response with Last-Modified header" do - last_modified = Time.now.httpdate - - app = lambda { |env| [200, { "Content-Type" => "text/plain", "Last-Modified" => last_modified }, ["Hello World!"]] } - request = Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => "gzip") - response = deflater(app).call(request) - - response[0].should.equal(200) - response[1].should.equal({ - "Content-Encoding" => "gzip", - "Vary" => "Accept-Encoding", - "Last-Modified" => last_modified, - "Content-Type" => "text/plain" - }) - - buf = '' - response[2].each { |part| buf << part } - io = StringIO.new(buf) - gz = Zlib::GzipReader.new(io) - gz.read.should.equal("Hello World!") - gz.close - end - - should "do nothing when no-transform Cache-Control directive present" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Cache-Control' => 'no-transform'}, ['Hello World!']] } - request = Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => "gzip") - response = deflater(app).call(request) - - response[0].should.equal(200) - response[1].should.not.include "Content-Encoding" - response[2].to_enum.to_a.join.should.equal("Hello World!") - end - - should "do nothing when Content-Encoding already present" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Content-Encoding' => 'gzip'}, ['Hello World!']] } - request = Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => "gzip") - response = deflater(app).call(request) - - response[0].should.equal(200) - response[2].to_enum.to_a.join.should.equal("Hello World!") - end - - should "deflate when Content-Encoding is identity" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Content-Encoding' => 'identity'}, ['Hello World!']] } - request = Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => "deflate") - response = deflater(app).call(request) - - response[0].should.equal(200) - buf = '' - response[2].each { |part| buf << part } - inflate(buf).should.equal("Hello World!") - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_directory.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_directory.rb deleted file mode 100644 index d41ef67..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_directory.rb +++ /dev/null @@ -1,88 +0,0 @@ -require 'rack/directory' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Directory do - DOCROOT = File.expand_path(File.dirname(__FILE__)) unless defined? DOCROOT - FILE_CATCH = proc{|env| [200, {'Content-Type'=>'text/plain', "Content-Length" => "7"}, ['passed!']] } - app = Rack::Lint.new(Rack::Directory.new(DOCROOT, FILE_CATCH)) - - should "serve directory indices" do - res = Rack::MockRequest.new(Rack::Lint.new(app)). - get("/cgi/") - - res.should.be.ok - res.should =~ // - end - - should "pass to app if file found" do - res = Rack::MockRequest.new(Rack::Lint.new(app)). - get("/cgi/test") - - res.should.be.ok - res.should =~ /passed!/ - end - - should "serve uri with URL encoded filenames" do - res = Rack::MockRequest.new(Rack::Lint.new(app)). - get("/%63%67%69/") # "/cgi/test" - - res.should.be.ok - res.should =~ // - - res = Rack::MockRequest.new(Rack::Lint.new(app)). - get("/cgi/%74%65%73%74") # "/cgi/test" - - res.should.be.ok - res.should =~ /passed!/ - end - - should "not allow directory traversal" do - res = Rack::MockRequest.new(Rack::Lint.new(app)). - get("/cgi/../test") - - res.should.be.forbidden - - res = Rack::MockRequest.new(Rack::Lint.new(app)). - get("/cgi/%2E%2E/test") - - res.should.be.forbidden - end - - should "404 if it can't find the file" do - res = Rack::MockRequest.new(Rack::Lint.new(app)). - get("/cgi/blubb") - - res.should.be.not_found - end - - should "uri escape path parts" do # #265, properly escape file names - mr = Rack::MockRequest.new(Rack::Lint.new(app)) - - res = mr.get("/cgi/test%2bdirectory") - - res.should.be.ok - res.body.should =~ %r[/cgi/test%2Bdirectory/test%2Bfile] - - res = mr.get("/cgi/test%2bdirectory/test%2bfile") - res.should.be.ok - end - - should "correctly escape script name" do - app2 = Rack::Builder.new do - map '/script-path' do - run app - end - end - - mr = Rack::MockRequest.new(Rack::Lint.new(app2)) - - res = mr.get("/script-path/cgi/test%2bdirectory") - - res.should.be.ok - res.body.should =~ %r[/script-path/cgi/test%2Bdirectory/test%2Bfile] - - res = mr.get("/script-path/cgi/test%2bdirectory/test%2bfile") - res.should.be.ok - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_etag.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_etag.rb deleted file mode 100644 index d7f0350..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_etag.rb +++ /dev/null @@ -1,98 +0,0 @@ -require 'rack/etag' -require 'rack/lint' -require 'rack/mock' -require 'time' - -describe Rack::ETag do - def etag(app, *args) - Rack::Lint.new Rack::ETag.new(app, *args) - end - - def request - Rack::MockRequest.env_for - end - - def sendfile_body - res = ['Hello World'] - def res.to_path ; "/tmp/hello.txt" ; end - res - end - - should "set ETag if none is set if status is 200" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] } - response = etag(app).call(request) - response[1]['ETag'].should.equal "\"65a8e27d8879283831b664bd8b7f0ad4\"" - end - - should "set ETag if none is set if status is 201" do - app = lambda { |env| [201, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] } - response = etag(app).call(request) - response[1]['ETag'].should.equal "\"65a8e27d8879283831b664bd8b7f0ad4\"" - end - - should "set Cache-Control to 'max-age=0, private, must-revalidate' (default) if none is set" do - app = lambda { |env| [201, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] } - response = etag(app).call(request) - response[1]['Cache-Control'].should.equal 'max-age=0, private, must-revalidate' - end - - should "set Cache-Control to chosen one if none is set" do - app = lambda { |env| [201, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] } - response = etag(app, nil, 'public').call(request) - response[1]['Cache-Control'].should.equal 'public' - end - - should "set a given Cache-Control even if digest could not be calculated" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, []] } - response = etag(app, 'no-cache').call(request) - response[1]['Cache-Control'].should.equal 'no-cache' - end - - should "not set Cache-Control if it is already set" do - app = lambda { |env| [201, {'Content-Type' => 'text/plain', 'Cache-Control' => 'public'}, ["Hello, World!"]] } - response = etag(app).call(request) - response[1]['Cache-Control'].should.equal 'public' - end - - should "not set Cache-Control if directive isn't present" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] } - response = etag(app, nil, nil).call(request) - response[1]['Cache-Control'].should.equal nil - end - - should "not change ETag if it is already set" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'ETag' => '"abc"'}, ["Hello, World!"]] } - response = etag(app).call(request) - response[1]['ETag'].should.equal "\"abc\"" - end - - should "not set ETag if body is empty" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Last-Modified' => Time.now.httpdate}, []] } - response = etag(app).call(request) - response[1]['ETag'].should.be.nil - end - - should "not set ETag if Last-Modified is set" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Last-Modified' => Time.now.httpdate}, ["Hello, World!"]] } - response = etag(app).call(request) - response[1]['ETag'].should.be.nil - end - - should "not set ETag if a sendfile_body is given" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, sendfile_body] } - response = etag(app).call(request) - response[1]['ETag'].should.be.nil - end - - should "not set ETag if a status is not 200 or 201" do - app = lambda { |env| [401, {'Content-Type' => 'text/plain'}, ['Access denied.']] } - response = etag(app).call(request) - response[1]['ETag'].should.be.nil - end - - should "not set ETag if no-cache is given" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', 'Cache-Control' => 'no-cache, must-revalidate'}, ['Hello, World!']] } - response = etag(app).call(request) - response[1]['ETag'].should.be.nil - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_fastcgi.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_fastcgi.rb deleted file mode 100644 index 14594a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_fastcgi.rb +++ /dev/null @@ -1,107 +0,0 @@ -begin -require File.expand_path('../testrequest', __FILE__) -require 'rack/handler/fastcgi' - -describe Rack::Handler::FastCGI do - extend TestRequest::Helpers - - @host = '127.0.0.1' - @port = 9203 - - if `which lighttpd` && !$?.success? - raise "lighttpd not found" - end - - # Keep this first. - $pid = fork { - ENV['RACK_ENV'] = 'deployment' - ENV['RUBYLIB'] = [ - File.expand_path('../../lib', __FILE__), - ENV['RUBYLIB'], - ].compact.join(':') - - Dir.chdir(File.expand_path("../cgi", __FILE__)) do - exec "lighttpd -D -f lighttpd.conf" - end - } - - should "respond" do - sleep 1 - GET("/test") - response.should.not.be.nil - end - - should "respond via rackup server" do - GET("/sample_rackup.ru") - status.should.equal 200 - end - - should "be a lighttpd" do - GET("/test.fcgi") - status.should.equal 200 - response["SERVER_SOFTWARE"].should =~ /lighttpd/ - response["HTTP_VERSION"].should.equal "HTTP/1.1" - response["SERVER_PROTOCOL"].should.equal "HTTP/1.1" - response["SERVER_PORT"].should.equal @port.to_s - response["SERVER_NAME"].should.equal @host - end - - should "have rack headers" do - GET("/test.fcgi") - response["rack.version"].should.equal [1,2] - response["rack.multithread"].should.be.false - response["rack.multiprocess"].should.be.true - response["rack.run_once"].should.be.false - end - - should "have CGI headers on GET" do - GET("/test.fcgi") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test.fcgi" - response["REQUEST_PATH"].should.equal "/" - response["PATH_INFO"].should.equal "" - response["QUERY_STRING"].should.equal "" - response["test.postdata"].should.equal "" - - GET("/test.fcgi/foo?quux=1") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test.fcgi" - response["REQUEST_PATH"].should.equal "/" - response["PATH_INFO"].should.equal "/foo" - response["QUERY_STRING"].should.equal "quux=1" - end - - should "have CGI headers on POST" do - POST("/test.fcgi", {"rack-form-data" => "23"}, {'X-test-header' => '42'}) - status.should.equal 200 - response["REQUEST_METHOD"].should.equal "POST" - response["SCRIPT_NAME"].should.equal "/test.fcgi" - response["REQUEST_PATH"].should.equal "/" - response["QUERY_STRING"].should.equal "" - response["HTTP_X_TEST_HEADER"].should.equal "42" - response["test.postdata"].should.equal "rack-form-data=23" - end - - should "support HTTP auth" do - GET("/test.fcgi", {:user => "ruth", :passwd => "secret"}) - response["HTTP_AUTHORIZATION"].should.equal "Basic cnV0aDpzZWNyZXQ=" - end - - should "set status" do - GET("/test.fcgi?secret") - status.should.equal 403 - response["rack.url_scheme"].should.equal "http" - end - - # Keep this last. - should "shutdown" do - Process.kill 15, $pid - Process.wait($pid).should.equal $pid - end -end - -rescue RuntimeError - $stderr.puts "Skipping Rack::Handler::FastCGI tests (lighttpd is required). Install lighttpd and try again." -rescue LoadError - $stderr.puts "Skipping Rack::Handler::FastCGI tests (FCGI is required). `gem install fcgi` and try again." -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_file.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_file.rb deleted file mode 100644 index c9d7a1b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_file.rb +++ /dev/null @@ -1,213 +0,0 @@ -require 'rack/file' -require 'rack/lint' -require 'rack/mock' - -describe Rack::File do - DOCROOT = File.expand_path(File.dirname(__FILE__)) unless defined? DOCROOT - - def file(*args) - Rack::Lint.new Rack::File.new(*args) - end - - should "serve files" do - res = Rack::MockRequest.new(file(DOCROOT)).get("/cgi/test") - - res.should.be.ok - res.should =~ /ruby/ - end - - should "set Last-Modified header" do - res = Rack::MockRequest.new(file(DOCROOT)).get("/cgi/test") - - path = File.join(DOCROOT, "/cgi/test") - - res.should.be.ok - res["Last-Modified"].should.equal File.mtime(path).httpdate - end - - should "return 304 if file isn't modified since last serve" do - path = File.join(DOCROOT, "/cgi/test") - res = Rack::MockRequest.new(file(DOCROOT)). - get("/cgi/test", 'HTTP_IF_MODIFIED_SINCE' => File.mtime(path).httpdate) - - res.status.should.equal 304 - res.body.should.be.empty - end - - should "return the file if it's modified since last serve" do - path = File.join(DOCROOT, "/cgi/test") - res = Rack::MockRequest.new(file(DOCROOT)). - get("/cgi/test", 'HTTP_IF_MODIFIED_SINCE' => (File.mtime(path) - 100).httpdate) - - res.should.be.ok - end - - should "serve files with URL encoded filenames" do - res = Rack::MockRequest.new(file(DOCROOT)).get("/cgi/%74%65%73%74") # "/cgi/test" - - res.should.be.ok - res.should =~ /ruby/ - end - - should "allow safe directory traversal" do - req = Rack::MockRequest.new(file(DOCROOT)) - - res = req.get('/cgi/../cgi/test') - res.should.be.successful - - res = req.get('.') - res.should.be.not_found - - res = req.get("test/..") - res.should.be.not_found - end - - should "not allow unsafe directory traversal" do - req = Rack::MockRequest.new(file(DOCROOT)) - - res = req.get("/../README.rdoc") - res.should.be.client_error - - res = req.get("../test/spec_file.rb") - res.should.be.client_error - - res = req.get("../README.rdoc") - res.should.be.client_error - - res.should.be.not_found - end - - should "allow files with .. in their name" do - req = Rack::MockRequest.new(file(DOCROOT)) - res = req.get("/cgi/..test") - res.should.be.not_found - - res = req.get("/cgi/test..") - res.should.be.not_found - - res = req.get("/cgi../test..") - res.should.be.not_found - end - - should "not allow unsafe directory traversal with encoded periods" do - res = Rack::MockRequest.new(file(DOCROOT)).get("/%2E%2E/README") - - res.should.be.client_error? - res.should.be.not_found - end - - should "allow safe directory traversal with encoded periods" do - res = Rack::MockRequest.new(file(DOCROOT)).get("/cgi/%2E%2E/cgi/test") - - res.should.be.successful - end - - should "404 if it can't find the file" do - res = Rack::MockRequest.new(file(DOCROOT)).get("/cgi/blubb") - - res.should.be.not_found - end - - should "detect SystemCallErrors" do - res = Rack::MockRequest.new(file(DOCROOT)).get("/cgi") - - res.should.be.not_found - end - - should "return bodies that respond to #to_path" do - env = Rack::MockRequest.env_for("/cgi/test") - status, _, body = Rack::File.new(DOCROOT).call(env) - - path = File.join(DOCROOT, "/cgi/test") - - status.should.equal 200 - body.should.respond_to :to_path - body.to_path.should.equal path - end - - should "return correct byte range in body" do - env = Rack::MockRequest.env_for("/cgi/test") - env["HTTP_RANGE"] = "bytes=22-33" - res = Rack::MockResponse.new(*file(DOCROOT).call(env)) - - res.status.should.equal 206 - res["Content-Length"].should.equal "12" - res["Content-Range"].should.equal "bytes 22-33/193" - res.body.should.equal "-*- ruby -*-" - end - - should "return error for unsatisfiable byte range" do - env = Rack::MockRequest.env_for("/cgi/test") - env["HTTP_RANGE"] = "bytes=1234-5678" - res = Rack::MockResponse.new(*file(DOCROOT).call(env)) - - res.status.should.equal 416 - res["Content-Range"].should.equal "bytes */193" - end - - should "support custom http headers" do - env = Rack::MockRequest.env_for("/cgi/test") - status, heads, _ = file(DOCROOT, 'Cache-Control' => 'public, max-age=38', - 'Access-Control-Allow-Origin' => '*').call(env) - - status.should.equal 200 - heads['Cache-Control'].should.equal 'public, max-age=38' - heads['Access-Control-Allow-Origin'].should.equal '*' - end - - should "support not add custom http headers if none are supplied" do - env = Rack::MockRequest.env_for("/cgi/test") - status, heads, _ = file(DOCROOT).call(env) - - status.should.equal 200 - heads['Cache-Control'].should.equal nil - heads['Access-Control-Allow-Origin'].should.equal nil - end - - should "only support GET and HEAD requests" do - req = Rack::MockRequest.new(file(DOCROOT)) - - forbidden = %w[post put patch delete] - forbidden.each do |method| - - res = req.send(method, "/cgi/test") - res.should.be.client_error - res.should.be.method_not_allowed - end - - allowed = %w[get head] - allowed.each do |method| - res = req.send(method, "/cgi/test") - res.should.be.successful - end - end - - should "set Content-Length correctly for HEAD requests" do - req = Rack::MockRequest.new(Rack::Lint.new(Rack::File.new(DOCROOT))) - res = req.head "/cgi/test" - res.should.be.successful - res['Content-Length'].should.equal "193" - end - - should "default to a mime type of text/plain" do - req = Rack::MockRequest.new(Rack::Lint.new(Rack::File.new(DOCROOT))) - res = req.get "/cgi/test" - res.should.be.successful - res['Content-Type'].should.equal "text/plain" - end - - should "allow the default mime type to be set" do - req = Rack::MockRequest.new(Rack::Lint.new(Rack::File.new(DOCROOT, nil, 'application/octet-stream'))) - res = req.get "/cgi/test" - res.should.be.successful - res['Content-Type'].should.equal "application/octet-stream" - end - - should "not set Content-Type if the mime type is not set" do - req = Rack::MockRequest.new(Rack::Lint.new(Rack::File.new(DOCROOT, nil, nil))) - res = req.get "/cgi/test" - res.should.be.successful - res['Content-Type'].should.equal nil - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_handler.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_handler.rb deleted file mode 100644 index e8f41fd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_handler.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'rack/handler' - -class Rack::Handler::Lobster; end -class RockLobster; end - -describe Rack::Handler do - it "has registered default handlers" do - Rack::Handler.get('cgi').should.equal Rack::Handler::CGI - Rack::Handler.get('webrick').should.equal Rack::Handler::WEBrick - - begin - Rack::Handler.get('fastcgi').should.equal Rack::Handler::FastCGI - rescue LoadError - end - - begin - Rack::Handler.get('mongrel').should.equal Rack::Handler::Mongrel - rescue LoadError - end - end - - should "raise LoadError if handler doesn't exist" do - lambda { - Rack::Handler.get('boom') - }.should.raise(LoadError) - end - - should "get unregistered, but already required, handler by name" do - Rack::Handler.get('Lobster').should.equal Rack::Handler::Lobster - end - - should "register custom handler" do - Rack::Handler.register('rock_lobster', 'RockLobster') - Rack::Handler.get('rock_lobster').should.equal RockLobster - end - - should "not need registration for properly coded handlers even if not already required" do - begin - $LOAD_PATH.push File.expand_path('../unregistered_handler', __FILE__) - Rack::Handler.get('Unregistered').should.equal Rack::Handler::Unregistered - lambda { - Rack::Handler.get('UnRegistered') - }.should.raise LoadError - Rack::Handler.get('UnregisteredLongOne').should.equal Rack::Handler::UnregisteredLongOne - ensure - $LOAD_PATH.delete File.expand_path('../unregistered_handler', __FILE__) - end - end - - should "allow autoloaded handlers to be registered properly while being loaded" do - path = File.expand_path('../registering_handler', __FILE__) - begin - $LOAD_PATH.push path - Rack::Handler.get('registering_myself').should.equal Rack::Handler::RegisteringMyself - ensure - $LOAD_PATH.delete path - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_head.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_head.rb deleted file mode 100644 index 18f9a76..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_head.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'rack/head' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Head do - - def test_response(headers = {}) - body = StringIO.new "foo" - app = lambda do |env| - [200, {"Content-type" => "test/plain", "Content-length" => "3"}, body] - end - request = Rack::MockRequest.env_for("/", headers) - response = Rack::Lint.new(Rack::Head.new(app)).call(request) - - return response, body - end - - should "pass GET, POST, PUT, DELETE, OPTIONS, TRACE requests" do - %w[GET POST PUT DELETE OPTIONS TRACE].each do |type| - resp, _ = test_response("REQUEST_METHOD" => type) - - resp[0].should.equal(200) - resp[1].should.equal({"Content-type" => "test/plain", "Content-length" => "3"}) - resp[2].to_enum.to_a.should.equal(["foo"]) - end - end - - should "remove body from HEAD requests" do - resp, _ = test_response("REQUEST_METHOD" => "HEAD") - - resp[0].should.equal(200) - resp[1].should.equal({"Content-type" => "test/plain", "Content-length" => "3"}) - resp[2].to_enum.to_a.should.equal([]) - end - - should "close the body when it is removed" do - resp, body = test_response("REQUEST_METHOD" => "HEAD") - resp[0].should.equal(200) - resp[1].should.equal({"Content-type" => "test/plain", "Content-length" => "3"}) - resp[2].to_enum.to_a.should.equal([]) - body.should.be.closed - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lint.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lint.rb deleted file mode 100644 index fb60b7e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lint.rb +++ /dev/null @@ -1,522 +0,0 @@ -require 'stringio' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Lint do - def env(*args) - Rack::MockRequest.env_for("/", *args) - end - - should "pass valid request" do - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Content-type" => "test/plain", "Content-length" => "3"}, ["foo"]] - }).call(env({})) - }.should.not.raise - end - - should "notice fatal errors" do - lambda { Rack::Lint.new(nil).call }.should.raise(Rack::Lint::LintError). - message.should.match(/No env given/) - end - - should "notice environment errors" do - lambda { Rack::Lint.new(nil).call 5 }.should.raise(Rack::Lint::LintError). - message.should.match(/not a Hash/) - - lambda { - e = env - e.delete("REQUEST_METHOD") - Rack::Lint.new(nil).call(e) - }.should.raise(Rack::Lint::LintError). - message.should.match(/missing required key REQUEST_METHOD/) - - lambda { - e = env - e.delete("SERVER_NAME") - Rack::Lint.new(nil).call(e) - }.should.raise(Rack::Lint::LintError). - message.should.match(/missing required key SERVER_NAME/) - - - lambda { - Rack::Lint.new(nil).call(env("HTTP_CONTENT_TYPE" => "text/plain")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/contains HTTP_CONTENT_TYPE/) - - lambda { - Rack::Lint.new(nil).call(env("HTTP_CONTENT_LENGTH" => "42")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/contains HTTP_CONTENT_LENGTH/) - - lambda { - Rack::Lint.new(nil).call(env("FOO" => Object.new)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/non-string value/) - - lambda { - Rack::Lint.new(nil).call(env("rack.version" => "0.2")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must be an Array/) - - lambda { - Rack::Lint.new(nil).call(env("rack.url_scheme" => "gopher")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/url_scheme unknown/) - - lambda { - Rack::Lint.new(nil).call(env("rack.session" => [])) - }.should.raise(Rack::Lint::LintError). - message.should.equal("session [] must respond to store and []=") - - lambda { - Rack::Lint.new(nil).call(env("rack.logger" => [])) - }.should.raise(Rack::Lint::LintError). - message.should.equal("logger [] must respond to info") - - lambda { - Rack::Lint.new(nil).call(env("REQUEST_METHOD" => "FUCKUP?")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/REQUEST_METHOD/) - - lambda { - Rack::Lint.new(nil).call(env("SCRIPT_NAME" => "howdy")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must start with/) - - lambda { - Rack::Lint.new(nil).call(env("PATH_INFO" => "../foo")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must start with/) - - lambda { - Rack::Lint.new(nil).call(env("CONTENT_LENGTH" => "xcii")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/Invalid CONTENT_LENGTH/) - - lambda { - e = env - e.delete("PATH_INFO") - e.delete("SCRIPT_NAME") - Rack::Lint.new(nil).call(e) - }.should.raise(Rack::Lint::LintError). - message.should.match(/One of .* must be set/) - - lambda { - Rack::Lint.new(nil).call(env("SCRIPT_NAME" => "/")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/cannot be .* make it ''/) - end - - should "notice input errors" do - lambda { - Rack::Lint.new(nil).call(env("rack.input" => "")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/does not respond to #gets/) - - lambda { - input = Object.new - def input.binmode? - false - end - Rack::Lint.new(nil).call(env("rack.input" => input)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/is not opened in binary mode/) - - lambda { - input = Object.new - def input.external_encoding - result = Object.new - def result.name - "US-ASCII" - end - result - end - Rack::Lint.new(nil).call(env("rack.input" => input)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/does not have ASCII-8BIT as its external encoding/) - end - - should "notice error errors" do - lambda { - Rack::Lint.new(nil).call(env("rack.errors" => "")) - }.should.raise(Rack::Lint::LintError). - message.should.match(/does not respond to #puts/) - end - - should "notice status errors" do - lambda { - Rack::Lint.new(lambda { |env| - ["cc", {}, ""] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must be >=100 seen as integer/) - - lambda { - Rack::Lint.new(lambda { |env| - [42, {}, ""] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must be >=100 seen as integer/) - end - - should "notice header errors" do - lambda { - Rack::Lint.new(lambda { |env| - [200, Object.new, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.equal("headers object should respond to #each, but doesn't (got Object as headers)") - - lambda { - Rack::Lint.new(lambda { |env| - [200, {true=>false}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.equal("header key must be a string, was TrueClass") - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Status" => "404"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must not contain Status/) - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Content-Type:" => "text/plain"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must not contain :/) - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Content-" => "text/plain"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/must not end/) - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"..%%quark%%.." => "text/plain"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.equal("invalid header name: ..%%quark%%..") - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Foo" => Object.new}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.equal("a header value must be a String, but the value of 'Foo' is a Object") - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Foo" => [1, 2, 3]}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.equal("a header value must be a String, but the value of 'Foo' is a Array") - - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Foo-Bar" => "text\000plain"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/invalid header/) - - # line ends (010) should be allowed in header values. - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Foo-Bar" => "one\ntwo\nthree", "Content-Length" => "0", "Content-Type" => "text/plain" }, []] - }).call(env({})) - }.should.not.raise(Rack::Lint::LintError) - - # non-Hash header responses should be allowed - lambda { - Rack::Lint.new(lambda { |env| - [200, [%w(Content-Type text/plain), %w(Content-Length 0)], []] - }).call(env({})) - }.should.not.raise(TypeError) - end - - should "notice content-type errors" do - # lambda { - # Rack::Lint.new(lambda { |env| - # [200, {"Content-length" => "0"}, []] - # }).call(env({})) - # }.should.raise(Rack::Lint::LintError). - # message.should.match(/No Content-Type/) - - [100, 101, 204, 205, 304].each do |status| - lambda { - Rack::Lint.new(lambda { |env| - [status, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/Content-Type header found/) - end - end - - should "notice content-length errors" do - [100, 101, 204, 205, 304].each do |status| - lambda { - Rack::Lint.new(lambda { |env| - [status, {"Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/Content-Length header found/) - end - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Content-type" => "text/plain", "Content-Length" => "1"}, []] - }).call(env({}))[2].each { } - }.should.raise(Rack::Lint::LintError). - message.should.match(/Content-Length header was 1, but should be 0/) - end - - should "notice body errors" do - lambda { - body = Rack::Lint.new(lambda { |env| - [200, {"Content-type" => "text/plain","Content-length" => "3"}, [1,2,3]] - }).call(env({}))[2] - body.each { |part| } - }.should.raise(Rack::Lint::LintError). - message.should.match(/yielded non-string/) - end - - should "notice input handling errors" do - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].gets("\r\n") - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/gets called with arguments/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(1, 2, 3) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/read called with too many arguments/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read("foo") - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/read called with non-integer and non-nil length/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(-1) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/read called with a negative length/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(nil, nil) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/read called with non-String buffer/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(nil, 1) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/read called with non-String buffer/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].rewind(0) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/rewind called with arguments/) - - weirdio = Object.new - class << weirdio - def gets - 42 - end - - def read - 23 - end - - def each - yield 23 - yield 42 - end - - def rewind - raise Errno::ESPIPE, "Errno::ESPIPE" - end - end - - eof_weirdio = Object.new - class << eof_weirdio - def gets - nil - end - - def read(*args) - nil - end - - def each - end - - def rewind - end - end - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].gets - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env("rack.input" => weirdio)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/gets didn't return a String/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].each { |x| } - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env("rack.input" => weirdio)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/each didn't yield a String/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env("rack.input" => weirdio)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/read didn't return nil or a String/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env("rack.input" => eof_weirdio)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/read\(nil\) returned nil on EOF/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].rewind - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env("rack.input" => weirdio)) - }.should.raise(Rack::Lint::LintError). - message.should.match(/rewind raised Errno::ESPIPE/) - - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].close - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/close must not be called/) - end - - should "notice error handling errors" do - lambda { - Rack::Lint.new(lambda { |env| - env["rack.errors"].write(42) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/write not called with a String/) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.errors"].close - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({})) - }.should.raise(Rack::Lint::LintError). - message.should.match(/close must not be called/) - end - - should "notice HEAD errors" do - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Content-type" => "test/plain", "Content-length" => "3"}, []] - }).call(env({"REQUEST_METHOD" => "HEAD"})) - }.should.not.raise - - lambda { - Rack::Lint.new(lambda { |env| - [200, {"Content-type" => "test/plain", "Content-length" => "3"}, ["foo"]] - }).call(env({"REQUEST_METHOD" => "HEAD"}))[2].each { } - }.should.raise(Rack::Lint::LintError). - message.should.match(/body was given for HEAD/) - end - - should "pass valid read calls" do - hello_str = "hello world" - hello_str.force_encoding("ASCII-8BIT") if hello_str.respond_to? :force_encoding - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({"rack.input" => StringIO.new(hello_str)})) - }.should.not.raise(Rack::Lint::LintError) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(0) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({"rack.input" => StringIO.new(hello_str)})) - }.should.not.raise(Rack::Lint::LintError) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(1) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({"rack.input" => StringIO.new(hello_str)})) - }.should.not.raise(Rack::Lint::LintError) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(nil) - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({"rack.input" => StringIO.new(hello_str)})) - }.should.not.raise(Rack::Lint::LintError) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(nil, '') - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({"rack.input" => StringIO.new(hello_str)})) - }.should.not.raise(Rack::Lint::LintError) - - lambda { - Rack::Lint.new(lambda { |env| - env["rack.input"].read(1, '') - [201, {"Content-type" => "text/plain", "Content-length" => "0"}, []] - }).call(env({"rack.input" => StringIO.new(hello_str)})) - }.should.not.raise(Rack::Lint::LintError) - end -end - -describe "Rack::Lint::InputWrapper" do - should "delegate :rewind to underlying IO object" do - io = StringIO.new("123") - wrapper = Rack::Lint::InputWrapper.new(io) - wrapper.read.should.equal "123" - wrapper.read.should.equal "" - wrapper.rewind - wrapper.read.should.equal "123" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lobster.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lobster.rb deleted file mode 100644 index 56a5479..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lobster.rb +++ /dev/null @@ -1,58 +0,0 @@ -require 'rack/lobster' -require 'rack/lint' -require 'rack/mock' - -module LobsterHelpers - def lobster - Rack::MockRequest.new Rack::Lint.new(Rack::Lobster.new) - end - - def lambda_lobster - Rack::MockRequest.new Rack::Lint.new(Rack::Lobster::LambdaLobster) - end -end - -describe Rack::Lobster::LambdaLobster do - extend LobsterHelpers - - should "be a single lambda" do - Rack::Lobster::LambdaLobster.should.be.kind_of Proc - end - - should "look like a lobster" do - res = lambda_lobster.get("/") - res.should.be.ok - res.body.should.include "(,(,,(,,,(" - res.body.should.include "?flip" - end - - should "be flippable" do - res = lambda_lobster.get("/?flip") - res.should.be.ok - res.body.should.include "(,,,(,,(,(" - end -end - -describe Rack::Lobster do - extend LobsterHelpers - - should "look like a lobster" do - res = lobster.get("/") - res.should.be.ok - res.body.should.include "(,(,,(,,,(" - res.body.should.include "?flip" - res.body.should.include "crash" - end - - should "be flippable" do - res = lobster.get("/?flip=left") - res.should.be.ok - res.body.should.include "(,,,(,,(,(" - end - - should "provide crashing for testing purposes" do - lambda { - lobster.get("/?flip=crash") - }.should.raise - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lock.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lock.rb deleted file mode 100644 index 0cbb544..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_lock.rb +++ /dev/null @@ -1,164 +0,0 @@ -require 'rack/lint' -require 'rack/lock' -require 'rack/mock' - -class Lock - attr_reader :synchronized - - def initialize - @synchronized = false - end - - def synchronize - @synchronized = true - yield - end - - def lock - @synchronized = true - end - - def unlock - @synchronized = false - end -end - -module LockHelpers - def lock_app(app, lock = Lock.new) - app = if lock - Rack::Lock.new app, lock - else - Rack::Lock.new app - end - Rack::Lint.new app - end -end - -describe Rack::Lock do - extend LockHelpers - - describe 'Proxy' do - extend LockHelpers - - should 'delegate each' do - env = Rack::MockRequest.env_for("/") - response = Class.new { - attr_accessor :close_called - def initialize; @close_called = false; end - def each; %w{ hi mom }.each { |x| yield x }; end - }.new - - app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, response] }) - response = app.call(env)[2] - list = [] - response.each { |x| list << x } - list.should.equal %w{ hi mom } - end - - should 'delegate to_path' do - lock = Lock.new - env = Rack::MockRequest.env_for("/") - - res = ['Hello World'] - def res.to_path ; "/tmp/hello.txt" ; end - - app = Rack::Lock.new(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, res] }, lock) - body = app.call(env)[2] - - body.should.respond_to :to_path - body.to_path.should.equal "/tmp/hello.txt" - end - - should 'not delegate to_path if body does not implement it' do - env = Rack::MockRequest.env_for("/") - - res = ['Hello World'] - - app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, res] }) - body = app.call(env)[2] - - body.should.not.respond_to :to_path - end - end - - should 'call super on close' do - env = Rack::MockRequest.env_for("/") - response = Class.new { - attr_accessor :close_called - def initialize; @close_called = false; end - def close; @close_called = true; end - }.new - - app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, response] }) - app.call(env) - response.close_called.should.equal false - response.close - response.close_called.should.equal true - end - - should "not unlock until body is closed" do - lock = Lock.new - env = Rack::MockRequest.env_for("/") - response = Object.new - app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, response] }, lock) - lock.synchronized.should.equal false - response = app.call(env)[2] - lock.synchronized.should.equal true - response.close - lock.synchronized.should.equal false - end - - should "return value from app" do - env = Rack::MockRequest.env_for("/") - body = [200, {"Content-Type" => "text/plain"}, %w{ hi mom }] - app = lock_app(lambda { |inner_env| body }) - - res = app.call(env) - res[0].should.equal body[0] - res[1].should.equal body[1] - res[2].to_enum.to_a.should.equal ["hi", "mom"] - end - - should "call synchronize on lock" do - lock = Lock.new - env = Rack::MockRequest.env_for("/") - app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, %w{ a b c }] }, lock) - lock.synchronized.should.equal false - app.call(env) - lock.synchronized.should.equal true - end - - should "unlock if the app raises" do - lock = Lock.new - env = Rack::MockRequest.env_for("/") - app = lock_app(lambda { raise Exception }, lock) - lambda { app.call(env) }.should.raise(Exception) - lock.synchronized.should.equal false - end - - should "unlock if the app throws" do - lock = Lock.new - env = Rack::MockRequest.env_for("/") - app = lock_app(lambda {|_| throw :bacon }, lock) - lambda { app.call(env) }.should.throw(:bacon) - lock.synchronized.should.equal false - end - - should "set multithread flag to false" do - app = lock_app(lambda { |env| - env['rack.multithread'].should.equal false - [200, {"Content-Type" => "text/plain"}, %w{ a b c }] - }, false) - app.call(Rack::MockRequest.env_for("/")) - end - - should "reset original multithread flag when exiting lock" do - app = Class.new(Rack::Lock) { - def call(env) - env['rack.multithread'].should.equal true - super - end - }.new(lambda { |env| [200, {"Content-Type" => "text/plain"}, %w{ a b c }] }) - Rack::Lint.new(app).call(Rack::MockRequest.env_for("/")) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_logger.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_logger.rb deleted file mode 100644 index 2ff4408..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_logger.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'stringio' -require 'rack/lint' -require 'rack/logger' -require 'rack/mock' - -describe Rack::Logger do - app = lambda { |env| - log = env['rack.logger'] - log.debug("Created logger") - log.info("Program started") - log.warn("Nothing to do!") - - [200, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] - } - - should "conform to Rack::Lint" do - errors = StringIO.new - a = Rack::Lint.new(Rack::Logger.new(app)) - Rack::MockRequest.new(a).get('/', 'rack.errors' => errors) - errors.string.should.match(/INFO -- : Program started/) - errors.string.should.match(/WARN -- : Nothing to do/) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_methodoverride.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_methodoverride.rb deleted file mode 100644 index 16f5f28..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_methodoverride.rb +++ /dev/null @@ -1,75 +0,0 @@ -require 'stringio' -require 'rack/methodoverride' -require 'rack/mock' - -describe Rack::MethodOverride do - def app - Rack::Lint.new(Rack::MethodOverride.new(lambda {|e| - [200, {"Content-Type" => "text/plain"}, []] - })) - end - - should "not affect GET requests" do - env = Rack::MockRequest.env_for("/?_method=delete", :method => "GET") - app.call env - - env["REQUEST_METHOD"].should.equal "GET" - end - - should "modify REQUEST_METHOD for POST requests when _method parameter is set" do - env = Rack::MockRequest.env_for("/", :method => "POST", :input => "_method=put") - app.call env - - env["REQUEST_METHOD"].should.equal "PUT" - end - - should "modify REQUEST_METHOD for POST requests when X-HTTP-Method-Override is set" do - env = Rack::MockRequest.env_for("/", - :method => "POST", - "HTTP_X_HTTP_METHOD_OVERRIDE" => "PATCH" - ) - app.call env - - env["REQUEST_METHOD"].should.equal "PATCH" - end - - should "not modify REQUEST_METHOD if the method is unknown" do - env = Rack::MockRequest.env_for("/", :method => "POST", :input => "_method=foo") - app.call env - - env["REQUEST_METHOD"].should.equal "POST" - end - - should "not modify REQUEST_METHOD when _method is nil" do - env = Rack::MockRequest.env_for("/", :method => "POST", :input => "foo=bar") - app.call env - - env["REQUEST_METHOD"].should.equal "POST" - end - - should "store the original REQUEST_METHOD prior to overriding" do - env = Rack::MockRequest.env_for("/", - :method => "POST", - :input => "_method=options") - app.call env - - env["rack.methodoverride.original_method"].should.equal "POST" - end - - should "not modify REQUEST_METHOD when given invalid multipart form data" do - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size.to_s, - :method => "POST", :input => input) - begin - app.call env - rescue EOFError - end - - env["REQUEST_METHOD"].should.equal "POST" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mime.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mime.rb deleted file mode 100644 index 231bf35..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mime.rb +++ /dev/null @@ -1,51 +0,0 @@ -require 'rack/mime' - -describe Rack::Mime do - - it "should return the fallback mime-type for files with no extension" do - fallback = 'image/jpg' - Rack::Mime.mime_type(File.extname('no_ext'), fallback).should.equal fallback - end - - it "should always return 'application/octet-stream' for unknown file extensions" do - unknown_ext = File.extname('unknown_ext.abcdefg') - Rack::Mime.mime_type(unknown_ext).should.equal 'application/octet-stream' - end - - it "should return the mime-type for a given extension" do - # sanity check. it would be infeasible test every single mime-type. - Rack::Mime.mime_type(File.extname('image.jpg')).should.equal 'image/jpeg' - end - - it "should support null fallbacks" do - Rack::Mime.mime_type('.nothing', nil).should.equal nil - end - - it "should match exact mimes" do - Rack::Mime.match?('text/html', 'text/html').should.equal true - Rack::Mime.match?('text/html', 'text/meme').should.equal false - Rack::Mime.match?('text', 'text').should.equal true - Rack::Mime.match?('text', 'binary').should.equal false - end - - it "should match class wildcard mimes" do - Rack::Mime.match?('text/html', 'text/*').should.equal true - Rack::Mime.match?('text/plain', 'text/*').should.equal true - Rack::Mime.match?('application/json', 'text/*').should.equal false - Rack::Mime.match?('text/html', 'text').should.equal true - end - - it "should match full wildcards" do - Rack::Mime.match?('text/html', '*').should.equal true - Rack::Mime.match?('text/plain', '*').should.equal true - Rack::Mime.match?('text/html', '*/*').should.equal true - Rack::Mime.match?('text/plain', '*/*').should.equal true - end - - it "should match type wildcard mimes" do - Rack::Mime.match?('text/html', '*/html').should.equal true - Rack::Mime.match?('text/plain', '*/plain').should.equal true - end - -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mock.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mock.rb deleted file mode 100644 index f49b196..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mock.rb +++ /dev/null @@ -1,269 +0,0 @@ -require 'yaml' -require 'rack/lint' -require 'rack/mock' -require 'stringio' - -app = Rack::Lint.new(lambda { |env| - req = Rack::Request.new(env) - - env["mock.postdata"] = env["rack.input"].read - if req.GET["error"] - env["rack.errors"].puts req.GET["error"] - env["rack.errors"].flush - end - - body = req.head? ? "" : env.to_yaml - Rack::Response.new(body, - req.GET["status"] || 200, - "Content-Type" => "text/yaml").finish -}) - -describe Rack::MockRequest do - should "return a MockResponse" do - res = Rack::MockRequest.new(app).get("") - res.should.be.kind_of Rack::MockResponse - end - - should "be able to only return the environment" do - env = Rack::MockRequest.env_for("") - env.should.be.kind_of Hash - env.should.include "rack.version" - end - - should "provide sensible defaults" do - res = Rack::MockRequest.new(app).request - - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - env["SERVER_NAME"].should.equal "example.org" - env["SERVER_PORT"].should.equal "80" - env["QUERY_STRING"].should.equal "" - env["PATH_INFO"].should.equal "/" - env["SCRIPT_NAME"].should.equal "" - env["rack.url_scheme"].should.equal "http" - env["mock.postdata"].should.be.empty - end - - should "allow GET/POST/PUT/DELETE/HEAD" do - res = Rack::MockRequest.new(app).get("", :input => "foo") - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - - res = Rack::MockRequest.new(app).post("", :input => "foo") - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "POST" - - res = Rack::MockRequest.new(app).put("", :input => "foo") - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "PUT" - - res = Rack::MockRequest.new(app).patch("", :input => "foo") - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "PATCH" - - res = Rack::MockRequest.new(app).delete("", :input => "foo") - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "DELETE" - - Rack::MockRequest.env_for("/", :method => "HEAD")["REQUEST_METHOD"]. - should.equal "HEAD" - - Rack::MockRequest.env_for("/", :method => "OPTIONS")["REQUEST_METHOD"]. - should.equal "OPTIONS" - end - - should "set content length" do - env = Rack::MockRequest.env_for("/", :input => "foo") - env["CONTENT_LENGTH"].should.equal "3" - end - - should "allow posting" do - res = Rack::MockRequest.new(app).get("", :input => "foo") - env = YAML.load(res.body) - env["mock.postdata"].should.equal "foo" - - res = Rack::MockRequest.new(app).post("", :input => StringIO.new("foo")) - env = YAML.load(res.body) - env["mock.postdata"].should.equal "foo" - end - - should "use all parts of an URL" do - res = Rack::MockRequest.new(app). - get("https://bla.example.org:9292/meh/foo?bar") - res.should.be.kind_of Rack::MockResponse - - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - env["SERVER_NAME"].should.equal "bla.example.org" - env["SERVER_PORT"].should.equal "9292" - env["QUERY_STRING"].should.equal "bar" - env["PATH_INFO"].should.equal "/meh/foo" - env["rack.url_scheme"].should.equal "https" - end - - should "set SSL port and HTTP flag on when using https" do - res = Rack::MockRequest.new(app). - get("https://example.org/foo") - res.should.be.kind_of Rack::MockResponse - - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - env["SERVER_NAME"].should.equal "example.org" - env["SERVER_PORT"].should.equal "443" - env["QUERY_STRING"].should.equal "" - env["PATH_INFO"].should.equal "/foo" - env["rack.url_scheme"].should.equal "https" - env["HTTPS"].should.equal "on" - end - - should "prepend slash to uri path" do - res = Rack::MockRequest.new(app). - get("foo") - res.should.be.kind_of Rack::MockResponse - - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - env["SERVER_NAME"].should.equal "example.org" - env["SERVER_PORT"].should.equal "80" - env["QUERY_STRING"].should.equal "" - env["PATH_INFO"].should.equal "/foo" - env["rack.url_scheme"].should.equal "http" - end - - should "properly convert method name to an uppercase string" do - res = Rack::MockRequest.new(app).request(:get) - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - end - - should "accept params and build query string for GET requests" do - res = Rack::MockRequest.new(app).get("/foo?baz=2", :params => {:foo => {:bar => "1"}}) - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - env["QUERY_STRING"].should.include "baz=2" - env["QUERY_STRING"].should.include "foo[bar]=1" - env["PATH_INFO"].should.equal "/foo" - env["mock.postdata"].should.equal "" - end - - should "accept raw input in params for GET requests" do - res = Rack::MockRequest.new(app).get("/foo?baz=2", :params => "foo[bar]=1") - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "GET" - env["QUERY_STRING"].should.include "baz=2" - env["QUERY_STRING"].should.include "foo[bar]=1" - env["PATH_INFO"].should.equal "/foo" - env["mock.postdata"].should.equal "" - end - - should "accept params and build url encoded params for POST requests" do - res = Rack::MockRequest.new(app).post("/foo", :params => {:foo => {:bar => "1"}}) - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "POST" - env["QUERY_STRING"].should.equal "" - env["PATH_INFO"].should.equal "/foo" - env["CONTENT_TYPE"].should.equal "application/x-www-form-urlencoded" - env["mock.postdata"].should.equal "foo[bar]=1" - end - - should "accept raw input in params for POST requests" do - res = Rack::MockRequest.new(app).post("/foo", :params => "foo[bar]=1") - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "POST" - env["QUERY_STRING"].should.equal "" - env["PATH_INFO"].should.equal "/foo" - env["CONTENT_TYPE"].should.equal "application/x-www-form-urlencoded" - env["mock.postdata"].should.equal "foo[bar]=1" - end - - should "accept params and build multipart encoded params for POST requests" do - files = Rack::Multipart::UploadedFile.new(File.join(File.dirname(__FILE__), "multipart", "file1.txt")) - res = Rack::MockRequest.new(app).post("/foo", :params => { "submit-name" => "Larry", "files" => files }) - env = YAML.load(res.body) - env["REQUEST_METHOD"].should.equal "POST" - env["QUERY_STRING"].should.equal "" - env["PATH_INFO"].should.equal "/foo" - env["CONTENT_TYPE"].should.equal "multipart/form-data; boundary=AaB03x" - # The gsub accounts for differences in YAMLs affect on the data. - env["mock.postdata"].gsub("\r", "").length.should.equal 206 - end - - should "behave valid according to the Rack spec" do - lambda { - Rack::MockRequest.new(app). - get("https://bla.example.org:9292/meh/foo?bar", :lint => true) - }.should.not.raise(Rack::Lint::LintError) - end - - should "call close on the original body object" do - called = false - body = Rack::BodyProxy.new(['hi']) { called = true } - capp = proc { |e| [200, {'Content-Type' => 'text/plain'}, body] } - called.should.equal false - Rack::MockRequest.new(capp).get('/', :lint => true) - called.should.equal true - end -end - -describe Rack::MockResponse do - should "provide access to the HTTP status" do - res = Rack::MockRequest.new(app).get("") - res.should.be.successful - res.should.be.ok - - res = Rack::MockRequest.new(app).get("/?status=404") - res.should.not.be.successful - res.should.be.client_error - res.should.be.not_found - - res = Rack::MockRequest.new(app).get("/?status=501") - res.should.not.be.successful - res.should.be.server_error - - res = Rack::MockRequest.new(app).get("/?status=307") - res.should.be.redirect - - res = Rack::MockRequest.new(app).get("/?status=201", :lint => true) - res.should.be.empty - end - - should "provide access to the HTTP headers" do - res = Rack::MockRequest.new(app).get("") - res.should.include "Content-Type" - res.headers["Content-Type"].should.equal "text/yaml" - res.original_headers["Content-Type"].should.equal "text/yaml" - res["Content-Type"].should.equal "text/yaml" - res.content_type.should.equal "text/yaml" - res.content_length.should.not.equal 0 - res.location.should.be.nil - end - - should "provide access to the HTTP body" do - res = Rack::MockRequest.new(app).get("") - res.body.should =~ /rack/ - res.should =~ /rack/ - res.should.match(/rack/) - res.should.satisfy { |r| r.match(/rack/) } - end - - should "provide access to the Rack errors" do - res = Rack::MockRequest.new(app).get("/?error=foo", :lint => true) - res.should.be.ok - res.errors.should.not.be.empty - res.errors.should.include "foo" - end - - should "allow calling body.close afterwards" do - # this is exactly what rack-test does - body = StringIO.new("hi") - res = Rack::MockResponse.new(200, {}, body) - body.close if body.respond_to?(:close) - res.body.should == 'hi' - end - - should "optionally make Rack errors fatal" do - lambda { - Rack::MockRequest.new(app).get("/?error=foo", :fatal => true) - }.should.raise(Rack::MockRequest::FatalWarning) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mongrel.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mongrel.rb deleted file mode 100644 index e162cdc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_mongrel.rb +++ /dev/null @@ -1,182 +0,0 @@ -begin -require 'rack' -require 'rack/handler/mongrel' -require File.expand_path('../testrequest', __FILE__) -require 'timeout' - -Thread.abort_on_exception = true -$tcp_defer_accept_opts = nil -$tcp_cork_opts = nil - -describe Rack::Handler::Mongrel do - extend TestRequest::Helpers - - @server = Mongrel::HttpServer.new(@host='127.0.0.1', @port=9201) - @server.register('/test', - Rack::Handler::Mongrel.new(Rack::Lint.new(TestRequest.new))) - @server.register('/stream', - Rack::Handler::Mongrel.new(Rack::Lint.new(StreamingRequest))) - @acc = @server.run - - should "respond" do - lambda { - GET("/test") - }.should.not.raise - end - - should "be a Mongrel" do - GET("/test") - status.should.equal 200 - response["SERVER_SOFTWARE"].should =~ /Mongrel/ - response["HTTP_VERSION"].should.equal "HTTP/1.1" - response["SERVER_PROTOCOL"].should.equal "HTTP/1.1" - response["SERVER_PORT"].should.equal "9201" - response["SERVER_NAME"].should.equal "127.0.0.1" - end - - should "have rack headers" do - GET("/test") - response["rack.version"].should.equal [1,2] - response["rack.multithread"].should.be.true - response["rack.multiprocess"].should.be.false - response["rack.run_once"].should.be.false - end - - should "have CGI headers on GET" do - GET("/test") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/test" - response["PATH_INFO"].should.be.equal "" - response["QUERY_STRING"].should.equal "" - response["test.postdata"].should.equal "" - - GET("/test/foo?quux=1") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/test/foo" - response["PATH_INFO"].should.equal "/foo" - response["QUERY_STRING"].should.equal "quux=1" - end - - should "have CGI headers on POST" do - POST("/test", {"rack-form-data" => "23"}, {'X-test-header' => '42'}) - status.should.equal 200 - response["REQUEST_METHOD"].should.equal "POST" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/test" - response["QUERY_STRING"].should.equal "" - response["HTTP_X_TEST_HEADER"].should.equal "42" - response["test.postdata"].should.equal "rack-form-data=23" - end - - should "support HTTP auth" do - GET("/test", {:user => "ruth", :passwd => "secret"}) - response["HTTP_AUTHORIZATION"].should.equal "Basic cnV0aDpzZWNyZXQ=" - end - - should "set status" do - GET("/test?secret") - status.should.equal 403 - response["rack.url_scheme"].should.equal "http" - end - - should "provide a .run" do - block_ran = false - Thread.new { - Rack::Handler::Mongrel.run(lambda {}, {:Host => '127.0.0.1', :Port => 9211}) { |server| - server.should.be.kind_of Mongrel::HttpServer - block_ran = true - } - } - sleep 1 - block_ran.should.be.true - end - - should "provide a .run that maps a hash" do - block_ran = false - Thread.new { - map = {'/'=>lambda{},'/foo'=>lambda{}} - Rack::Handler::Mongrel.run(map, :map => true, :Host => '127.0.0.1', :Port => 9221) { |server| - server.should.be.kind_of Mongrel::HttpServer - server.classifier.uris.size.should.equal 2 - server.classifier.uris.should.not.include '/arf' - server.classifier.uris.should.include '/' - server.classifier.uris.should.include '/foo' - block_ran = true - } - } - sleep 1 - block_ran.should.be.true - end - - should "provide a .run that maps a urlmap" do - block_ran = false - Thread.new { - map = Rack::URLMap.new({'/'=>lambda{},'/bar'=>lambda{}}) - Rack::Handler::Mongrel.run(map, {:map => true, :Host => '127.0.0.1', :Port => 9231}) { |server| - server.should.be.kind_of Mongrel::HttpServer - server.classifier.uris.size.should.equal 2 - server.classifier.uris.should.not.include '/arf' - server.classifier.uris.should.include '/' - server.classifier.uris.should.include '/bar' - block_ran = true - } - } - sleep 1 - block_ran.should.be.true - end - - should "provide a .run that maps a urlmap restricting by host" do - block_ran = false - Thread.new { - map = Rack::URLMap.new({ - '/' => lambda{}, - '/foo' => lambda{}, - '/bar' => lambda{}, - 'http://127.0.0.1/' => lambda{}, - 'http://127.0.0.1/bar' => lambda{}, - 'http://falsehost/arf' => lambda{}, - 'http://falsehost/qux' => lambda{} - }) - opt = {:map => true, :Port => 9241, :Host => '127.0.0.1'} - Rack::Handler::Mongrel.run(map, opt) { |server| - server.should.be.kind_of Mongrel::HttpServer - server.classifier.uris.should.include '/' - server.classifier.handler_map['/'].size.should.equal 2 - server.classifier.uris.should.include '/foo' - server.classifier.handler_map['/foo'].size.should.equal 1 - server.classifier.uris.should.include '/bar' - server.classifier.handler_map['/bar'].size.should.equal 2 - server.classifier.uris.should.not.include '/qux' - server.classifier.uris.should.not.include '/arf' - server.classifier.uris.size.should.equal 3 - block_ran = true - } - } - sleep 1 - block_ran.should.be.true - end - - should "stream #each part of the response" do - body = '' - begin - Timeout.timeout(1) do - Net::HTTP.start(@host, @port) do |http| - get = Net::HTTP::Get.new('/stream') - http.request(get) do |response| - response.read_body { |part| body << part } - end - end - end - rescue Timeout::Error - end - body.should.not.be.empty - end - - @acc.raise Mongrel::StopServer -end - -rescue LoadError - warn "Skipping Rack::Handler::Mongrel tests (Mongrel is required). `gem install mongrel` and try again." -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_multipart.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_multipart.rb deleted file mode 100644 index bd0b07b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_multipart.rb +++ /dev/null @@ -1,445 +0,0 @@ -require 'rack/utils' -require 'rack/mock' - -describe Rack::Multipart do - def multipart_fixture(name, boundary = "AaB03x") - file = multipart_file(name) - data = File.open(file, 'rb') { |io| io.read } - - type = "multipart/form-data; boundary=#{boundary}" - length = data.respond_to?(:bytesize) ? data.bytesize : data.size - - { "CONTENT_TYPE" => type, - "CONTENT_LENGTH" => length.to_s, - :input => StringIO.new(data) } - end - - def multipart_file(name) - File.join(File.dirname(__FILE__), "multipart", name.to_s) - end - - should "return nil if content type is not multipart" do - env = Rack::MockRequest.env_for("/", - "CONTENT_TYPE" => 'application/x-www-form-urlencoded') - Rack::Multipart.parse_multipart(env).should.equal nil - end - - should "parse multipart content when content type present but filename is not" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:content_type_and_no_filename)) - params = Rack::Multipart.parse_multipart(env) - params["text"].should.equal "contents" - end - - should "raise RangeError if the key space is exhausted" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:content_type_and_no_filename)) - - old, Rack::Utils.key_space_limit = Rack::Utils.key_space_limit, 1 - begin - lambda { Rack::Multipart.parse_multipart(env) }.should.raise(RangeError) - ensure - Rack::Utils.key_space_limit = old - end - end - - should "parse multipart form webkit style" do - env = Rack::MockRequest.env_for '/', multipart_fixture(:webkit) - env['CONTENT_TYPE'] = "multipart/form-data; boundary=----WebKitFormBoundaryWLHCs9qmcJJoyjKR" - params = Rack::Multipart.parse_multipart(env) - params['profile']['bio'].should.include 'hello' - end - - should "reject insanely long boundaries" do - # using a pipe since a tempfile can use up too much space - rd, wr = IO.pipe - - # we only call rewind once at start, so make sure it succeeds - # and doesn't hit ESPIPE - def rd.rewind; end - wr.sync = true - - # mock out length to make this pipe look like a Tempfile - def rd.length - 1024 * 1024 * 8 - end - - # write to a pipe in a background thread, this will write a lot - # unless Rack (properly) shuts down the read end - thr = Thread.new do - begin - wr.write("--AaB03x") - - # make the initial boundary a few gigs long - longer = "0123456789" * 1024 * 1024 - (1024 * 1024).times { wr.write(longer) } - - wr.write("\r\n") - wr.write('Content-Disposition: form-data; name="a"; filename="a.txt"') - wr.write("\r\n") - wr.write("Content-Type: text/plain\r\n") - wr.write("\r\na") - wr.write("--AaB03x--\r\n") - wr.close - rescue => err # this is EPIPE if Rack shuts us down - err - end - end - - fixture = { - "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x", - "CONTENT_LENGTH" => rd.length.to_s, - :input => rd, - } - - env = Rack::MockRequest.env_for '/', fixture - lambda { - Rack::Multipart.parse_multipart(env) - }.should.raise(EOFError) - rd.close - - err = thr.value - err.should.be.instance_of Errno::EPIPE - wr.close - end - - should "parse multipart upload with text file" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:text)) - params = Rack::Multipart.parse_multipart(env) - params["submit-name"].should.equal "Larry" - params["submit-name-with-content"].should.equal "Berry" - params["files"][:type].should.equal "text/plain" - params["files"][:filename].should.equal "file1.txt" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; filename=\"file1.txt\"\r\n" + - "Content-Type: text/plain\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "parse multipart upload with nested parameters" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:nested)) - params = Rack::Multipart.parse_multipart(env) - params["foo"]["submit-name"].should.equal "Larry" - params["foo"]["files"][:type].should.equal "text/plain" - params["foo"]["files"][:filename].should.equal "file1.txt" - params["foo"]["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"foo[files]\"; filename=\"file1.txt\"\r\n" + - "Content-Type: text/plain\r\n" - params["foo"]["files"][:name].should.equal "foo[files]" - params["foo"]["files"][:tempfile].read.should.equal "contents" - end - - should "parse multipart upload with binary file" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:binary)) - params = Rack::Multipart.parse_multipart(env) - params["submit-name"].should.equal "Larry" - params["files"][:type].should.equal "image/png" - params["files"][:filename].should.equal "rack-logo.png" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; filename=\"rack-logo.png\"\r\n" + - "Content-Type: image/png\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.length.should.equal 26473 - end - - should "parse multipart upload with empty file" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:empty)) - params = Rack::Multipart.parse_multipart(env) - params["submit-name"].should.equal "Larry" - params["files"][:type].should.equal "text/plain" - params["files"][:filename].should.equal "file1.txt" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; filename=\"file1.txt\"\r\n" + - "Content-Type: text/plain\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "" - end - - should "parse multipart upload with filename with semicolons" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:semicolon)) - params = Rack::Multipart.parse_multipart(env) - params["files"][:type].should.equal "text/plain" - params["files"][:filename].should.equal "fi;le1.txt" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; filename=\"fi;le1.txt\"\r\n" + - "Content-Type: text/plain\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "not include file params if no file was selected" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:none)) - params = Rack::Multipart.parse_multipart(env) - params["submit-name"].should.equal "Larry" - params["files"].should.equal nil - params.keys.should.not.include "files" - end - - should "parse multipart/mixed" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:mixed_files)) - params = Rack::Utils::Multipart.parse_multipart(env) - params["foo"].should.equal "bar" - params["files"].should.be.instance_of String - params["files"].size.should.equal 252 - end - - should "parse IE multipart upload and clean up filename" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:ie)) - params = Rack::Multipart.parse_multipart(env) - params["files"][:type].should.equal "text/plain" - params["files"][:filename].should.equal "file1.txt" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; " + - 'filename="C:\Documents and Settings\Administrator\Desktop\file1.txt"' + - "\r\nContent-Type: text/plain\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "parse filename and modification param" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_and_modification_param)) - params = Rack::Multipart.parse_multipart(env) - params["files"][:type].should.equal "image/jpeg" - params["files"][:filename].should.equal "genome.jpeg" - params["files"][:head].should.equal "Content-Type: image/jpeg\r\n" + - "Content-Disposition: attachment; " + - "name=\"files\"; " + - "filename=genome.jpeg; " + - "modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";\r\n" + - "Content-Description: a complete map of the human genome\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "parse filename with escaped quotes" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_with_escaped_quotes)) - params = Rack::Multipart.parse_multipart(env) - params["files"][:type].should.equal "application/octet-stream" - params["files"][:filename].should.equal "escape \"quotes" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; " + - "filename=\"escape \\\"quotes\"\r\n" + - "Content-Type: application/octet-stream\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "parse filename with percent escaped quotes" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_with_percent_escaped_quotes)) - params = Rack::Multipart.parse_multipart(env) - params["files"][:type].should.equal "application/octet-stream" - params["files"][:filename].should.equal "escape \"quotes" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; " + - "filename=\"escape %22quotes\"\r\n" + - "Content-Type: application/octet-stream\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "parse filename with unescaped quotes" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_with_unescaped_quotes)) - params = Rack::Multipart.parse_multipart(env) - params["files"][:type].should.equal "application/octet-stream" - params["files"][:filename].should.equal "escape \"quotes" - params["files"][:head].should.equal "Content-Disposition: form-data; " + - "name=\"files\"; " + - "filename=\"escape \"quotes\"\r\n" + - "Content-Type: application/octet-stream\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "parse filename with escaped quotes and modification param" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_with_escaped_quotes_and_modification_param)) - params = Rack::Multipart.parse_multipart(env) - params["files"][:type].should.equal "image/jpeg" - params["files"][:filename].should.equal "\"human\" genome.jpeg" - params["files"][:head].should.equal "Content-Type: image/jpeg\r\n" + - "Content-Disposition: attachment; " + - "name=\"files\"; " + - "filename=\"\"human\" genome.jpeg\"; " + - "modification-date=\"Wed, 12 Feb 1997 16:29:51 -0500\";\r\n" + - "Content-Description: a complete map of the human genome\r\n" - params["files"][:name].should.equal "files" - params["files"][:tempfile].read.should.equal "contents" - end - - should "parse filename with unescaped percentage characters" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_with_unescaped_percentages, "----WebKitFormBoundary2NHc7OhsgU68l3Al")) - params = Rack::Multipart.parse_multipart(env) - files = params["document"]["attachment"] - files[:type].should.equal "image/jpeg" - files[:filename].should.equal "100% of a photo.jpeg" - files[:head].should.equal <<-MULTIPART -Content-Disposition: form-data; name="document[attachment]"; filename="100% of a photo.jpeg"\r -Content-Type: image/jpeg\r - MULTIPART - - files[:name].should.equal "document[attachment]" - files[:tempfile].read.should.equal "contents" - end - - should "parse filename with unescaped percentage characters that look like partial hex escapes" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_with_unescaped_percentages2, "----WebKitFormBoundary2NHc7OhsgU68l3Al")) - params = Rack::Multipart.parse_multipart(env) - files = params["document"]["attachment"] - files[:type].should.equal "image/jpeg" - files[:filename].should.equal "100%a" - files[:head].should.equal <<-MULTIPART -Content-Disposition: form-data; name="document[attachment]"; filename="100%a"\r -Content-Type: image/jpeg\r - MULTIPART - - files[:name].should.equal "document[attachment]" - files[:tempfile].read.should.equal "contents" - end - - should "parse filename with unescaped percentage characters that look like partial hex escapes" do - env = Rack::MockRequest.env_for("/", multipart_fixture(:filename_with_unescaped_percentages3, "----WebKitFormBoundary2NHc7OhsgU68l3Al")) - params = Rack::Multipart.parse_multipart(env) - files = params["document"]["attachment"] - files[:type].should.equal "image/jpeg" - files[:filename].should.equal "100%" - files[:head].should.equal <<-MULTIPART -Content-Disposition: form-data; name="document[attachment]"; filename="100%"\r -Content-Type: image/jpeg\r - MULTIPART - - files[:name].should.equal "document[attachment]" - files[:tempfile].read.should.equal "contents" - end - - it "rewinds input after parsing upload" do - options = multipart_fixture(:text) - input = options[:input] - env = Rack::MockRequest.env_for("/", options) - params = Rack::Multipart.parse_multipart(env) - params["submit-name"].should.equal "Larry" - params["files"][:filename].should.equal "file1.txt" - input.read.length.should.equal 307 - end - - it "builds multipart body" do - files = Rack::Multipart::UploadedFile.new(multipart_file("file1.txt")) - data = Rack::Multipart.build_multipart("submit-name" => "Larry", "files" => files) - - options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x", - "CONTENT_LENGTH" => data.length.to_s, - :input => StringIO.new(data) - } - env = Rack::MockRequest.env_for("/", options) - params = Rack::Multipart.parse_multipart(env) - params["submit-name"].should.equal "Larry" - params["files"][:filename].should.equal "file1.txt" - params["files"][:tempfile].read.should.equal "contents" - end - - it "builds nested multipart body" do - files = Rack::Multipart::UploadedFile.new(multipart_file("file1.txt")) - data = Rack::Multipart.build_multipart("people" => [{"submit-name" => "Larry", "files" => files}]) - - options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x", - "CONTENT_LENGTH" => data.length.to_s, - :input => StringIO.new(data) - } - env = Rack::MockRequest.env_for("/", options) - params = Rack::Multipart.parse_multipart(env) - params["people"][0]["submit-name"].should.equal "Larry" - params["people"][0]["files"][:filename].should.equal "file1.txt" - params["people"][0]["files"][:tempfile].read.should.equal "contents" - end - - it "can parse fields that end at the end of the buffer" do - input = File.read(multipart_file("bad_robots")) - - req = Rack::Request.new Rack::MockRequest.env_for("/", - "CONTENT_TYPE" => "multipart/form-data, boundary=1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon", - "CONTENT_LENGTH" => input.size, - :input => input) - - req.POST['file.path'].should.equal "/var/tmp/uploads/4/0001728414" - req.POST['addresses'].should.not.equal nil - end - - it "builds complete params with the chunk size of 16384 slicing exactly on boundary" do - data = File.open(multipart_file("fail_16384_nofile"), 'rb') { |f| f.read }.gsub(/\n/, "\r\n") - options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=----WebKitFormBoundaryWsY0GnpbI5U7ztzo", - "CONTENT_LENGTH" => data.length.to_s, - :input => StringIO.new(data) - } - env = Rack::MockRequest.env_for("/", options) - params = Rack::Multipart.parse_multipart(env) - - params.should.not.equal nil - params.keys.should.include "AAAAAAAAAAAAAAAAAAA" - params["AAAAAAAAAAAAAAAAAAA"].keys.should.include "PLAPLAPLA_MEMMEMMEMM_ATTRATTRER" - params["AAAAAAAAAAAAAAAAAAA"]["PLAPLAPLA_MEMMEMMEMM_ATTRATTRER"].keys.should.include "new" - params["AAAAAAAAAAAAAAAAAAA"]["PLAPLAPLA_MEMMEMMEMM_ATTRATTRER"]["new"].keys.should.include "-2" - params["AAAAAAAAAAAAAAAAAAA"]["PLAPLAPLA_MEMMEMMEMM_ATTRATTRER"]["new"]["-2"].keys.should.include "ba_unit_id" - params["AAAAAAAAAAAAAAAAAAA"]["PLAPLAPLA_MEMMEMMEMM_ATTRATTRER"]["new"]["-2"]["ba_unit_id"].should.equal "1017" - end - - should "return nil if no UploadedFiles were used" do - data = Rack::Multipart.build_multipart("people" => [{"submit-name" => "Larry", "files" => "contents"}]) - data.should.equal nil - end - - should "raise ArgumentError if params is not a Hash" do - lambda { Rack::Multipart.build_multipart("foo=bar") }. - should.raise(ArgumentError). - message.should.equal "value must be a Hash" - end - - it "can parse fields with a content type" do - data = <<-EOF ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon\r -Content-Disposition: form-data; name="description"\r -Content-Type: text/plain"\r -\r -Very very blue\r ---1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon--\r -EOF - options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=1yy3laWhgX31qpiHinh67wJXqKalukEUTvqTzmon", - "CONTENT_LENGTH" => data.length.to_s, - :input => StringIO.new(data) - } - env = Rack::MockRequest.env_for("/", options) - params = Rack::Utils::Multipart.parse_multipart(env) - - params.should.equal({"description"=>"Very very blue"}) - end - - should "parse multipart upload with no content-length header" do - env = Rack::MockRequest.env_for '/', multipart_fixture(:webkit) - env['CONTENT_TYPE'] = "multipart/form-data; boundary=----WebKitFormBoundaryWLHCs9qmcJJoyjKR" - env.delete 'CONTENT_LENGTH' - params = Rack::Multipart.parse_multipart(env) - params['profile']['bio'].should.include 'hello' - end - - should "parse very long unquoted multipart file names" do - data = <<-EOF ---AaB03x\r -Content-Type: text/plain\r -Content-Disposition: attachment; name=file; filename=#{'long' * 100}\r -\r -contents\r ---AaB03x--\r - EOF - - options = { - "CONTENT_TYPE" => "multipart/form-data; boundary=AaB03x", - "CONTENT_LENGTH" => data.length.to_s, - :input => StringIO.new(data) - } - env = Rack::MockRequest.env_for("/", options) - params = Rack::Utils::Multipart.parse_multipart(env) - - params["file"][:filename].should.equal('long' * 100) - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_nulllogger.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_nulllogger.rb deleted file mode 100644 index 88ba521..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_nulllogger.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'rack/lint' -require 'rack/mock' -require 'rack/nulllogger' - -describe Rack::NullLogger do - should "act as a noop logger" do - app = lambda { |env| - env['rack.logger'].warn "b00m" - [200, {'Content-Type' => 'text/plain'}, ["Hello, World!"]] - } - - logger = Rack::Lint.new(Rack::NullLogger.new(app)) - - res = logger.call(Rack::MockRequest.env_for) - res[0..1].should.equal [ - 200, {'Content-Type' => 'text/plain'} - ] - res[2].to_enum.to_a.should.equal ["Hello, World!"] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_recursive.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_recursive.rb deleted file mode 100644 index 764c44c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_recursive.rb +++ /dev/null @@ -1,72 +0,0 @@ -require 'rack/lint' -require 'rack/recursive' -require 'rack/mock' - -describe Rack::Recursive do - @app1 = lambda { |env| - res = Rack::Response.new - res["X-Path-Info"] = env["PATH_INFO"] - res["X-Query-String"] = env["QUERY_STRING"] - res.finish do |inner_res| - inner_res.write "App1" - end - } - - @app2 = lambda { |env| - Rack::Response.new.finish do |res| - res.write "App2" - _, _, body = env['rack.recursive.include'].call(env, "/app1") - body.each { |b| - res.write b - } - end - } - - @app3 = lambda { |env| - raise Rack::ForwardRequest.new("/app1") - } - - @app4 = lambda { |env| - raise Rack::ForwardRequest.new("http://example.org/app1/quux?meh") - } - - def recursive(map) - Rack::Lint.new Rack::Recursive.new(Rack::URLMap.new(map)) - end - - should "allow for subrequests" do - res = Rack::MockRequest.new(recursive("/app1" => @app1, - "/app2" => @app2)). - get("/app2") - - res.should.be.ok - res.body.should.equal "App2App1" - end - - should "raise error on requests not below the app" do - app = Rack::URLMap.new("/app1" => @app1, - "/app" => recursive("/1" => @app1, - "/2" => @app2)) - - lambda { - Rack::MockRequest.new(app).get("/app/2") - }.should.raise(ArgumentError). - message.should =~ /can only include below/ - end - - should "support forwarding" do - app = recursive("/app1" => @app1, - "/app3" => @app3, - "/app4" => @app4) - - res = Rack::MockRequest.new(app).get("/app3") - res.should.be.ok - res.body.should.equal "App1" - - res = Rack::MockRequest.new(app).get("/app4") - res.should.be.ok - res.body.should.equal "App1" - res["X-Path-Info"].should.equal "/quux" - res["X-Query-String"].should.equal "meh" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_request.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_request.rb deleted file mode 100644 index 9649c5d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_request.rb +++ /dev/null @@ -1,1078 +0,0 @@ -require 'stringio' -require 'cgi' -require 'rack/request' -require 'rack/mock' - -describe Rack::Request do - should "wrap the rack variables" do - req = Rack::Request.new(Rack::MockRequest.env_for("http://example.com:8080/")) - - req.body.should.respond_to? :gets - req.scheme.should.equal "http" - req.request_method.should.equal "GET" - - req.should.be.get - req.should.not.be.post - req.should.not.be.put - req.should.not.be.delete - req.should.not.be.head - req.should.not.be.patch - - req.script_name.should.equal "" - req.path_info.should.equal "/" - req.query_string.should.equal "" - - req.host.should.equal "example.com" - req.port.should.equal 8080 - - req.content_length.should.equal "0" - req.content_type.should.be.nil - end - - should "figure out the correct host" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org") - req.host.should.equal "www2.example.org" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "SERVER_NAME" => "example.org", "SERVER_PORT" => "9292") - req.host.should.equal "example.org" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9292") - req.host.should.equal "example.org" - - env = Rack::MockRequest.env_for("/", "SERVER_ADDR" => "192.168.1.1", "SERVER_PORT" => "9292") - env.delete("SERVER_NAME") - req = Rack::Request.new(env) - req.host.should.equal "192.168.1.1" - - env = Rack::MockRequest.env_for("/") - env.delete("SERVER_NAME") - req = Rack::Request.new(env) - req.host.should.equal "" - end - - should "figure out the correct port" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org") - req.port.should.equal 80 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org:81") - req.port.should.equal 81 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "SERVER_NAME" => "example.org", "SERVER_PORT" => "9292") - req.port.should.equal 9292 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9292") - req.port.should.equal 9292 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org") - req.port.should.equal 80 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "HTTP_X_FORWARDED_SSL" => "on") - req.port.should.equal 443 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "HTTP_X_FORWARDED_PROTO" => "https") - req.port.should.equal 443 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "HTTP_X_FORWARDED_PORT" => "9393") - req.port.should.equal 9393 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9393", "SERVER_PORT" => "80") - req.port.should.equal 9393 - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "SERVER_PORT" => "9393") - req.port.should.equal 80 - end - - should "figure out the correct host with port" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "www2.example.org") - req.host_with_port.should.equal "www2.example.org" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81") - req.host_with_port.should.equal "localhost:81" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "SERVER_NAME" => "example.org", "SERVER_PORT" => "9292") - req.host_with_port.should.equal "example.org:9292" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org:9292") - req.host_with_port.should.equal "example.org:9292" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_HOST" => "localhost:81", "HTTP_X_FORWARDED_HOST" => "example.org", "SERVER_PORT" => "9393") - req.host_with_port.should.equal "example.org" - end - - should "parse the query string" do - req = Rack::Request.new(Rack::MockRequest.env_for("/?foo=bar&quux=bla")) - req.query_string.should.equal "foo=bar&quux=bla" - req.GET.should.equal "foo" => "bar", "quux" => "bla" - req.POST.should.be.empty - req.params.should.equal "foo" => "bar", "quux" => "bla" - end - - should "limit the keys from the GET query string" do - env = Rack::MockRequest.env_for("/?foo=bar") - - old, Rack::Utils.key_space_limit = Rack::Utils.key_space_limit, 1 - begin - req = Rack::Request.new(env) - lambda { req.GET }.should.raise(RangeError) - ensure - Rack::Utils.key_space_limit = old - end - end - - should "limit the key size per nested params hash" do - nested_query = Rack::MockRequest.env_for("/?foo[bar][baz][qux]=1") - plain_query = Rack::MockRequest.env_for("/?foo_bar__baz__qux_=1") - - old, Rack::Utils.key_space_limit = Rack::Utils.key_space_limit, 3 - begin - lambda { Rack::Request.new(nested_query).GET }.should.not.raise(RangeError) - lambda { Rack::Request.new(plain_query).GET }.should.raise(RangeError) - ensure - Rack::Utils.key_space_limit = old - end - end - - should "not unify GET and POST when calling params" do - mr = Rack::MockRequest.env_for("/?foo=quux", - "REQUEST_METHOD" => 'POST', - :input => "foo=bar&quux=bla" - ) - req = Rack::Request.new mr - - req.params - - req.GET.should.equal "foo" => "quux" - req.POST.should.equal "foo" => "bar", "quux" => "bla" - req.params.should.equal req.GET.merge(req.POST) - end - - should "raise if rack.input is missing" do - req = Rack::Request.new({}) - lambda { req.POST }.should.raise(RuntimeError) - end - - should "parse POST data when method is POST and no Content-Type given" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/?foo=quux", - "REQUEST_METHOD" => 'POST', - :input => "foo=bar&quux=bla") - req.content_type.should.be.nil - req.media_type.should.be.nil - req.query_string.should.equal "foo=quux" - req.GET.should.equal "foo" => "quux" - req.POST.should.equal "foo" => "bar", "quux" => "bla" - req.params.should.equal "foo" => "bar", "quux" => "bla" - end - - should "limit the keys from the POST form data" do - env = Rack::MockRequest.env_for("", - "REQUEST_METHOD" => 'POST', - :input => "foo=bar&quux=bla") - - old, Rack::Utils.key_space_limit = Rack::Utils.key_space_limit, 1 - begin - req = Rack::Request.new(env) - lambda { req.POST }.should.raise(RangeError) - ensure - Rack::Utils.key_space_limit = old - end - end - - should "parse POST data with explicit content type regardless of method" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", - "CONTENT_TYPE" => 'application/x-www-form-urlencoded;foo=bar', - :input => "foo=bar&quux=bla") - req.content_type.should.equal 'application/x-www-form-urlencoded;foo=bar' - req.media_type.should.equal 'application/x-www-form-urlencoded' - req.media_type_params['foo'].should.equal 'bar' - req.POST.should.equal "foo" => "bar", "quux" => "bla" - req.params.should.equal "foo" => "bar", "quux" => "bla" - end - - should "not parse POST data when media type is not form-data" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/?foo=quux", - "REQUEST_METHOD" => 'POST', - "CONTENT_TYPE" => 'text/plain;charset=utf-8', - :input => "foo=bar&quux=bla") - req.content_type.should.equal 'text/plain;charset=utf-8' - req.media_type.should.equal 'text/plain' - req.media_type_params['charset'].should.equal 'utf-8' - req.POST.should.be.empty - req.params.should.equal "foo" => "quux" - req.body.read.should.equal "foo=bar&quux=bla" - end - - should "parse POST data on PUT when media type is form-data" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/?foo=quux", - "REQUEST_METHOD" => 'PUT', - "CONTENT_TYPE" => 'application/x-www-form-urlencoded', - :input => "foo=bar&quux=bla") - req.POST.should.equal "foo" => "bar", "quux" => "bla" - req.body.read.should.equal "foo=bar&quux=bla" - end - - should "rewind input after parsing POST data" do - input = StringIO.new("foo=bar&quux=bla") - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", - "CONTENT_TYPE" => 'application/x-www-form-urlencoded;foo=bar', - :input => input) - req.params.should.equal "foo" => "bar", "quux" => "bla" - input.read.should.equal "foo=bar&quux=bla" - end - - should "clean up Safari's ajax POST body" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", - 'REQUEST_METHOD' => 'POST', :input => "foo=bar&quux=bla\0") - req.POST.should.equal "foo" => "bar", "quux" => "bla" - end - - should "get value by key from params with #[]" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("?foo=quux") - req['foo'].should.equal 'quux' - req[:foo].should.equal 'quux' - end - - should "set value to key on params with #[]=" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("?foo=duh") - req['foo'].should.equal 'duh' - req[:foo].should.equal 'duh' - req.params.should.equal 'foo' => 'duh' - - req['foo'] = 'bar' - req.params.should.equal 'foo' => 'bar' - req['foo'].should.equal 'bar' - req[:foo].should.equal 'bar' - - req[:foo] = 'jaz' - req.params.should.equal 'foo' => 'jaz' - req['foo'].should.equal 'jaz' - req[:foo].should.equal 'jaz' - end - - should "return values for the keys in the order given from values_at" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("?foo=baz&wun=der&bar=ful") - req.values_at('foo').should.equal ['baz'] - req.values_at('foo', 'wun').should.equal ['baz', 'der'] - req.values_at('bar', 'foo', 'wun').should.equal ['ful', 'baz', 'der'] - end - - should "extract referrer correctly" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_REFERER" => "/some/path") - req.referer.should.equal "/some/path" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/") - req.referer.should.equal nil - end - - should "extract user agent correctly" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "HTTP_USER_AGENT" => "Mozilla/4.0 (compatible)") - req.user_agent.should.equal "Mozilla/4.0 (compatible)" - - req = Rack::Request.new \ - Rack::MockRequest.env_for("/") - req.user_agent.should.equal nil - end - - should "treat missing content type as nil" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/") - req.content_type.should.equal nil - end - - should "treat empty content type as nil" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "") - req.content_type.should.equal nil - end - - should "return nil media type for empty content type" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", "CONTENT_TYPE" => "") - req.media_type.should.equal nil - end - - should "cache, but invalidates the cache" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/?foo=quux", - "CONTENT_TYPE" => "application/x-www-form-urlencoded", - :input => "foo=bar&quux=bla") - req.GET.should.equal "foo" => "quux" - req.GET.should.equal "foo" => "quux" - req.env["QUERY_STRING"] = "bla=foo" - req.GET.should.equal "bla" => "foo" - req.GET.should.equal "bla" => "foo" - - req.POST.should.equal "foo" => "bar", "quux" => "bla" - req.POST.should.equal "foo" => "bar", "quux" => "bla" - req.env["rack.input"] = StringIO.new("foo=bla&quux=bar") - req.POST.should.equal "foo" => "bla", "quux" => "bar" - req.POST.should.equal "foo" => "bla", "quux" => "bar" - end - - should "figure out if called via XHR" do - req = Rack::Request.new(Rack::MockRequest.env_for("")) - req.should.not.be.xhr - - req = Rack::Request.new \ - Rack::MockRequest.env_for("", "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest") - req.should.be.xhr - end - - should "ssl detection" do - request = Rack::Request.new(Rack::MockRequest.env_for("/")) - request.scheme.should.equal "http" - request.should.not.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'HTTPS' => 'on')) - request.scheme.should.equal "https" - request.should.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'rack.url_scheme' => 'https')) - request.scheme.should.equal "https" - request.should.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'HTTP_HOST' => 'www.example.org:8080')) - request.scheme.should.equal "http" - request.should.not.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'HTTP_HOST' => 'www.example.org:8443', 'HTTPS' => 'on')) - request.scheme.should.equal "https" - request.should.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'HTTP_HOST' => 'www.example.org:8443', 'HTTP_X_FORWARDED_SSL' => 'on')) - request.scheme.should.equal "https" - request.should.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'HTTP_X_FORWARDED_SCHEME' => 'https')) - request.scheme.should.equal "https" - request.should.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'HTTP_X_FORWARDED_PROTO' => 'https')) - request.scheme.should.equal "https" - request.should.be.ssl? - - request = Rack::Request.new(Rack::MockRequest.env_for("/", 'HTTP_X_FORWARDED_PROTO' => 'https, http, http')) - request.scheme.should.equal "https" - request.should.be.ssl? - end - - should "parse cookies" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("", "HTTP_COOKIE" => "foo=bar;quux=h&m") - req.cookies.should.equal "foo" => "bar", "quux" => "h&m" - req.cookies.should.equal "foo" => "bar", "quux" => "h&m" - req.env.delete("HTTP_COOKIE") - req.cookies.should.equal({}) - end - - should "always return the same hash object" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("", "HTTP_COOKIE" => "foo=bar;quux=h&m") - hash = req.cookies - req.env.delete("HTTP_COOKIE") - req.cookies.should.equal(hash) - req.env["HTTP_COOKIE"] = "zoo=m" - req.cookies.should.equal(hash) - end - - should "modify the cookies hash in place" do - req = Rack::Request.new(Rack::MockRequest.env_for("")) - req.cookies.should.equal({}) - req.cookies['foo'] = 'bar' - req.cookies.should.equal 'foo' => 'bar' - end - - should "not modify the params hash in place" do - e = Rack::MockRequest.env_for("") - req1 = Rack::Request.new(e) - req1.params.should.equal({}) - req1.params['foo'] = 'bar' - req1.params.should.equal 'foo' => 'bar' - req2 = Rack::Request.new(e) - req2.params.should.equal({}) - end - - should "modify params hash if param is in GET" do - e = Rack::MockRequest.env_for("?foo=duh") - req1 = Rack::Request.new(e) - req1.params.should.equal 'foo' => 'duh' - req1.update_param 'foo', 'bar' - req1.params.should.equal 'foo' => 'bar' - req2 = Rack::Request.new(e) - req2.params.should.equal 'foo' => 'bar' - end - - should "modify params hash if param is in POST" do - e = Rack::MockRequest.env_for("", "REQUEST_METHOD" => 'POST', :input => 'foo=duh') - req1 = Rack::Request.new(e) - req1.params.should.equal 'foo' => 'duh' - req1.update_param 'foo', 'bar' - req1.params.should.equal 'foo' => 'bar' - req2 = Rack::Request.new(e) - req2.params.should.equal 'foo' => 'bar' - end - - should "modify params hash, even if param didn't exist before" do - e = Rack::MockRequest.env_for("") - req1 = Rack::Request.new(e) - req1.params.should.equal({}) - req1.update_param 'foo', 'bar' - req1.params.should.equal 'foo' => 'bar' - req2 = Rack::Request.new(e) - req2.params.should.equal 'foo' => 'bar' - end - - should "modify params hash by changing only GET" do - e = Rack::MockRequest.env_for("?foo=duhget") - req = Rack::Request.new(e) - req.GET.should.equal 'foo' => 'duhget' - req.POST.should.equal({}) - req.update_param 'foo', 'bar' - req.GET.should.equal 'foo' => 'bar' - req.POST.should.equal({}) - end - - should "modify params hash by changing only POST" do - e = Rack::MockRequest.env_for("", "REQUEST_METHOD" => 'POST', :input => "foo=duhpost") - req = Rack::Request.new(e) - req.GET.should.equal({}) - req.POST.should.equal 'foo' => 'duhpost' - req.update_param 'foo', 'bar' - req.GET.should.equal({}) - req.POST.should.equal 'foo' => 'bar' - end - - should "modify params hash, even if param is defined in both POST and GET" do - e = Rack::MockRequest.env_for("?foo=duhget", "REQUEST_METHOD" => 'POST', :input => "foo=duhpost") - req1 = Rack::Request.new(e) - req1.GET.should.equal 'foo' => 'duhget' - req1.POST.should.equal 'foo' => 'duhpost' - req1.params.should.equal 'foo' => 'duhpost' - req1.update_param 'foo', 'bar' - req1.GET.should.equal 'foo' => 'bar' - req1.POST.should.equal 'foo' => 'bar' - req1.params.should.equal 'foo' => 'bar' - req2 = Rack::Request.new(e) - req2.GET.should.equal 'foo' => 'bar' - req2.POST.should.equal 'foo' => 'bar' - req2.params.should.equal 'foo' => 'bar' - req2.params.should.equal 'foo' => 'bar' - end - - should "allow deleting from params hash if param is in GET" do - e = Rack::MockRequest.env_for("?foo=bar") - req1 = Rack::Request.new(e) - req1.params.should.equal 'foo' => 'bar' - req1.delete_param('foo').should.equal 'bar' - req1.params.should.equal({}) - req2 = Rack::Request.new(e) - req2.params.should.equal({}) - end - - should "allow deleting from params hash if param is in POST" do - e = Rack::MockRequest.env_for("", "REQUEST_METHOD" => 'POST', :input => 'foo=bar') - req1 = Rack::Request.new(e) - req1.params.should.equal 'foo' => 'bar' - req1.delete_param('foo').should.equal 'bar' - req1.params.should.equal({}) - req2 = Rack::Request.new(e) - req2.params.should.equal({}) - end - - should "pass through non-uri escaped cookies as-is" do - req = Rack::Request.new Rack::MockRequest.env_for("", "HTTP_COOKIE" => "foo=%") - req.cookies["foo"].should == "%" - end - - should "parse cookies according to RFC 2109" do - req = Rack::Request.new \ - Rack::MockRequest.env_for('', 'HTTP_COOKIE' => 'foo=bar;foo=car') - req.cookies.should.equal 'foo' => 'bar' - end - - should 'parse cookies with quotes' do - req = Rack::Request.new Rack::MockRequest.env_for('', { - 'HTTP_COOKIE' => '$Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"; Part_Number="Rocket_Launcher_0001"; $Path="/acme"' - }) - req.cookies.should.equal({ - '$Version' => '"1"', - 'Customer' => '"WILE_E_COYOTE"', - '$Path' => '"/acme"', - 'Part_Number' => '"Rocket_Launcher_0001"', - }) - end - - should "provide setters" do - req = Rack::Request.new(e=Rack::MockRequest.env_for("")) - req.script_name.should.equal "" - req.script_name = "/foo" - req.script_name.should.equal "/foo" - e["SCRIPT_NAME"].should.equal "/foo" - - req.path_info.should.equal "/" - req.path_info = "/foo" - req.path_info.should.equal "/foo" - e["PATH_INFO"].should.equal "/foo" - end - - should "provide the original env" do - req = Rack::Request.new(e = Rack::MockRequest.env_for("")) - req.env.should == e - end - - should "restore the base URL" do - Rack::Request.new(Rack::MockRequest.env_for("")).base_url. - should.equal "http://example.org" - Rack::Request.new(Rack::MockRequest.env_for("", "SCRIPT_NAME" => "/foo")).base_url. - should.equal "http://example.org" - end - - should "restore the URL" do - Rack::Request.new(Rack::MockRequest.env_for("")).url. - should.equal "http://example.org/" - Rack::Request.new(Rack::MockRequest.env_for("", "SCRIPT_NAME" => "/foo")).url. - should.equal "http://example.org/foo/" - Rack::Request.new(Rack::MockRequest.env_for("/foo")).url. - should.equal "http://example.org/foo" - Rack::Request.new(Rack::MockRequest.env_for("?foo")).url. - should.equal "http://example.org/?foo" - Rack::Request.new(Rack::MockRequest.env_for("http://example.org:8080/")).url. - should.equal "http://example.org:8080/" - Rack::Request.new(Rack::MockRequest.env_for("https://example.org/")).url. - should.equal "https://example.org/" - Rack::Request.new(Rack::MockRequest.env_for("coffee://example.org/")).url. - should.equal "coffee://example.org/" - Rack::Request.new(Rack::MockRequest.env_for("coffee://example.org:443/")).url. - should.equal "coffee://example.org:443/" - Rack::Request.new(Rack::MockRequest.env_for("https://example.com:8080/foo?foo")).url. - should.equal "https://example.com:8080/foo?foo" - end - - should "restore the full path" do - Rack::Request.new(Rack::MockRequest.env_for("")).fullpath. - should.equal "/" - Rack::Request.new(Rack::MockRequest.env_for("", "SCRIPT_NAME" => "/foo")).fullpath. - should.equal "/foo/" - Rack::Request.new(Rack::MockRequest.env_for("/foo")).fullpath. - should.equal "/foo" - Rack::Request.new(Rack::MockRequest.env_for("?foo")).fullpath. - should.equal "/?foo" - Rack::Request.new(Rack::MockRequest.env_for("http://example.org:8080/")).fullpath. - should.equal "/" - Rack::Request.new(Rack::MockRequest.env_for("https://example.org/")).fullpath. - should.equal "/" - - Rack::Request.new(Rack::MockRequest.env_for("https://example.com:8080/foo?foo")).fullpath. - should.equal "/foo?foo" - end - - should "handle multiple media type parameters" do - req = Rack::Request.new \ - Rack::MockRequest.env_for("/", - "CONTENT_TYPE" => 'text/plain; foo=BAR,baz=bizzle dizzle;BLING=bam') - req.should.not.be.form_data - req.media_type_params.should.include 'foo' - req.media_type_params['foo'].should.equal 'BAR' - req.media_type_params.should.include 'baz' - req.media_type_params['baz'].should.equal 'bizzle dizzle' - req.media_type_params.should.not.include 'BLING' - req.media_type_params.should.include 'bling' - req.media_type_params['bling'].should.equal 'bam' - end - - should "parse with junk before boundry" do - # Adapted from RFC 1867. - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - req.POST.should.include "fileupload" - req.POST.should.include "reply" - - req.should.be.form_data - req.content_length.should.equal input.size - req.media_type.should.equal 'multipart/form-data' - req.media_type_params.should.include 'boundary' - req.media_type_params['boundary'].should.equal 'AaB03x' - - req.POST["reply"].should.equal "yes" - - f = req.POST["fileupload"] - f.should.be.kind_of Hash - f[:type].should.equal "image/jpeg" - f[:filename].should.equal "dj.jpg" - f.should.include :tempfile - f[:tempfile].size.should.equal 76 - end - - should "not infinite loop with a malformed HTTP request" do - # Adapted from RFC 1867. - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - lambda{req.POST}.should.raise(EOFError) - end - - - should "parse multipart form data" do - # Adapted from RFC 1867. - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - req.POST.should.include "fileupload" - req.POST.should.include "reply" - - req.should.be.form_data - req.content_length.should.equal input.size - req.media_type.should.equal 'multipart/form-data' - req.media_type_params.should.include 'boundary' - req.media_type_params['boundary'].should.equal 'AaB03x' - - req.POST["reply"].should.equal "yes" - - f = req.POST["fileupload"] - f.should.be.kind_of Hash - f[:type].should.equal "image/jpeg" - f[:filename].should.equal "dj.jpg" - f.should.include :tempfile - f[:tempfile].size.should.equal 76 - end - - should "parse big multipart form data" do - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - req.POST["huge"][:tempfile].size.should.equal 32768 - req.POST["mean"][:tempfile].size.should.equal 10 - req.POST["mean"][:tempfile].read.should.equal "--AaB03xha" - end - - should "detect invalid multipart form data" do - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - lambda { req.POST }.should.raise(EOFError) - - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - lambda { req.POST }.should.raise(EOFError) - - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - lambda { req.POST }.should.raise(EOFError) - end - - should "correctly parse the part name from Content-Id header" do - input = <\r -Content-Transfer-Encoding: 7bit\r -\r -foo\r ---AaB03x--\r -EOF - req = Rack::Request.new Rack::MockRequest.env_for("/", - "CONTENT_TYPE" => "multipart/related, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - req.params.keys.should.equal [""] - end - - should "not try to interpret binary as utf8" do - if /regexp/.respond_to?(:kcode) # < 1.9 - begin - original_kcode = $KCODE - $KCODE='UTF8' - - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - lambda{req.POST}.should.not.raise(EOFError) - req.POST["fileupload"][:tempfile].size.should.equal 4 - ensure - $KCODE = original_kcode - end - else # >= 1.9 - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => input) - - lambda{req.POST}.should.not.raise(EOFError) - req.POST["fileupload"][:tempfile].size.should.equal 4 - end - end - - should "work around buggy 1.8.* Tempfile equality" do - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size, - :input => rack_input) - - lambda{ req.POST }.should.not.raise - lambda{ req.POST }.should.not.raise("input re-processed!") - end - - should "conform to the Rack spec" do - app = lambda { |env| - content = Rack::Request.new(env).POST["file"].inspect - size = content.respond_to?(:bytesize) ? content.bytesize : content.size - [200, {"Content-Type" => "text/html", "Content-Length" => size.to_s}, [content]] - } - - input = < "multipart/form-data, boundary=AaB03x", - "CONTENT_LENGTH" => input.size.to_s, "rack.input" => StringIO.new(input) - - res.should.be.ok - end - - should "parse Accept-Encoding correctly" do - parser = lambda do |x| - Rack::Request.new(Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => x)).accept_encoding - end - - parser.call(nil).should.equal([]) - - parser.call("compress, gzip").should.equal([["compress", 1.0], ["gzip", 1.0]]) - parser.call("").should.equal([]) - parser.call("*").should.equal([["*", 1.0]]) - parser.call("compress;q=0.5, gzip;q=1.0").should.equal([["compress", 0.5], ["gzip", 1.0]]) - parser.call("gzip;q=1.0, identity; q=0.5, *;q=0").should.equal([["gzip", 1.0], ["identity", 0.5], ["*", 0] ]) - - parser.call("gzip ; q=0.9").should.equal([["gzip", 0.9]]) - parser.call("gzip ; deflate").should.equal([["gzip", 1.0]]) - end - - ip_app = lambda { |env| - request = Rack::Request.new(env) - response = Rack::Response.new - response.write request.ip - response.finish - } - - should 'provide ip information' do - mock = Rack::MockRequest.new(Rack::Lint.new(ip_app)) - - res = mock.get '/', 'REMOTE_ADDR' => '1.2.3.4' - res.body.should.equal '1.2.3.4' - - res = mock.get '/', 'REMOTE_ADDR' => 'fe80::202:b3ff:fe1e:8329' - res.body.should.equal 'fe80::202:b3ff:fe1e:8329' - - res = mock.get '/', 'REMOTE_ADDR' => '1.2.3.4,3.4.5.6' - res.body.should.equal '1.2.3.4' - end - - should 'deals with proxies' do - mock = Rack::MockRequest.new(Rack::Lint.new(ip_app)) - - res = mock.get '/', - 'REMOTE_ADDR' => '1.2.3.4', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - res.body.should.equal '1.2.3.4' - - res = mock.get '/', - 'REMOTE_ADDR' => '1.2.3.4', - 'HTTP_X_FORWARDED_FOR' => 'unknown' - res.body.should.equal '1.2.3.4' - - res = mock.get '/', - 'REMOTE_ADDR' => '127.0.0.1', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'unknown,3.4.5.6' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '192.168.0.1,3.4.5.6' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '10.0.0.1,3.4.5.6' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '10.0.0.1, 10.0.0.1, 3.4.5.6' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '127.0.0.1, 3.4.5.6' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'unknown,192.168.0.1' - res.body.should.equal 'unknown' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'other,unknown,192.168.0.1' - res.body.should.equal 'unknown' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'unknown,localhost,192.168.0.1' - res.body.should.equal 'unknown' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '9.9.9.9, 3.4.5.6, 10.0.0.1, 172.31.4.4' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '::1,2620:0:1c00:0:812c:9583:754b:ca11' - res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,::1' - res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => 'fd5b:982e:9130:247f:0000:0000:0000:0000,2620:0:1c00:0:812c:9583:754b:ca11' - res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '2620:0:1c00:0:812c:9583:754b:ca11,fd5b:982e:9130:247f:0000:0000:0000:0000' - res.body.should.equal '2620:0:1c00:0:812c:9583:754b:ca11' - - res = mock.get '/', - 'HTTP_X_FORWARDED_FOR' => '1.1.1.1, 127.0.0.1', - 'HTTP_CLIENT_IP' => '1.1.1.1' - res.body.should.equal '1.1.1.1' - - # Spoofing attempt - res = mock.get '/', - 'HTTP_X_FORWARDED_FOR' => '1.1.1.1', - 'HTTP_CLIENT_IP' => '2.2.2.2' - res.body.should.equal '1.1.1.1' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, 9.9.9.9' - res.body.should.equal '9.9.9.9' - - res = mock.get '/', 'HTTP_X_FORWARDED_FOR' => '8.8.8.8, fe80::202:b3ff:fe1e:8329' - res.body.should.equal 'fe80::202:b3ff:fe1e:8329' - - # Unix Sockets - res = mock.get '/', - 'REMOTE_ADDR' => 'unix', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - res.body.should.equal '3.4.5.6' - - res = mock.get '/', - 'REMOTE_ADDR' => 'unix:/tmp/foo', - 'HTTP_X_FORWARDED_FOR' => '3.4.5.6' - res.body.should.equal '3.4.5.6' - end - - should "regard local addresses as proxies" do - req = Rack::Request.new(Rack::MockRequest.env_for("/")) - req.trusted_proxy?('127.0.0.1').should.equal 0 - req.trusted_proxy?('10.0.0.1').should.equal 0 - req.trusted_proxy?('172.16.0.1').should.equal 0 - req.trusted_proxy?('172.20.0.1').should.equal 0 - req.trusted_proxy?('172.30.0.1').should.equal 0 - req.trusted_proxy?('172.31.0.1').should.equal 0 - req.trusted_proxy?('192.168.0.1').should.equal 0 - req.trusted_proxy?('::1').should.equal 0 - req.trusted_proxy?('fd00::').should.equal 0 - req.trusted_proxy?('localhost').should.equal 0 - req.trusted_proxy?('unix').should.equal 0 - req.trusted_proxy?('unix:/tmp/sock').should.equal 0 - - req.trusted_proxy?("unix.example.org").should.equal nil - req.trusted_proxy?("example.org\n127.0.0.1").should.equal nil - req.trusted_proxy?("127.0.0.1\nexample.org").should.equal nil - req.trusted_proxy?("11.0.0.1").should.equal nil - req.trusted_proxy?("172.15.0.1").should.equal nil - req.trusted_proxy?("172.32.0.1").should.equal nil - req.trusted_proxy?("2001:470:1f0b:18f8::1").should.equal nil - end - - class MyRequest < Rack::Request - def params - {:foo => "bar"} - end - end - - should "allow subclass request to be instantiated after parent request" do - env = Rack::MockRequest.env_for("/?foo=bar") - - req1 = Rack::Request.new(env) - req1.GET.should.equal "foo" => "bar" - req1.params.should.equal "foo" => "bar" - - req2 = MyRequest.new(env) - req2.GET.should.equal "foo" => "bar" - req2.params.should.equal :foo => "bar" - end - - should "allow parent request to be instantiated after subclass request" do - env = Rack::MockRequest.env_for("/?foo=bar") - - req1 = MyRequest.new(env) - req1.GET.should.equal "foo" => "bar" - req1.params.should.equal :foo => "bar" - - req2 = Rack::Request.new(env) - req2.GET.should.equal "foo" => "bar" - req2.params.should.equal "foo" => "bar" - end - - (0x20...0x7E).collect { |a| - b = a.chr - c = CGI.escape(b) - should "not strip '#{a}' => '#{c}' => '#{b}' escaped character from parameters when accessed as string" do - url = "/?foo=#{c}bar#{c}" - env = Rack::MockRequest.env_for(url) - req2 = Rack::Request.new(env) - req2.GET.should.equal "foo" => "#{b}bar#{b}" - req2.params.should.equal "foo" => "#{b}bar#{b}" - end - } -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_response.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_response.rb deleted file mode 100644 index 7ba1e0e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_response.rb +++ /dev/null @@ -1,313 +0,0 @@ -require 'rack/response' -require 'stringio' - -describe Rack::Response do - should "have sensible default values" do - response = Rack::Response.new - status, header, body = response.finish - status.should.equal 200 - header.should.equal({}) - body.each { |part| - part.should.equal "" - } - - response = Rack::Response.new - status, header, body = *response - status.should.equal 200 - header.should.equal({}) - body.each { |part| - part.should.equal "" - } - end - - it "can be written to" do - response = Rack::Response.new - - _, _, body = response.finish do - response.write "foo" - response.write "bar" - response.write "baz" - end - - parts = [] - body.each { |part| parts << part } - - parts.should.equal ["foo", "bar", "baz"] - end - - it "can set and read headers" do - response = Rack::Response.new - response["Content-Type"].should.equal nil - response["Content-Type"] = "text/plain" - response["Content-Type"].should.equal "text/plain" - end - - it "can override the initial Content-Type with a different case" do - response = Rack::Response.new("", 200, "content-type" => "text/plain") - response["Content-Type"].should.equal "text/plain" - end - - it "can set cookies" do - response = Rack::Response.new - - response.set_cookie "foo", "bar" - response["Set-Cookie"].should.equal "foo=bar" - response.set_cookie "foo2", "bar2" - response["Set-Cookie"].should.equal ["foo=bar", "foo2=bar2"].join("\n") - response.set_cookie "foo3", "bar3" - response["Set-Cookie"].should.equal ["foo=bar", "foo2=bar2", "foo3=bar3"].join("\n") - end - - it "can set cookies with the same name for multiple domains" do - response = Rack::Response.new - response.set_cookie "foo", {:value => "bar", :domain => "sample.example.com"} - response.set_cookie "foo", {:value => "bar", :domain => ".example.com"} - response["Set-Cookie"].should.equal ["foo=bar; domain=sample.example.com", "foo=bar; domain=.example.com"].join("\n") - end - - it "formats the Cookie expiration date accordingly to RFC 6265" do - response = Rack::Response.new - - response.set_cookie "foo", {:value => "bar", :expires => Time.now+10} - response["Set-Cookie"].should.match( - /expires=..., \d\d ... \d\d\d\d \d\d:\d\d:\d\d .../) - end - - it "can set secure cookies" do - response = Rack::Response.new - response.set_cookie "foo", {:value => "bar", :secure => true} - response["Set-Cookie"].should.equal "foo=bar; secure" - end - - it "can set http only cookies" do - response = Rack::Response.new - response.set_cookie "foo", {:value => "bar", :httponly => true} - response["Set-Cookie"].should.equal "foo=bar; HttpOnly" - end - - it "can delete cookies" do - response = Rack::Response.new - response.set_cookie "foo", "bar" - response.set_cookie "foo2", "bar2" - response.delete_cookie "foo" - response["Set-Cookie"].should.equal [ - "foo2=bar2", - "foo=; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000" - ].join("\n") - end - - it "can delete cookies with the same name from multiple domains" do - response = Rack::Response.new - response.set_cookie "foo", {:value => "bar", :domain => "sample.example.com"} - response.set_cookie "foo", {:value => "bar", :domain => ".example.com"} - response["Set-Cookie"].should.equal ["foo=bar; domain=sample.example.com", "foo=bar; domain=.example.com"].join("\n") - response.delete_cookie "foo", :domain => ".example.com" - response["Set-Cookie"].should.equal ["foo=bar; domain=sample.example.com", "foo=; domain=.example.com; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"].join("\n") - response.delete_cookie "foo", :domain => "sample.example.com" - response["Set-Cookie"].should.equal ["foo=; domain=.example.com; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000", - "foo=; domain=sample.example.com; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"].join("\n") - end - - it "can delete cookies with the same name with different paths" do - response = Rack::Response.new - response.set_cookie "foo", {:value => "bar", :path => "/"} - response.set_cookie "foo", {:value => "bar", :path => "/path"} - response["Set-Cookie"].should.equal ["foo=bar; path=/", - "foo=bar; path=/path"].join("\n") - - response.delete_cookie "foo", :path => "/path" - response["Set-Cookie"].should.equal ["foo=bar; path=/", - "foo=; path=/path; max-age=0; expires=Thu, 01 Jan 1970 00:00:00 -0000"].join("\n") - end - - it "can do redirects" do - response = Rack::Response.new - response.redirect "/foo" - status, header, body = response.finish - status.should.equal 302 - header["Location"].should.equal "/foo" - - response = Rack::Response.new - response.redirect "/foo", 307 - status, header, body = response.finish - - status.should.equal 307 - end - - it "has a useful constructor" do - r = Rack::Response.new("foo") - status, header, body = r.finish - str = ""; body.each { |part| str << part } - str.should.equal "foo" - - r = Rack::Response.new(["foo", "bar"]) - status, header, body = r.finish - str = ""; body.each { |part| str << part } - str.should.equal "foobar" - - object_with_each = Object.new - def object_with_each.each - yield "foo" - yield "bar" - end - r = Rack::Response.new(object_with_each) - r.write "foo" - status, header, body = r.finish - str = ""; body.each { |part| str << part } - str.should.equal "foobarfoo" - - r = Rack::Response.new([], 500) - r.status.should.equal 500 - - r = Rack::Response.new([], "200 OK") - r.status.should.equal 200 - end - - it "has a constructor that can take a block" do - r = Rack::Response.new { |res| - res.status = 404 - res.write "foo" - } - status, _, body = r.finish - str = ""; body.each { |part| str << part } - str.should.equal "foo" - status.should.equal 404 - end - - it "doesn't return invalid responses" do - r = Rack::Response.new(["foo", "bar"], 204) - _, header, body = r.finish - str = ""; body.each { |part| str << part } - str.should.be.empty - header["Content-Type"].should.equal nil - header['Content-Length'].should.equal nil - - lambda { - Rack::Response.new(Object.new) - }.should.raise(TypeError). - message.should =~ /stringable or iterable required/ - end - - it "knows if it's empty" do - r = Rack::Response.new - r.should.be.empty - r.write "foo" - r.should.not.be.empty - - r = Rack::Response.new - r.should.be.empty - r.finish - r.should.be.empty - - r = Rack::Response.new - r.should.be.empty - r.finish { } - r.should.not.be.empty - end - - should "provide access to the HTTP status" do - res = Rack::Response.new - res.status = 200 - res.should.be.successful - res.should.be.ok - - res.status = 400 - res.should.not.be.successful - res.should.be.client_error - res.should.be.bad_request - - res.status = 404 - res.should.not.be.successful - res.should.be.client_error - res.should.be.not_found - - res.status = 405 - res.should.not.be.successful - res.should.be.client_error - res.should.be.method_not_allowed - - res.status = 422 - res.should.not.be.successful - res.should.be.client_error - res.should.be.unprocessable - - res.status = 501 - res.should.not.be.successful - res.should.be.server_error - - res.status = 307 - res.should.be.redirect - end - - should "provide access to the HTTP headers" do - res = Rack::Response.new - res["Content-Type"] = "text/yaml" - - res.should.include "Content-Type" - res.headers["Content-Type"].should.equal "text/yaml" - res["Content-Type"].should.equal "text/yaml" - res.content_type.should.equal "text/yaml" - res.content_length.should.be.nil - res.location.should.be.nil - end - - it "does not add or change Content-Length when #finish()ing" do - res = Rack::Response.new - res.status = 200 - res.finish - res.headers["Content-Length"].should.be.nil - - res = Rack::Response.new - res.status = 200 - res.headers["Content-Length"] = "10" - res.finish - res.headers["Content-Length"].should.equal "10" - end - - it "updates Content-Length when body appended to using #write" do - res = Rack::Response.new - res.status = 200 - res.headers["Content-Length"].should.be.nil - res.write "Hi" - res.headers["Content-Length"].should.equal "2" - res.write " there" - res.headers["Content-Length"].should.equal "8" - end - - it "calls close on #body" do - res = Rack::Response.new - res.body = StringIO.new - res.close - res.body.should.be.closed - end - - it "calls close on #body when 204, 205, or 304" do - res = Rack::Response.new - res.body = StringIO.new - res.finish - res.body.should.not.be.closed - - res.status = 204 - _, _, b = res.finish - res.body.should.be.closed - b.should.not.equal res.body - - res.body = StringIO.new - res.status = 205 - _, _, b = res.finish - res.body.should.be.closed - b.should.not.equal res.body - - res.body = StringIO.new - res.status = 304 - _, _, b = res.finish - res.body.should.be.closed - b.should.not.equal res.body - end - - it "wraps the body from #to_ary to prevent infinite loops" do - res = Rack::Response.new - res.finish.last.should.not.respond_to?(:to_ary) - lambda { res.finish.last.to_ary }.should.raise(NoMethodError) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_rewindable_input.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_rewindable_input.rb deleted file mode 100644 index 025d830..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_rewindable_input.rb +++ /dev/null @@ -1,118 +0,0 @@ -require 'stringio' -require 'rack/rewindable_input' - -shared "a rewindable IO object" do - before do - @rio = Rack::RewindableInput.new(@io) - end - - should "be able to handle to read()" do - @rio.read.should.equal "hello world" - end - - should "be able to handle to read(nil)" do - @rio.read(nil).should.equal "hello world" - end - - should "be able to handle to read(length)" do - @rio.read(1).should.equal "h" - end - - should "be able to handle to read(length, buffer)" do - buffer = "" - result = @rio.read(1, buffer) - result.should.equal "h" - result.object_id.should.equal buffer.object_id - end - - should "be able to handle to read(nil, buffer)" do - buffer = "" - result = @rio.read(nil, buffer) - result.should.equal "hello world" - result.object_id.should.equal buffer.object_id - end - - should "rewind to the beginning when #rewind is called" do - @rio.read(1) - @rio.rewind - @rio.read.should.equal "hello world" - end - - should "be able to handle gets" do - @rio.gets.should == "hello world" - end - - should "be able to handle each" do - array = [] - @rio.each do |data| - array << data - end - array.should.equal(["hello world"]) - end - - should "not buffer into a Tempfile if no data has been read yet" do - @rio.instance_variable_get(:@rewindable_io).should.be.nil - end - - should "buffer into a Tempfile when data has been consumed for the first time" do - @rio.read(1) - tempfile = @rio.instance_variable_get(:@rewindable_io) - tempfile.should.not.be.nil - @rio.read(1) - tempfile2 = @rio.instance_variable_get(:@rewindable_io) - tempfile2.path.should == tempfile.path - end - - should "close the underlying tempfile upon calling #close" do - @rio.read(1) - tempfile = @rio.instance_variable_get(:@rewindable_io) - @rio.close - tempfile.should.be.closed - end - - should "be possible to call #close when no data has been buffered yet" do - lambda{ @rio.close }.should.not.raise - end - - should "be possible to call #close multiple times" do - lambda{ - @rio.close - @rio.close - }.should.not.raise - end - - @rio.close - @rio = nil -end - -describe Rack::RewindableInput do - describe "given an IO object that is already rewindable" do - before do - @io = StringIO.new("hello world") - end - - behaves_like "a rewindable IO object" - end - - describe "given an IO object that is not rewindable" do - before do - @io = StringIO.new("hello world") - @io.instance_eval do - undef :rewind - end - end - - behaves_like "a rewindable IO object" - end - - describe "given an IO object whose rewind method raises Errno::ESPIPE" do - before do - @io = StringIO.new("hello world") - def @io.rewind - raise Errno::ESPIPE, "You can't rewind this!" - end - end - - behaves_like "a rewindable IO object" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_runtime.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_runtime.rb deleted file mode 100644 index f9897a1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_runtime.rb +++ /dev/null @@ -1,49 +0,0 @@ -require 'rack/lint' -require 'rack/mock' -require 'rack/runtime' - -describe Rack::Runtime do - def runtime_app(app, *args) - Rack::Lint.new Rack::Runtime.new(app, *args) - end - - def request - Rack::MockRequest.env_for - end - - it "sets X-Runtime is none is set" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, "Hello, World!"] } - response = runtime_app(app).call(request) - response[1]['X-Runtime'].should =~ /[\d\.]+/ - end - - it "doesn't set the X-Runtime if it is already set" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain', "X-Runtime" => "foobar"}, "Hello, World!"] } - response = runtime_app(app).call(request) - response[1]['X-Runtime'].should == "foobar" - end - - should "allow a suffix to be set" do - app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, "Hello, World!"] } - response = runtime_app(app, "Test").call(request) - response[1]['X-Runtime-Test'].should =~ /[\d\.]+/ - end - - should "allow multiple timers to be set" do - app = lambda { |env| sleep 0.1; [200, {'Content-Type' => 'text/plain'}, "Hello, World!"] } - runtime = runtime_app(app, "App") - - # wrap many times to guarantee a measurable difference - 100.times do |i| - runtime = Rack::Runtime.new(runtime, i.to_s) - end - runtime = Rack::Runtime.new(runtime, "All") - - response = runtime.call(request) - - response[1]['X-Runtime-App'].should =~ /[\d\.]+/ - response[1]['X-Runtime-All'].should =~ /[\d\.]+/ - - Float(response[1]['X-Runtime-All']).should > Float(response[1]['X-Runtime-App']) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_sendfile.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_sendfile.rb deleted file mode 100644 index 7c9acd6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_sendfile.rb +++ /dev/null @@ -1,130 +0,0 @@ -require 'fileutils' -require 'rack/lint' -require 'rack/sendfile' -require 'rack/mock' -require 'tmpdir' - -describe Rack::File do - should "respond to #to_path" do - Rack::File.new(Dir.pwd).should.respond_to :to_path - end -end - -describe Rack::Sendfile do - def sendfile_body - FileUtils.touch File.join(Dir.tmpdir, "rack_sendfile") - res = ['Hello World'] - def res.to_path ; File.join(Dir.tmpdir, "rack_sendfile") ; end - res - end - - def simple_app(body=sendfile_body) - lambda { |env| [200, {'Content-Type' => 'text/plain'}, body] } - end - - def sendfile_app(body, mappings = []) - Rack::Lint.new Rack::Sendfile.new(simple_app(body), nil, mappings) - end - - def request(headers={}, body=sendfile_body, mappings=[]) - yield Rack::MockRequest.new(sendfile_app(body, mappings)).get('/', headers) - end - - def open_file(path) - Class.new(File) do - unless method_defined?(:to_path) - alias :to_path :path - end - end.open(path, 'wb+') - end - - it "does nothing when no X-Sendfile-Type header present" do - request do |response| - response.should.be.ok - response.body.should.equal 'Hello World' - response.headers.should.not.include 'X-Sendfile' - end - end - - it "sets X-Sendfile response header and discards body" do - request 'HTTP_X_SENDFILE_TYPE' => 'X-Sendfile' do |response| - response.should.be.ok - response.body.should.be.empty - response.headers['Content-Length'].should.equal '0' - response.headers['X-Sendfile'].should.equal File.join(Dir.tmpdir, "rack_sendfile") - end - end - - it "sets X-Lighttpd-Send-File response header and discards body" do - request 'HTTP_X_SENDFILE_TYPE' => 'X-Lighttpd-Send-File' do |response| - response.should.be.ok - response.body.should.be.empty - response.headers['Content-Length'].should.equal '0' - response.headers['X-Lighttpd-Send-File'].should.equal File.join(Dir.tmpdir, "rack_sendfile") - end - end - - it "sets X-Accel-Redirect response header and discards body" do - headers = { - 'HTTP_X_SENDFILE_TYPE' => 'X-Accel-Redirect', - 'HTTP_X_ACCEL_MAPPING' => "#{Dir.tmpdir}/=/foo/bar/" - } - request headers do |response| - response.should.be.ok - response.body.should.be.empty - response.headers['Content-Length'].should.equal '0' - response.headers['X-Accel-Redirect'].should.equal '/foo/bar/rack_sendfile' - end - end - - it 'writes to rack.error when no X-Accel-Mapping is specified' do - request 'HTTP_X_SENDFILE_TYPE' => 'X-Accel-Redirect' do |response| - response.should.be.ok - response.body.should.equal 'Hello World' - response.headers.should.not.include 'X-Accel-Redirect' - response.errors.should.include 'X-Accel-Mapping' - end - end - - it 'does nothing when body does not respond to #to_path' do - request({'HTTP_X_SENDFILE_TYPE' => 'X-Sendfile'}, ['Not a file...']) do |response| - response.body.should.equal 'Not a file...' - response.headers.should.not.include 'X-Sendfile' - end - end - - it "sets X-Accel-Redirect response header and discards body when initialized with multiple mappings" do - begin - dir1 = Dir.mktmpdir - dir2 = Dir.mktmpdir - - first_body = open_file(File.join(dir1, 'rack_sendfile')) - first_body.puts 'hello world' - - second_body = open_file(File.join(dir2, 'rack_sendfile')) - second_body.puts 'goodbye world' - - mappings = [ - ["#{dir1}/", '/foo/bar/'], - ["#{dir2}/", '/wibble/'] - ] - - request({'HTTP_X_SENDFILE_TYPE' => 'X-Accel-Redirect'}, first_body, mappings) do |response| - response.should.be.ok - response.body.should.be.empty - response.headers['Content-Length'].should.equal '0' - response.headers['X-Accel-Redirect'].should.equal '/foo/bar/rack_sendfile' - end - - request({'HTTP_X_SENDFILE_TYPE' => 'X-Accel-Redirect'}, second_body, mappings) do |response| - response.should.be.ok - response.body.should.be.empty - response.headers['Content-Length'].should.equal '0' - response.headers['X-Accel-Redirect'].should.equal '/wibble/rack_sendfile' - end - ensure - FileUtils.remove_entry_secure dir1 - FileUtils.remove_entry_secure dir2 - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_server.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_server.rb deleted file mode 100644 index 44d4bcb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_server.rb +++ /dev/null @@ -1,143 +0,0 @@ -require 'rack' -require 'rack/server' -require 'tempfile' -require 'socket' -require 'open-uri' - -describe Rack::Server do - - def app - lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['success']] } - end - - def with_stderr - old, $stderr = $stderr, StringIO.new - yield $stderr - ensure - $stderr = old - end - - it "overrides :config if :app is passed in" do - server = Rack::Server.new(:app => "FOO") - server.app.should.equal "FOO" - end - - should "prefer to use :builder when it is passed in" do - server = Rack::Server.new(:builder => "run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['success']] }") - server.app.class.should.equal Proc - Rack::MockRequest.new(server.app).get("/").body.to_s.should.equal 'success' - end - - should "not include Rack::Lint in deployment or none environments" do - server = Rack::Server.new(:app => 'foo') - server.middleware['deployment'].flatten.should.not.include(Rack::Lint) - server.middleware['none'].flatten.should.not.include(Rack::Lint) - end - - should "not include Rack::ShowExceptions in deployment or none environments" do - server = Rack::Server.new(:app => 'foo') - server.middleware['deployment'].flatten.should.not.include(Rack::ShowExceptions) - server.middleware['none'].flatten.should.not.include(Rack::ShowExceptions) - end - - should "support CGI" do - begin - o, ENV["REQUEST_METHOD"] = ENV["REQUEST_METHOD"], 'foo' - server = Rack::Server.new(:app => 'foo') - server.server.name =~ /CGI/ - Rack::Server.logging_middleware.call(server).should.eql(nil) - ensure - ENV['REQUEST_METHOD'] = o - end - end - - should "not force any middleware under the none configuration" do - server = Rack::Server.new(:app => 'foo') - server.middleware['none'].should.be.empty - end - - should "use a full path to the pidfile" do - # avoids issues with daemonize chdir - opts = Rack::Server.new.send(:parse_options, %w[--pid testing.pid]) - opts[:pid].should.eql(::File.expand_path('testing.pid')) - end - - should "run a server" do - pidfile = Tempfile.open('pidfile') { |f| break f }.path - FileUtils.rm pidfile - server = Rack::Server.new( - :app => app, - :environment => 'none', - :pid => pidfile, - :Port => TCPServer.open('127.0.0.1', 0){|s| s.addr[1] }, - :Host => '127.0.0.1', - :daemonize => false, - :server => 'webrick' - ) - t = Thread.new { server.start { |s| Thread.current[:server] = s } } - t.join(0.01) until t[:server] && t[:server].status != :Stop - body = open("http://127.0.0.1:#{server.options[:Port]}/") { |f| f.read } - body.should.eql('success') - - Process.kill(:INT, $$) - t.join - open(pidfile) { |f| f.read.should.eql $$.to_s } - end - - should "check pid file presence and running process" do - pidfile = Tempfile.open('pidfile') { |f| f.write($$); break f }.path - server = Rack::Server.new(:pid => pidfile) - server.send(:pidfile_process_status).should.eql :running - end - - should "check pid file presence and dead process" do - dead_pid = `echo $$`.to_i - pidfile = Tempfile.open('pidfile') { |f| f.write(dead_pid); break f }.path - server = Rack::Server.new(:pid => pidfile) - server.send(:pidfile_process_status).should.eql :dead - end - - should "check pid file presence and exited process" do - pidfile = Tempfile.open('pidfile') { |f| break f }.path - ::File.delete(pidfile) - server = Rack::Server.new(:pid => pidfile) - server.send(:pidfile_process_status).should.eql :exited - end - - should "check pid file presence and not owned process" do - pidfile = Tempfile.open('pidfile') { |f| f.write(1); break f }.path - server = Rack::Server.new(:pid => pidfile) - server.send(:pidfile_process_status).should.eql :not_owned - end - - should "not write pid file when it is created after check" do - pidfile = Tempfile.open('pidfile') { |f| break f }.path - ::File.delete(pidfile) - server = Rack::Server.new(:pid => pidfile) - ::File.open(pidfile, 'w') { |f| f.write(1) } - with_stderr do |err| - should.raise(SystemExit) do - server.send(:write_pid) - end - err.rewind - output = err.read - output.should.match(/already running/) - output.should.include? pidfile - end - end - - should "inform the user about existing pidfiles with running processes" do - pidfile = Tempfile.open('pidfile') { |f| f.write(1); break f }.path - server = Rack::Server.new(:pid => pidfile) - with_stderr do |err| - should.raise(SystemExit) do - server.start - end - err.rewind - output = err.read - output.should.match(/already running/) - output.should.include? pidfile - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_abstract_id.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_abstract_id.rb deleted file mode 100644 index 911f43b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_abstract_id.rb +++ /dev/null @@ -1,53 +0,0 @@ -### WARNING: there be hax in this file. - -require 'rack/session/abstract/id' - -describe Rack::Session::Abstract::ID do - id = Rack::Session::Abstract::ID - - def silence_warning - o, $VERBOSE = $VERBOSE, nil - yield - ensure - $VERBOSE = o - end - - def reload_id - $".delete $".find { |part| part =~ %r{session/abstract/id.rb} } - silence_warning { require 'rack/session/abstract/id' } - end - - should "use securerandom when available" do - begin - fake = false - silence_warning do - ::SecureRandom = fake = true unless defined?(SecureRandom) - end - reload_id - id::DEFAULT_OPTIONS[:secure_random].should.eql(fake || SecureRandom) - ensure - Object.send(:remove_const, :SecureRandom) if fake - end - end - - should "not use securerandom when unavailable" do - begin - sr = Object.send(:remove_const, :SecureRandom) if defined?(SecureRandom) - reload_id - id::DEFAULT_OPTIONS[:secure_random].should.eql false - ensure - ::SecureRandom = sr if defined?(sr) - end - end - - should "allow to use another securerandom provider" do - secure_random = Class.new do - def hex(*args) - 'fake_hex' - end - end - id = Rack::Session::Abstract::ID.new nil, :secure_random => secure_random.new - id.send(:generate_sid).should.eql 'fake_hex' - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_cookie.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_cookie.rb deleted file mode 100644 index 8256f76..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_cookie.rb +++ /dev/null @@ -1,367 +0,0 @@ -require 'rack/session/cookie' -require 'rack/lint' -require 'rack/mock' - -describe Rack::Session::Cookie do - incrementor = lambda do |env| - env["rack.session"]["counter"] ||= 0 - env["rack.session"]["counter"] += 1 - hash = env["rack.session"].dup - hash.delete("session_id") - Rack::Response.new(hash.inspect).to_a - end - - session_id = lambda do |env| - Rack::Response.new(env["rack.session"].to_hash.inspect).to_a - end - - session_option = lambda do |opt| - lambda do |env| - Rack::Response.new(env["rack.session.options"][opt].inspect).to_a - end - end - - nothing = lambda do |env| - Rack::Response.new("Nothing").to_a - end - - renewer = lambda do |env| - env["rack.session.options"][:renew] = true - Rack::Response.new("Nothing").to_a - end - - only_session_id = lambda do |env| - Rack::Response.new(env["rack.session"]["session_id"].to_s).to_a - end - - bigcookie = lambda do |env| - env["rack.session"]["cookie"] = "big" * 3000 - Rack::Response.new(env["rack.session"].inspect).to_a - end - - destroy_session = lambda do |env| - env["rack.session"].destroy - Rack::Response.new("Nothing").to_a - end - - def response_for(options={}) - request_options = options.fetch(:request, {}) - cookie = if options[:cookie].is_a?(Rack::Response) - options[:cookie]["Set-Cookie"] - else - options[:cookie] - end - request_options["HTTP_COOKIE"] = cookie || "" - - app_with_cookie = Rack::Session::Cookie.new(*options[:app]) - app_with_cookie = Rack::Lint.new(app_with_cookie) - Rack::MockRequest.new(app_with_cookie).get("/", request_options) - end - - before do - @warnings = warnings = [] - Rack::Session::Cookie.class_eval do - define_method(:warn) { |m| warnings << m } - end - end - - after do - Rack::Session::Cookie.class_eval { remove_method :warn } - end - - describe 'Base64' do - it 'uses base64 to encode' do - coder = Rack::Session::Cookie::Base64.new - str = 'fuuuuu' - coder.encode(str).should.equal [str].pack('m') - end - - it 'uses base64 to decode' do - coder = Rack::Session::Cookie::Base64.new - str = ['fuuuuu'].pack('m') - coder.decode(str).should.equal str.unpack('m').first - end - - describe 'Marshal' do - it 'marshals and base64 encodes' do - coder = Rack::Session::Cookie::Base64::Marshal.new - str = 'fuuuuu' - coder.encode(str).should.equal [::Marshal.dump(str)].pack('m') - end - - it 'marshals and base64 decodes' do - coder = Rack::Session::Cookie::Base64::Marshal.new - str = [::Marshal.dump('fuuuuu')].pack('m') - coder.decode(str).should.equal ::Marshal.load(str.unpack('m').first) - end - - it 'rescues failures on decode' do - coder = Rack::Session::Cookie::Base64::Marshal.new - coder.decode('lulz').should.equal nil - end - end - - describe 'JSON' do - it 'marshals and base64 encodes' do - coder = Rack::Session::Cookie::Base64::JSON.new - obj = %w[fuuuuu] - coder.encode(obj).should.equal [::Rack::Utils::OkJson.encode(obj)].pack('m') - end - - it 'marshals and base64 decodes' do - coder = Rack::Session::Cookie::Base64::JSON.new - str = [::Rack::Utils::OkJson.encode(%w[fuuuuu])].pack('m') - coder.decode(str).should.equal ::Rack::Utils::OkJson.decode(str.unpack('m').first) - end - - it 'rescues failures on decode' do - coder = Rack::Session::Cookie::Base64::JSON.new - coder.decode('lulz').should.equal nil - end - end - end - - it "warns if no secret is given" do - cookie = Rack::Session::Cookie.new(incrementor) - @warnings.first.should =~ /no secret/i - @warnings.clear - cookie = Rack::Session::Cookie.new(incrementor, :secret => 'abc') - @warnings.should.be.empty? - end - - it 'uses a coder' do - identity = Class.new { - attr_reader :calls - - def initialize - @calls = [] - end - - def encode(str); @calls << :encode; str; end - def decode(str); @calls << :decode; str; end - }.new - response = response_for(:app => [incrementor, { :coder => identity }]) - - response["Set-Cookie"].should.include("rack.session=") - response.body.should.equal '{"counter"=>1}' - identity.calls.should.equal [:decode, :encode] - end - - it "creates a new cookie" do - response = response_for(:app => incrementor) - response["Set-Cookie"].should.include("rack.session=") - response.body.should.equal '{"counter"=>1}' - end - - it "loads from a cookie" do - response = response_for(:app => incrementor) - - response = response_for(:app => incrementor, :cookie => response) - response.body.should.equal '{"counter"=>2}' - - response = response_for(:app => incrementor, :cookie => response) - response.body.should.equal '{"counter"=>3}' - end - - it "renew session id" do - response = response_for(:app => incrementor) - cookie = response['Set-Cookie'] - response = response_for(:app => only_session_id, :cookie => cookie) - cookie = response['Set-Cookie'] if response['Set-Cookie'] - - response.body.should.not.equal "" - old_session_id = response.body - - response = response_for(:app => renewer, :cookie => cookie) - cookie = response['Set-Cookie'] if response['Set-Cookie'] - response = response_for(:app => only_session_id, :cookie => cookie) - - response.body.should.not.equal "" - response.body.should.not.equal old_session_id - end - - it "destroys session" do - response = response_for(:app => incrementor) - response = response_for(:app => only_session_id, :cookie => response) - - response.body.should.not.equal "" - old_session_id = response.body - - response = response_for(:app => destroy_session, :cookie => response) - response = response_for(:app => only_session_id, :cookie => response) - - response.body.should.not.equal "" - response.body.should.not.equal old_session_id - end - - it "survives broken cookies" do - response = response_for( - :app => incrementor, - :cookie => "rack.session=blarghfasel" - ) - response.body.should.equal '{"counter"=>1}' - - response = response_for( - :app => [incrementor, { :secret => "test" }], - :cookie => "rack.session=" - ) - response.body.should.equal '{"counter"=>1}' - end - - it "barks on too big cookies" do - lambda{ - response_for(:app => bigcookie, :request => { :fatal => true }) - }.should.raise(Rack::MockRequest::FatalWarning) - end - - it "loads from a cookie with integrity hash" do - app = [incrementor, { :secret => "test" }] - - response = response_for(:app => app) - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>2}' - - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>3}' - - app = [incrementor, { :secret => "other" }] - - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>1}' - end - - it "loads from a cookie wih accept-only integrity hash for graceful key rotation" do - response = response_for(:app => [incrementor, { :secret => "test" }]) - - app = [incrementor, { :secret => "test2", :old_secret => "test" }] - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>2}' - - app = [incrementor, { :secret => "test3", :old_secret => "test2" }] - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>3}' - end - - it "ignores tampered with session cookies" do - app = [incrementor, { :secret => "test" }] - response = response_for(:app => app) - response.body.should.equal '{"counter"=>1}' - - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>2}' - - _, digest = response["Set-Cookie"].split("--") - tampered_with_cookie = "hackerman-was-here" + "--" + digest - - response = response_for(:app => app, :cookie => tampered_with_cookie) - response.body.should.equal '{"counter"=>1}' - end - - it "supports either of secret or old_secret" do - app = [incrementor, { :secret => "test" }] - response = response_for(:app => app) - response.body.should.equal '{"counter"=>1}' - - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>2}' - - app = [incrementor, { :old_secret => "test" }] - response = response_for(:app => app) - response.body.should.equal '{"counter"=>1}' - - response = response_for(:app => app, :cookie => response) - response.body.should.equal '{"counter"=>2}' - end - - it "can handle Rack::Lint middleware" do - response = response_for(:app => incrementor) - - lint = Rack::Lint.new(session_id) - response = response_for(:app => lint, :cookie => response) - response.body.should.not.be.nil - end - - it "can handle middleware that inspects the env" do - class TestEnvInspector - def initialize(app) - @app = app - end - def call(env) - env.inspect - @app.call(env) - end - end - - response = response_for(:app => incrementor) - - inspector = TestEnvInspector.new(session_id) - response = response_for(:app => inspector, :cookie => response) - response.body.should.not.be.nil - end - - it "returns the session id in the session hash" do - response = response_for(:app => incrementor) - response.body.should.equal '{"counter"=>1}' - - response = response_for(:app => session_id, :cookie => response) - response.body.should.match(/"session_id"=>/) - response.body.should.match(/"counter"=>1/) - end - - it "does not return a cookie if set to secure but not using ssl" do - app = [incrementor, { :secure => true }] - - response = response_for(:app => app) - response["Set-Cookie"].should.be.nil - - response = response_for(:app => app, :request => { "HTTPS" => "on" }) - response["Set-Cookie"].should.not.be.nil - response["Set-Cookie"].should.match(/secure/) - end - - it "does not return a cookie if cookie was not read/written" do - response = response_for(:app => nothing) - response["Set-Cookie"].should.be.nil - end - - it "does not return a cookie if cookie was not written (only read)" do - response = response_for(:app => session_id) - response["Set-Cookie"].should.be.nil - end - - it "returns even if not read/written if :expire_after is set" do - app = [nothing, { :expire_after => 3600 }] - request = { "rack.session" => { "not" => "empty" }} - response = response_for(:app => app, :request => request) - response["Set-Cookie"].should.not.be.nil - end - - it "returns no cookie if no data was written and no session was created previously, even if :expire_after is set" do - app = [nothing, { :expire_after => 3600 }] - response = response_for(:app => app) - response["Set-Cookie"].should.be.nil - end - - it "exposes :secret in env['rack.session.option']" do - response = response_for(:app => [session_option[:secret], { :secret => "foo" }]) - response.body.should == '"foo"' - end - - it "exposes :coder in env['rack.session.option']" do - response = response_for(:app => session_option[:coder]) - response.body.should.match(/Base64::Marshal/) - end - - it "allows passing in a hash with session data from middleware in front" do - request = { 'rack.session' => { :foo => 'bar' }} - response = response_for(:app => session_id, :request => request) - response.body.should.match(/foo/) - end - - it "allows modifying session data with session data from middleware in front" do - request = { 'rack.session' => { :foo => 'bar' }} - response = response_for(:app => incrementor, :request => request) - response.body.should.match(/counter/) - response.body.should.match(/foo/) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_memcache.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_memcache.rb deleted file mode 100644 index 6e5325b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_memcache.rb +++ /dev/null @@ -1,321 +0,0 @@ -begin - require 'rack/session/memcache' - require 'rack/lint' - require 'rack/mock' - require 'thread' - - describe Rack::Session::Memcache do - session_key = Rack::Session::Memcache::DEFAULT_OPTIONS[:key] - session_match = /#{session_key}=([0-9a-fA-F]+);/ - incrementor = lambda do |env| - env["rack.session"]["counter"] ||= 0 - env["rack.session"]["counter"] += 1 - Rack::Response.new(env["rack.session"].inspect).to_a - end - drop_session = Rack::Lint.new(proc do |env| - env['rack.session.options'][:drop] = true - incrementor.call(env) - end) - renew_session = Rack::Lint.new(proc do |env| - env['rack.session.options'][:renew] = true - incrementor.call(env) - end) - defer_session = Rack::Lint.new(proc do |env| - env['rack.session.options'][:defer] = true - incrementor.call(env) - end) - skip_session = Rack::Lint.new(proc do |env| - env['rack.session.options'][:skip] = true - incrementor.call(env) - end) - incrementor = Rack::Lint.new(incrementor) - - # test memcache connection - Rack::Session::Memcache.new(incrementor) - - it "faults on no connection" do - lambda{ - Rack::Session::Memcache.new(incrementor, :memcache_server => 'nosuchserver') - }.should.raise - end - - it "connects to existing server" do - test_pool = MemCache.new(incrementor, :namespace => 'test:rack:session') - test_pool.namespace.should.equal 'test:rack:session' - end - - it "passes options to MemCache" do - pool = Rack::Session::Memcache.new(incrementor, :namespace => 'test:rack:session') - pool.pool.namespace.should.equal 'test:rack:session' - end - - it "creates a new cookie" do - pool = Rack::Session::Memcache.new(incrementor) - res = Rack::MockRequest.new(pool).get("/") - res["Set-Cookie"].should.include("#{session_key}=") - res.body.should.equal '{"counter"=>1}' - end - - it "determines session from a cookie" do - pool = Rack::Session::Memcache.new(incrementor) - req = Rack::MockRequest.new(pool) - res = req.get("/") - cookie = res["Set-Cookie"] - req.get("/", "HTTP_COOKIE" => cookie). - body.should.equal '{"counter"=>2}' - req.get("/", "HTTP_COOKIE" => cookie). - body.should.equal '{"counter"=>3}' - end - - it "determines session only from a cookie by default" do - pool = Rack::Session::Memcache.new(incrementor) - req = Rack::MockRequest.new(pool) - res = req.get("/") - sid = res["Set-Cookie"][session_match, 1] - req.get("/?rack.session=#{sid}"). - body.should.equal '{"counter"=>1}' - req.get("/?rack.session=#{sid}"). - body.should.equal '{"counter"=>1}' - end - - it "determines session from params" do - pool = Rack::Session::Memcache.new(incrementor, :cookie_only => false) - req = Rack::MockRequest.new(pool) - res = req.get("/") - sid = res["Set-Cookie"][session_match, 1] - req.get("/?rack.session=#{sid}"). - body.should.equal '{"counter"=>2}' - req.get("/?rack.session=#{sid}"). - body.should.equal '{"counter"=>3}' - end - - it "survives nonexistant cookies" do - bad_cookie = "rack.session=blarghfasel" - pool = Rack::Session::Memcache.new(incrementor) - res = Rack::MockRequest.new(pool). - get("/", "HTTP_COOKIE" => bad_cookie) - res.body.should.equal '{"counter"=>1}' - cookie = res["Set-Cookie"][session_match] - cookie.should.not.match(/#{bad_cookie}/) - end - - it "maintains freshness" do - pool = Rack::Session::Memcache.new(incrementor, :expire_after => 3) - res = Rack::MockRequest.new(pool).get('/') - res.body.should.include '"counter"=>1' - cookie = res["Set-Cookie"] - res = Rack::MockRequest.new(pool).get('/', "HTTP_COOKIE" => cookie) - res["Set-Cookie"].should.equal cookie - res.body.should.include '"counter"=>2' - puts 'Sleeping to expire session' if $DEBUG - sleep 4 - res = Rack::MockRequest.new(pool).get('/', "HTTP_COOKIE" => cookie) - res["Set-Cookie"].should.not.equal cookie - res.body.should.include '"counter"=>1' - end - - it "does not send the same session id if it did not change" do - pool = Rack::Session::Memcache.new(incrementor) - req = Rack::MockRequest.new(pool) - - res0 = req.get("/") - cookie = res0["Set-Cookie"][session_match] - res0.body.should.equal '{"counter"=>1}' - - res1 = req.get("/", "HTTP_COOKIE" => cookie) - res1["Set-Cookie"].should.be.nil - res1.body.should.equal '{"counter"=>2}' - - res2 = req.get("/", "HTTP_COOKIE" => cookie) - res2["Set-Cookie"].should.be.nil - res2.body.should.equal '{"counter"=>3}' - end - - it "deletes cookies with :drop option" do - pool = Rack::Session::Memcache.new(incrementor) - req = Rack::MockRequest.new(pool) - drop = Rack::Utils::Context.new(pool, drop_session) - dreq = Rack::MockRequest.new(drop) - - res1 = req.get("/") - session = (cookie = res1["Set-Cookie"])[session_match] - res1.body.should.equal '{"counter"=>1}' - - res2 = dreq.get("/", "HTTP_COOKIE" => cookie) - res2["Set-Cookie"].should.equal nil - res2.body.should.equal '{"counter"=>2}' - - res3 = req.get("/", "HTTP_COOKIE" => cookie) - res3["Set-Cookie"][session_match].should.not.equal session - res3.body.should.equal '{"counter"=>1}' - end - - it "provides new session id with :renew option" do - pool = Rack::Session::Memcache.new(incrementor) - req = Rack::MockRequest.new(pool) - renew = Rack::Utils::Context.new(pool, renew_session) - rreq = Rack::MockRequest.new(renew) - - res1 = req.get("/") - session = (cookie = res1["Set-Cookie"])[session_match] - res1.body.should.equal '{"counter"=>1}' - - res2 = rreq.get("/", "HTTP_COOKIE" => cookie) - new_cookie = res2["Set-Cookie"] - new_session = new_cookie[session_match] - new_session.should.not.equal session - res2.body.should.equal '{"counter"=>2}' - - res3 = req.get("/", "HTTP_COOKIE" => new_cookie) - res3.body.should.equal '{"counter"=>3}' - - # Old cookie was deleted - res4 = req.get("/", "HTTP_COOKIE" => cookie) - res4.body.should.equal '{"counter"=>1}' - end - - it "omits cookie with :defer option but still updates the state" do - pool = Rack::Session::Memcache.new(incrementor) - count = Rack::Utils::Context.new(pool, incrementor) - defer = Rack::Utils::Context.new(pool, defer_session) - dreq = Rack::MockRequest.new(defer) - creq = Rack::MockRequest.new(count) - - res0 = dreq.get("/") - res0["Set-Cookie"].should.equal nil - res0.body.should.equal '{"counter"=>1}' - - res0 = creq.get("/") - res1 = dreq.get("/", "HTTP_COOKIE" => res0["Set-Cookie"]) - res1.body.should.equal '{"counter"=>2}' - res2 = dreq.get("/", "HTTP_COOKIE" => res0["Set-Cookie"]) - res2.body.should.equal '{"counter"=>3}' - end - - it "omits cookie and state update with :skip option" do - pool = Rack::Session::Memcache.new(incrementor) - count = Rack::Utils::Context.new(pool, incrementor) - skip = Rack::Utils::Context.new(pool, skip_session) - sreq = Rack::MockRequest.new(skip) - creq = Rack::MockRequest.new(count) - - res0 = sreq.get("/") - res0["Set-Cookie"].should.equal nil - res0.body.should.equal '{"counter"=>1}' - - res0 = creq.get("/") - res1 = sreq.get("/", "HTTP_COOKIE" => res0["Set-Cookie"]) - res1.body.should.equal '{"counter"=>2}' - res2 = sreq.get("/", "HTTP_COOKIE" => res0["Set-Cookie"]) - res2.body.should.equal '{"counter"=>2}' - end - - it "updates deep hashes correctly" do - hash_check = proc do |env| - session = env['rack.session'] - unless session.include? 'test' - session.update :a => :b, :c => { :d => :e }, - :f => { :g => { :h => :i} }, 'test' => true - else - session[:f][:g][:h] = :j - end - [200, {}, [session.inspect]] - end - pool = Rack::Session::Memcache.new(hash_check) - req = Rack::MockRequest.new(pool) - - res0 = req.get("/") - session_id = (cookie = res0["Set-Cookie"])[session_match, 1] - ses0 = pool.pool.get(session_id, true) - - req.get("/", "HTTP_COOKIE" => cookie) - ses1 = pool.pool.get(session_id, true) - - ses1.should.not.equal ses0 - end - - # anyone know how to do this better? - it "cleanly merges sessions when multithreaded" do - unless $DEBUG - 1.should.equal 1 # fake assertion to appease the mighty bacon - next - end - warn 'Running multithread test for Session::Memcache' - pool = Rack::Session::Memcache.new(incrementor) - req = Rack::MockRequest.new(pool) - - res = req.get('/') - res.body.should.equal '{"counter"=>1}' - cookie = res["Set-Cookie"] - session_id = cookie[session_match, 1] - - delta_incrementor = lambda do |env| - # emulate disconjoinment of threading - env['rack.session'] = env['rack.session'].dup - Thread.stop - env['rack.session'][(Time.now.usec*rand).to_i] = true - incrementor.call(env) - end - tses = Rack::Utils::Context.new pool, delta_incrementor - treq = Rack::MockRequest.new(tses) - tnum = rand(7).to_i+5 - r = Array.new(tnum) do - Thread.new(treq) do |run| - run.get('/', "HTTP_COOKIE" => cookie, 'rack.multithread' => true) - end - end.reverse.map{|t| t.run.join.value } - r.each do |request| - request['Set-Cookie'].should.equal cookie - request.body.should.include '"counter"=>2' - end - - session = pool.pool.get(session_id) - session.size.should.equal tnum+1 # counter - session['counter'].should.equal 2 # meeeh - - tnum = rand(7).to_i+5 - r = Array.new(tnum) do |i| - app = Rack::Utils::Context.new pool, time_delta - req = Rack::MockRequest.new app - Thread.new(req) do |run| - run.get('/', "HTTP_COOKIE" => cookie, 'rack.multithread' => true) - end - end.reverse.map{|t| t.run.join.value } - r.each do |request| - request['Set-Cookie'].should.equal cookie - request.body.should.include '"counter"=>3' - end - - session = pool.pool.get(session_id) - session.size.should.be tnum+1 - session['counter'].should.be 3 - - drop_counter = proc do |env| - env['rack.session'].delete 'counter' - env['rack.session']['foo'] = 'bar' - [200, {'Content-Type'=>'text/plain'}, env['rack.session'].inspect] - end - tses = Rack::Utils::Context.new pool, drop_counter - treq = Rack::MockRequest.new(tses) - tnum = rand(7).to_i+5 - r = Array.new(tnum) do - Thread.new(treq) do |run| - run.get('/', "HTTP_COOKIE" => cookie, 'rack.multithread' => true) - end - end.reverse.map{|t| t.run.join.value } - r.each do |request| - request['Set-Cookie'].should.equal cookie - request.body.should.include '"foo"=>"bar"' - end - - session = pool.pool.get(session_id) - session.size.should.be r.size+1 - session['counter'].should.be.nil? - session['foo'].should.equal 'bar' - end - end -rescue RuntimeError - $stderr.puts "Skipping Rack::Session::Memcache tests. Start memcached and try again." -rescue LoadError - $stderr.puts "Skipping Rack::Session::Memcache tests (Memcache is required). `gem install memcache-client` and try again." -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_pool.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_pool.rb deleted file mode 100644 index 984f55a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_session_pool.rb +++ /dev/null @@ -1,209 +0,0 @@ -require 'thread' -require 'rack/lint' -require 'rack/mock' -require 'rack/session/pool' - -describe Rack::Session::Pool do - session_key = Rack::Session::Pool::DEFAULT_OPTIONS[:key] - session_match = /#{session_key}=[0-9a-fA-F]+;/ - - incrementor = lambda do |env| - env["rack.session"]["counter"] ||= 0 - env["rack.session"]["counter"] += 1 - Rack::Response.new(env["rack.session"].inspect).to_a - end - - session_id = Rack::Lint.new(lambda do |env| - Rack::Response.new(env["rack.session"].inspect).to_a - end) - - nothing = Rack::Lint.new(lambda do |env| - Rack::Response.new("Nothing").to_a - end) - - drop_session = Rack::Lint.new(lambda do |env| - env['rack.session.options'][:drop] = true - incrementor.call(env) - end) - - renew_session = Rack::Lint.new(lambda do |env| - env['rack.session.options'][:renew] = true - incrementor.call(env) - end) - - defer_session = Rack::Lint.new(lambda do |env| - env['rack.session.options'][:defer] = true - incrementor.call(env) - end) - - incrementor = Rack::Lint.new(incrementor) - - it "creates a new cookie" do - pool = Rack::Session::Pool.new(incrementor) - res = Rack::MockRequest.new(pool).get("/") - res["Set-Cookie"].should.match session_match - res.body.should.equal '{"counter"=>1}' - end - - it "determines session from a cookie" do - pool = Rack::Session::Pool.new(incrementor) - req = Rack::MockRequest.new(pool) - cookie = req.get("/")["Set-Cookie"] - req.get("/", "HTTP_COOKIE" => cookie). - body.should.equal '{"counter"=>2}' - req.get("/", "HTTP_COOKIE" => cookie). - body.should.equal '{"counter"=>3}' - end - - it "survives nonexistant cookies" do - pool = Rack::Session::Pool.new(incrementor) - res = Rack::MockRequest.new(pool). - get("/", "HTTP_COOKIE" => "#{session_key}=blarghfasel") - res.body.should.equal '{"counter"=>1}' - end - - it "does not send the same session id if it did not change" do - pool = Rack::Session::Pool.new(incrementor) - req = Rack::MockRequest.new(pool) - - res0 = req.get("/") - cookie = res0["Set-Cookie"][session_match] - res0.body.should.equal '{"counter"=>1}' - pool.pool.size.should.equal 1 - - res1 = req.get("/", "HTTP_COOKIE" => cookie) - res1["Set-Cookie"].should.be.nil - res1.body.should.equal '{"counter"=>2}' - pool.pool.size.should.equal 1 - - res2 = req.get("/", "HTTP_COOKIE" => cookie) - res2["Set-Cookie"].should.be.nil - res2.body.should.equal '{"counter"=>3}' - pool.pool.size.should.equal 1 - end - - it "deletes cookies with :drop option" do - pool = Rack::Session::Pool.new(incrementor) - req = Rack::MockRequest.new(pool) - drop = Rack::Utils::Context.new(pool, drop_session) - dreq = Rack::MockRequest.new(drop) - - res1 = req.get("/") - session = (cookie = res1["Set-Cookie"])[session_match] - res1.body.should.equal '{"counter"=>1}' - pool.pool.size.should.equal 1 - - res2 = dreq.get("/", "HTTP_COOKIE" => cookie) - res2["Set-Cookie"].should.be.nil - res2.body.should.equal '{"counter"=>2}' - pool.pool.size.should.equal 0 - - res3 = req.get("/", "HTTP_COOKIE" => cookie) - res3["Set-Cookie"][session_match].should.not.equal session - res3.body.should.equal '{"counter"=>1}' - pool.pool.size.should.equal 1 - end - - it "provides new session id with :renew option" do - pool = Rack::Session::Pool.new(incrementor) - req = Rack::MockRequest.new(pool) - renew = Rack::Utils::Context.new(pool, renew_session) - rreq = Rack::MockRequest.new(renew) - - res1 = req.get("/") - session = (cookie = res1["Set-Cookie"])[session_match] - res1.body.should.equal '{"counter"=>1}' - pool.pool.size.should.equal 1 - - res2 = rreq.get("/", "HTTP_COOKIE" => cookie) - new_cookie = res2["Set-Cookie"] - new_session = new_cookie[session_match] - new_session.should.not.equal session - res2.body.should.equal '{"counter"=>2}' - pool.pool.size.should.equal 1 - - res3 = req.get("/", "HTTP_COOKIE" => new_cookie) - res3.body.should.equal '{"counter"=>3}' - pool.pool.size.should.equal 1 - - res4 = req.get("/", "HTTP_COOKIE" => cookie) - res4.body.should.equal '{"counter"=>1}' - pool.pool.size.should.equal 2 - end - - it "omits cookie with :defer option" do - pool = Rack::Session::Pool.new(incrementor) - defer = Rack::Utils::Context.new(pool, defer_session) - dreq = Rack::MockRequest.new(defer) - - res1 = dreq.get("/") - res1["Set-Cookie"].should.equal nil - res1.body.should.equal '{"counter"=>1}' - pool.pool.size.should.equal 1 - end - - # anyone know how to do this better? - it "should merge sessions when multithreaded" do - unless $DEBUG - 1.should.equal 1 - next - end - - warn 'Running multithread tests for Session::Pool' - pool = Rack::Session::Pool.new(incrementor) - req = Rack::MockRequest.new(pool) - - res = req.get('/') - res.body.should.equal '{"counter"=>1}' - cookie = res["Set-Cookie"] - sess_id = cookie[/#{pool.key}=([^,;]+)/,1] - - delta_incrementor = lambda do |env| - # emulate disconjoinment of threading - env['rack.session'] = env['rack.session'].dup - Thread.stop - env['rack.session'][(Time.now.usec*rand).to_i] = true - incrementor.call(env) - end - tses = Rack::Utils::Context.new pool, delta_incrementor - treq = Rack::MockRequest.new(tses) - tnum = rand(7).to_i+5 - r = Array.new(tnum) do - Thread.new(treq) do |run| - run.get('/', "HTTP_COOKIE" => cookie, 'rack.multithread' => true) - end - end.reverse.map{|t| t.run.join.value } - r.each do |resp| - resp['Set-Cookie'].should.equal cookie - resp.body.should.include '"counter"=>2' - end - - session = pool.pool[sess_id] - session.size.should.equal tnum+1 # counter - session['counter'].should.equal 2 # meeeh - end - - it "does not return a cookie if cookie was not read/written" do - app = Rack::Session::Pool.new(nothing) - res = Rack::MockRequest.new(app).get("/") - res["Set-Cookie"].should.be.nil - end - - it "does not return a cookie if cookie was not written (only read)" do - app = Rack::Session::Pool.new(session_id) - res = Rack::MockRequest.new(app).get("/") - res["Set-Cookie"].should.be.nil - end - - it "returns even if not read/written if :expire_after is set" do - app = Rack::Session::Pool.new(nothing, :expire_after => 3600) - res = Rack::MockRequest.new(app).get("/", 'rack.session' => {'not' => 'empty'}) - res["Set-Cookie"].should.not.be.nil - end - - it "returns no cookie if no data was written and no session was created previously, even if :expire_after is set" do - app = Rack::Session::Pool.new(nothing, :expire_after => 3600) - res = Rack::MockRequest.new(app).get("/") - res["Set-Cookie"].should.be.nil - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_showexceptions.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_showexceptions.rb deleted file mode 100644 index bdd5ce5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_showexceptions.rb +++ /dev/null @@ -1,92 +0,0 @@ -require 'rack/showexceptions' -require 'rack/lint' -require 'rack/mock' - -describe Rack::ShowExceptions do - def show_exceptions(app) - Rack::Lint.new Rack::ShowExceptions.new(app) - end - - it "catches exceptions" do - res = nil - - req = Rack::MockRequest.new( - show_exceptions( - lambda{|env| raise RuntimeError } - )) - - lambda{ - res = req.get("/") - }.should.not.raise - - res.should.be.a.server_error - res.status.should.equal 500 - - res.should =~ /RuntimeError/ - res.should =~ /ShowExceptions/ - end - - it "responds with plain text on AJAX requests accepting anything but HTML" do - res = nil - - req = Rack::MockRequest.new( - show_exceptions( - lambda{|env| raise RuntimeError, "It was never supposed to work" } - )) - - lambda{ - res = req.get("/", "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest") - }.should.not.raise - - res.should.be.a.server_error - res.status.should.equal 500 - - res.content_type.should.equal "text/plain" - - res.body.should.include "RuntimeError: It was never supposed to work\n" - res.body.should.include __FILE__ - end - - it "responds with HTML on AJAX requests accepting HTML" do - res = nil - - req = Rack::MockRequest.new( - show_exceptions( - lambda{|env| raise RuntimeError, "It was never supposed to work" } - )) - - lambda{ - res = req.get("/", "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest", "HTTP_ACCEPT" => "text/html") - }.should.not.raise - - res.should.be.a.server_error - res.status.should.equal 500 - - res.content_type.should.equal "text/html" - - res.body.should.include "RuntimeError" - res.body.should.include "It was never supposed to work" - res.body.should.include Rack::Utils.escape_html(__FILE__) - end - - it "handles exceptions without a backtrace" do - res = nil - - req = Rack::MockRequest.new( - show_exceptions( - lambda{|env| raise RuntimeError, "", [] } - ) - ) - - lambda{ - res = req.get("/") - }.should.not.raise - - res.should.be.a.server_error - res.status.should.equal 500 - - res.should =~ /RuntimeError/ - res.should =~ /ShowExceptions/ - res.should =~ /unknown location/ - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_showstatus.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_showstatus.rb deleted file mode 100644 index 6f8e6fe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_showstatus.rb +++ /dev/null @@ -1,84 +0,0 @@ -require 'rack/showstatus' -require 'rack/lint' -require 'rack/mock' - -describe Rack::ShowStatus do - def show_status(app) - Rack::Lint.new Rack::ShowStatus.new(app) - end - - should "provide a default status message" do - req = Rack::MockRequest.new( - show_status(lambda{|env| - [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []] - })) - - res = req.get("/", :lint => true) - res.should.be.not_found - res.should.be.not.empty - - res["Content-Type"].should.equal("text/html") - res.should =~ /404/ - res.should =~ /Not Found/ - end - - should "let the app provide additional information" do - req = Rack::MockRequest.new( - show_status( - lambda{|env| - env["rack.showstatus.detail"] = "gone too meta." - [404, {"Content-Type" => "text/plain", "Content-Length" => "0"}, []] - })) - - res = req.get("/", :lint => true) - res.should.be.not_found - res.should.be.not.empty - - res["Content-Type"].should.equal("text/html") - res.should =~ /404/ - res.should =~ /Not Found/ - res.should =~ /too meta/ - end - - should "not replace existing messages" do - req = Rack::MockRequest.new( - show_status( - lambda{|env| - [404, {"Content-Type" => "text/plain", "Content-Length" => "4"}, ["foo!"]] - })) - - res = req.get("/", :lint => true) - res.should.be.not_found - - res.body.should == "foo!" - end - - should "pass on original headers" do - headers = {"WWW-Authenticate" => "Basic blah"} - - req = Rack::MockRequest.new( - show_status(lambda{|env| [401, headers, []] })) - res = req.get("/", :lint => true) - - res["WWW-Authenticate"].should.equal("Basic blah") - end - - should "replace existing messages if there is detail" do - req = Rack::MockRequest.new( - show_status( - lambda{|env| - env["rack.showstatus.detail"] = "gone too meta." - [404, {"Content-Type" => "text/plain", "Content-Length" => "4"}, ["foo!"]] - })) - - res = req.get("/", :lint => true) - res.should.be.not_found - res.should.be.not.empty - - res["Content-Type"].should.equal("text/html") - res["Content-Length"].should.not.equal("4") - res.should =~ /404/ - res.should =~ /too meta/ - res.body.should.not =~ /foo/ - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_static.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_static.rb deleted file mode 100644 index fed1df2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_static.rb +++ /dev/null @@ -1,145 +0,0 @@ -require 'rack/static' -require 'rack/lint' -require 'rack/mock' - -class DummyApp - def call(env) - [200, {"Content-Type" => "text/plain"}, ["Hello World"]] - end -end - -describe Rack::Static do - def static(app, *args) - Rack::Lint.new Rack::Static.new(app, *args) - end - - root = File.expand_path(File.dirname(__FILE__)) - - OPTIONS = {:urls => ["/cgi"], :root => root} - STATIC_OPTIONS = {:urls => [""], :root => "#{root}/static", :index => 'index.html'} - HASH_OPTIONS = {:urls => {"/cgi/sekret" => 'cgi/test'}, :root => root} - - @request = Rack::MockRequest.new(static(DummyApp.new, OPTIONS)) - @static_request = Rack::MockRequest.new(static(DummyApp.new, STATIC_OPTIONS)) - @hash_request = Rack::MockRequest.new(static(DummyApp.new, HASH_OPTIONS)) - - it "serves files" do - res = @request.get("/cgi/test") - res.should.be.ok - res.body.should =~ /ruby/ - end - - it "404s if url root is known but it can't find the file" do - res = @request.get("/cgi/foo") - res.should.be.not_found - end - - it "calls down the chain if url root is not known" do - res = @request.get("/something/else") - res.should.be.ok - res.body.should == "Hello World" - end - - it "calls index file when requesting root in the given folder" do - res = @static_request.get("/") - res.should.be.ok - res.body.should =~ /index!/ - - res = @static_request.get("/other/") - res.should.be.not_found - - res = @static_request.get("/another/") - res.should.be.ok - res.body.should =~ /another index!/ - end - - it "doesn't call index file if :index option was omitted" do - res = @request.get("/") - res.body.should == "Hello World" - end - - it "serves hidden files" do - res = @hash_request.get("/cgi/sekret") - res.should.be.ok - res.body.should =~ /ruby/ - end - - it "calls down the chain if the URI is not specified" do - res = @hash_request.get("/something/else") - res.should.be.ok - res.body.should == "Hello World" - end - - it "supports serving fixed cache-control (legacy option)" do - opts = OPTIONS.merge(:cache_control => 'public') - request = Rack::MockRequest.new(static(DummyApp.new, opts)) - res = request.get("/cgi/test") - res.should.be.ok - res.headers['Cache-Control'].should == 'public' - end - - HEADER_OPTIONS = {:urls => ["/cgi"], :root => root, :header_rules => [ - [:all, {'Cache-Control' => 'public, max-age=100'}], - [:fonts, {'Cache-Control' => 'public, max-age=200'}], - [%w(png jpg), {'Cache-Control' => 'public, max-age=300'}], - ['/cgi/assets/folder/', {'Cache-Control' => 'public, max-age=400'}], - ['cgi/assets/javascripts', {'Cache-Control' => 'public, max-age=500'}], - [/\.(css|erb)\z/, {'Cache-Control' => 'public, max-age=600'}] - ]} - @header_request = Rack::MockRequest.new(static(DummyApp.new, HEADER_OPTIONS)) - - it "supports header rule :all" do - # Headers for all files via :all shortcut - res = @header_request.get('/cgi/assets/index.html') - res.should.be.ok - res.headers['Cache-Control'].should == 'public, max-age=100' - end - - it "supports header rule :fonts" do - # Headers for web fonts via :fonts shortcut - res = @header_request.get('/cgi/assets/fonts/font.eot') - res.should.be.ok - res.headers['Cache-Control'].should == 'public, max-age=200' - end - - it "supports file extension header rules provided as an Array" do - # Headers for file extensions via array - res = @header_request.get('/cgi/assets/images/image.png') - res.should.be.ok - res.headers['Cache-Control'].should == 'public, max-age=300' - end - - it "supports folder rules provided as a String" do - # Headers for files in folder via string - res = @header_request.get('/cgi/assets/folder/test.js') - res.should.be.ok - res.headers['Cache-Control'].should == 'public, max-age=400' - end - - it "supports folder header rules provided as a String not starting with a slash" do - res = @header_request.get('/cgi/assets/javascripts/app.js') - res.should.be.ok - res.headers['Cache-Control'].should == 'public, max-age=500' - end - - it "supports flexible header rules provided as Regexp" do - # Flexible Headers via Regexp - res = @header_request.get('/cgi/assets/stylesheets/app.css') - res.should.be.ok - res.headers['Cache-Control'].should == 'public, max-age=600' - end - - it "prioritizes header rules over fixed cache-control setting (legacy option)" do - opts = OPTIONS.merge( - :cache_control => 'public, max-age=24', - :header_rules => [ - [:all, {'Cache-Control' => 'public, max-age=42'}] - ]) - - request = Rack::MockRequest.new(static(DummyApp.new, opts)) - res = request.get("/cgi/test") - res.should.be.ok - res.headers['Cache-Control'].should == 'public, max-age=42' - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_thin.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_thin.rb deleted file mode 100644 index 15a1ab5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_thin.rb +++ /dev/null @@ -1,91 +0,0 @@ -begin -require 'rack/handler/thin' -require File.expand_path('../testrequest', __FILE__) -require 'timeout' - -describe Rack::Handler::Thin do - extend TestRequest::Helpers - - @app = Rack::Lint.new(TestRequest.new) - @server = nil - Thin::Logging.silent = true - - @thread = Thread.new do - Rack::Handler::Thin.run(@app, :Host => @host='127.0.0.1', :Port => @port=9204, :tag => "tag") do |server| - @server = server - end - end - - Thread.pass until @server && @server.running? - - should "respond" do - GET("/") - response.should.not.be.nil - end - - should "be a Thin" do - GET("/") - status.should.equal 200 - response["SERVER_SOFTWARE"].should =~ /thin/ - response["HTTP_VERSION"].should.equal "HTTP/1.1" - response["SERVER_PROTOCOL"].should.equal "HTTP/1.1" - response["SERVER_PORT"].should.equal "9204" - response["SERVER_NAME"].should.equal "127.0.0.1" - end - - should "have rack headers" do - GET("/") - response["rack.version"].should.equal [1,0] - response["rack.multithread"].should.equal false - response["rack.multiprocess"].should.equal false - response["rack.run_once"].should.equal false - end - - should "have CGI headers on GET" do - GET("/") - response["REQUEST_METHOD"].should.equal "GET" - response["REQUEST_PATH"].should.equal "/" - response["PATH_INFO"].should.be.equal "/" - response["QUERY_STRING"].should.equal "" - response["test.postdata"].should.equal "" - - GET("/test/foo?quux=1") - response["REQUEST_METHOD"].should.equal "GET" - response["REQUEST_PATH"].should.equal "/test/foo" - response["PATH_INFO"].should.equal "/test/foo" - response["QUERY_STRING"].should.equal "quux=1" - end - - should "have CGI headers on POST" do - POST("/", {"rack-form-data" => "23"}, {'X-test-header' => '42'}) - status.should.equal 200 - response["REQUEST_METHOD"].should.equal "POST" - response["REQUEST_PATH"].should.equal "/" - response["QUERY_STRING"].should.equal "" - response["HTTP_X_TEST_HEADER"].should.equal "42" - response["test.postdata"].should.equal "rack-form-data=23" - end - - should "support HTTP auth" do - GET("/test", {:user => "ruth", :passwd => "secret"}) - response["HTTP_AUTHORIZATION"].should.equal "Basic cnV0aDpzZWNyZXQ=" - end - - should "set status" do - GET("/test?secret") - status.should.equal 403 - response["rack.url_scheme"].should.equal "http" - end - - should "set tag for server" do - @server.tag.should.equal 'tag' - end - - @server.stop! - @thread.kill - -end - -rescue LoadError - $stderr.puts "Skipping Rack::Handler::Thin tests (Thin is required). `gem install thin` and try again." -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_urlmap.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_urlmap.rb deleted file mode 100644 index 316c725..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_urlmap.rb +++ /dev/null @@ -1,213 +0,0 @@ -require 'rack/urlmap' -require 'rack/mock' - -describe Rack::URLMap do - it "dispatches paths correctly" do - app = lambda { |env| - [200, { - 'X-ScriptName' => env['SCRIPT_NAME'], - 'X-PathInfo' => env['PATH_INFO'], - 'Content-Type' => 'text/plain' - }, [""]] - } - map = Rack::Lint.new(Rack::URLMap.new({ - 'http://foo.org/bar' => app, - '/foo' => app, - '/foo/bar' => app - })) - - res = Rack::MockRequest.new(map).get("/") - res.should.be.not_found - - res = Rack::MockRequest.new(map).get("/qux") - res.should.be.not_found - - res = Rack::MockRequest.new(map).get("/foo") - res.should.be.ok - res["X-ScriptName"].should.equal "/foo" - res["X-PathInfo"].should.equal "" - - res = Rack::MockRequest.new(map).get("/foo/") - res.should.be.ok - res["X-ScriptName"].should.equal "/foo" - res["X-PathInfo"].should.equal "/" - - res = Rack::MockRequest.new(map).get("/foo/bar") - res.should.be.ok - res["X-ScriptName"].should.equal "/foo/bar" - res["X-PathInfo"].should.equal "" - - res = Rack::MockRequest.new(map).get("/foo/bar/") - res.should.be.ok - res["X-ScriptName"].should.equal "/foo/bar" - res["X-PathInfo"].should.equal "/" - - res = Rack::MockRequest.new(map).get("/foo///bar//quux") - res.status.should.equal 200 - res.should.be.ok - res["X-ScriptName"].should.equal "/foo/bar" - res["X-PathInfo"].should.equal "//quux" - - res = Rack::MockRequest.new(map).get("/foo/quux", "SCRIPT_NAME" => "/bleh") - res.should.be.ok - res["X-ScriptName"].should.equal "/bleh/foo" - res["X-PathInfo"].should.equal "/quux" - - res = Rack::MockRequest.new(map).get("/bar", 'HTTP_HOST' => 'foo.org') - res.should.be.ok - res["X-ScriptName"].should.equal "/bar" - res["X-PathInfo"].should.be.empty - - res = Rack::MockRequest.new(map).get("/bar/", 'HTTP_HOST' => 'foo.org') - res.should.be.ok - res["X-ScriptName"].should.equal "/bar" - res["X-PathInfo"].should.equal '/' - end - - - it "dispatches hosts correctly" do - map = Rack::Lint.new(Rack::URLMap.new("http://foo.org/" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "foo.org", - "X-Host" => env["HTTP_HOST"] || env["SERVER_NAME"], - }, [""]]}, - "http://subdomain.foo.org/" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "subdomain.foo.org", - "X-Host" => env["HTTP_HOST"] || env["SERVER_NAME"], - }, [""]]}, - "http://bar.org/" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "bar.org", - "X-Host" => env["HTTP_HOST"] || env["SERVER_NAME"], - }, [""]]}, - "/" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "default.org", - "X-Host" => env["HTTP_HOST"] || env["SERVER_NAME"], - }, [""]]} - )) - - res = Rack::MockRequest.new(map).get("/") - res.should.be.ok - res["X-Position"].should.equal "default.org" - - res = Rack::MockRequest.new(map).get("/", "HTTP_HOST" => "bar.org") - res.should.be.ok - res["X-Position"].should.equal "bar.org" - - res = Rack::MockRequest.new(map).get("/", "HTTP_HOST" => "foo.org") - res.should.be.ok - res["X-Position"].should.equal "foo.org" - - res = Rack::MockRequest.new(map).get("/", "HTTP_HOST" => "subdomain.foo.org", "SERVER_NAME" => "foo.org") - res.should.be.ok - res["X-Position"].should.equal "subdomain.foo.org" - - res = Rack::MockRequest.new(map).get("http://foo.org/") - res.should.be.ok - res["X-Position"].should.equal "foo.org" - - res = Rack::MockRequest.new(map).get("/", "HTTP_HOST" => "example.org") - res.should.be.ok - res["X-Position"].should.equal "default.org" - - res = Rack::MockRequest.new(map).get("/", - "HTTP_HOST" => "example.org:9292", - "SERVER_PORT" => "9292") - res.should.be.ok - res["X-Position"].should.equal "default.org" - end - - should "be nestable" do - map = Rack::Lint.new(Rack::URLMap.new("/foo" => - Rack::URLMap.new("/bar" => - Rack::URLMap.new("/quux" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "/foo/bar/quux", - "X-PathInfo" => env["PATH_INFO"], - "X-ScriptName" => env["SCRIPT_NAME"], - }, [""]]} - )))) - - res = Rack::MockRequest.new(map).get("/foo/bar") - res.should.be.not_found - - res = Rack::MockRequest.new(map).get("/foo/bar/quux") - res.should.be.ok - res["X-Position"].should.equal "/foo/bar/quux" - res["X-PathInfo"].should.equal "" - res["X-ScriptName"].should.equal "/foo/bar/quux" - end - - should "route root apps correctly" do - map = Rack::Lint.new(Rack::URLMap.new("/" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "root", - "X-PathInfo" => env["PATH_INFO"], - "X-ScriptName" => env["SCRIPT_NAME"] - }, [""]]}, - "/foo" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "foo", - "X-PathInfo" => env["PATH_INFO"], - "X-ScriptName" => env["SCRIPT_NAME"] - }, [""]]} - )) - - res = Rack::MockRequest.new(map).get("/foo/bar") - res.should.be.ok - res["X-Position"].should.equal "foo" - res["X-PathInfo"].should.equal "/bar" - res["X-ScriptName"].should.equal "/foo" - - res = Rack::MockRequest.new(map).get("/foo") - res.should.be.ok - res["X-Position"].should.equal "foo" - res["X-PathInfo"].should.equal "" - res["X-ScriptName"].should.equal "/foo" - - res = Rack::MockRequest.new(map).get("/bar") - res.should.be.ok - res["X-Position"].should.equal "root" - res["X-PathInfo"].should.equal "/bar" - res["X-ScriptName"].should.equal "" - - res = Rack::MockRequest.new(map).get("") - res.should.be.ok - res["X-Position"].should.equal "root" - res["X-PathInfo"].should.equal "/" - res["X-ScriptName"].should.equal "" - end - - should "not squeeze slashes" do - map = Rack::Lint.new(Rack::URLMap.new("/" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "root", - "X-PathInfo" => env["PATH_INFO"], - "X-ScriptName" => env["SCRIPT_NAME"] - }, [""]]}, - "/foo" => lambda { |env| - [200, - { "Content-Type" => "text/plain", - "X-Position" => "foo", - "X-PathInfo" => env["PATH_INFO"], - "X-ScriptName" => env["SCRIPT_NAME"] - }, [""]]} - )) - - res = Rack::MockRequest.new(map).get("/http://example.org/bar") - res.should.be.ok - res["X-Position"].should.equal "root" - res["X-PathInfo"].should.equal "/http://example.org/bar" - res["X-ScriptName"].should.equal "" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_utils.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_utils.rb deleted file mode 100644 index 622b8ff..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_utils.rb +++ /dev/null @@ -1,573 +0,0 @@ -# -*- encoding: utf-8 -*- -require 'rack/utils' -require 'rack/mock' -require 'timeout' - -describe Rack::Utils do - - # A helper method which checks - # if certain query parameters - # are equal. - def equal_query_to(query) - parts = query.split('&') - lambda{|other| (parts & other.split('&')) == parts } - end - - def kcodeu - one8 = RUBY_VERSION.to_f < 1.9 - default_kcode, $KCODE = $KCODE, 'U' if one8 - yield - ensure - $KCODE = default_kcode if one8 - end - - should "round trip binary data" do - r = [218, 0].pack 'CC' - if defined?(::Encoding) - z = Rack::Utils.unescape(Rack::Utils.escape(r), Encoding::BINARY) - else - z = Rack::Utils.unescape(Rack::Utils.escape(r)) - end - r.should.equal z - end - - should "escape correctly" do - Rack::Utils.escape("fobar").should.equal "fo%3Co%3Ebar" - Rack::Utils.escape("a space").should.equal "a+space" - Rack::Utils.escape("q1!2\"'w$5&7/z8)?\\"). - should.equal "q1%212%22%27w%245%267%2Fz8%29%3F%5C" - end - - should "escape correctly for multibyte characters" do - matz_name = "\xE3\x81\xBE\xE3\x81\xA4\xE3\x82\x82\xE3\x81\xA8".unpack("a*")[0] # Matsumoto - matz_name.force_encoding("UTF-8") if matz_name.respond_to? :force_encoding - Rack::Utils.escape(matz_name).should.equal '%E3%81%BE%E3%81%A4%E3%82%82%E3%81%A8' - matz_name_sep = "\xE3\x81\xBE\xE3\x81\xA4 \xE3\x82\x82\xE3\x81\xA8".unpack("a*")[0] # Matsu moto - matz_name_sep.force_encoding("UTF-8") if matz_name_sep.respond_to? :force_encoding - Rack::Utils.escape(matz_name_sep).should.equal '%E3%81%BE%E3%81%A4+%E3%82%82%E3%81%A8' - end - - if RUBY_VERSION[/^\d+\.\d+/] == '1.8' - should "escape correctly for multibyte characters if $KCODE is set to 'U'" do - kcodeu do - matz_name = "\xE3\x81\xBE\xE3\x81\xA4\xE3\x82\x82\xE3\x81\xA8".unpack("a*")[0] # Matsumoto - matz_name.force_encoding("UTF-8") if matz_name.respond_to? :force_encoding - Rack::Utils.escape(matz_name).should.equal '%E3%81%BE%E3%81%A4%E3%82%82%E3%81%A8' - matz_name_sep = "\xE3\x81\xBE\xE3\x81\xA4 \xE3\x82\x82\xE3\x81\xA8".unpack("a*")[0] # Matsu moto - matz_name_sep.force_encoding("UTF-8") if matz_name_sep.respond_to? :force_encoding - Rack::Utils.escape(matz_name_sep).should.equal '%E3%81%BE%E3%81%A4+%E3%82%82%E3%81%A8' - end - end - - should "unescape multibyte characters correctly if $KCODE is set to 'U'" do - kcodeu do - Rack::Utils.unescape('%E3%81%BE%E3%81%A4+%E3%82%82%E3%81%A8').should.equal( - "\xE3\x81\xBE\xE3\x81\xA4 \xE3\x82\x82\xE3\x81\xA8".unpack("a*")[0]) - end - end - end - - should "escape objects that responds to to_s" do - kcodeu do - Rack::Utils.escape(:id).should.equal "id" - end - end - - if "".respond_to?(:encode) - should "escape non-UTF8 strings" do - Rack::Utils.escape("ø".encode("ISO-8859-1")).should.equal "%F8" - end - end - - should "not hang on escaping long strings that end in % (http://redmine.ruby-lang.org/issues/5149)" do - lambda { - timeout(1) do - lambda { - URI.decode_www_form_component "A string that causes catastrophic backtracking as it gets longer %" - }.should.raise(ArgumentError) - end - }.should.not.raise(Timeout::Error) - end - - should "escape path spaces with %20" do - Rack::Utils.escape_path("foo bar").should.equal "foo%20bar" - end - - should "unescape correctly" do - Rack::Utils.unescape("fo%3Co%3Ebar").should.equal "fobar" - Rack::Utils.unescape("a+space").should.equal "a space" - Rack::Utils.unescape("a%20space").should.equal "a space" - Rack::Utils.unescape("q1%212%22%27w%245%267%2Fz8%29%3F%5C"). - should.equal "q1!2\"'w$5&7/z8)?\\" - end - - should "parse query strings correctly" do - Rack::Utils.parse_query("foo=bar"). - should.equal "foo" => "bar" - Rack::Utils.parse_query("foo=\"bar\""). - should.equal "foo" => "\"bar\"" - Rack::Utils.parse_query("foo=bar&foo=quux"). - should.equal "foo" => ["bar", "quux"] - Rack::Utils.parse_query("foo=1&bar=2"). - should.equal "foo" => "1", "bar" => "2" - Rack::Utils.parse_query("my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F"). - should.equal "my weird field" => "q1!2\"'w$5&7/z8)?" - Rack::Utils.parse_query("foo%3Dbaz=bar").should.equal "foo=baz" => "bar" - Rack::Utils.parse_query("=").should.equal "" => "" - Rack::Utils.parse_query("=value").should.equal "" => "value" - Rack::Utils.parse_query("key=").should.equal "key" => "" - Rack::Utils.parse_query("&key&").should.equal "key" => nil - Rack::Utils.parse_query(";key;", ";,").should.equal "key" => nil - Rack::Utils.parse_query(",key,", ";,").should.equal "key" => nil - Rack::Utils.parse_query(";foo=bar,;", ";,").should.equal "foo" => "bar" - Rack::Utils.parse_query(",foo=bar;,", ";,").should.equal "foo" => "bar" - end - - should "parse nested query strings correctly" do - Rack::Utils.parse_nested_query("foo"). - should.equal "foo" => nil - Rack::Utils.parse_nested_query("foo="). - should.equal "foo" => "" - Rack::Utils.parse_nested_query("foo=bar"). - should.equal "foo" => "bar" - Rack::Utils.parse_nested_query("foo=\"bar\""). - should.equal "foo" => "\"bar\"" - - Rack::Utils.parse_nested_query("foo=bar&foo=quux"). - should.equal "foo" => "quux" - Rack::Utils.parse_nested_query("foo&foo="). - should.equal "foo" => "" - Rack::Utils.parse_nested_query("foo=1&bar=2"). - should.equal "foo" => "1", "bar" => "2" - Rack::Utils.parse_nested_query("&foo=1&&bar=2"). - should.equal "foo" => "1", "bar" => "2" - Rack::Utils.parse_nested_query("foo&bar="). - should.equal "foo" => nil, "bar" => "" - Rack::Utils.parse_nested_query("foo=bar&baz="). - should.equal "foo" => "bar", "baz" => "" - Rack::Utils.parse_nested_query("my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F"). - should.equal "my weird field" => "q1!2\"'w$5&7/z8)?" - - Rack::Utils.parse_nested_query("a=b&pid%3D1234=1023"). - should.equal "pid=1234" => "1023", "a" => "b" - - Rack::Utils.parse_nested_query("foo[]"). - should.equal "foo" => [nil] - Rack::Utils.parse_nested_query("foo[]="). - should.equal "foo" => [""] - Rack::Utils.parse_nested_query("foo[]=bar"). - should.equal "foo" => ["bar"] - - Rack::Utils.parse_nested_query("foo[]=1&foo[]=2"). - should.equal "foo" => ["1", "2"] - Rack::Utils.parse_nested_query("foo=bar&baz[]=1&baz[]=2&baz[]=3"). - should.equal "foo" => "bar", "baz" => ["1", "2", "3"] - Rack::Utils.parse_nested_query("foo[]=bar&baz[]=1&baz[]=2&baz[]=3"). - should.equal "foo" => ["bar"], "baz" => ["1", "2", "3"] - - Rack::Utils.parse_nested_query("x[y][z]=1"). - should.equal "x" => {"y" => {"z" => "1"}} - Rack::Utils.parse_nested_query("x[y][z][]=1"). - should.equal "x" => {"y" => {"z" => ["1"]}} - Rack::Utils.parse_nested_query("x[y][z]=1&x[y][z]=2"). - should.equal "x" => {"y" => {"z" => "2"}} - Rack::Utils.parse_nested_query("x[y][z][]=1&x[y][z][]=2"). - should.equal "x" => {"y" => {"z" => ["1", "2"]}} - - Rack::Utils.parse_nested_query("x[y][][z]=1"). - should.equal "x" => {"y" => [{"z" => "1"}]} - Rack::Utils.parse_nested_query("x[y][][z][]=1"). - should.equal "x" => {"y" => [{"z" => ["1"]}]} - Rack::Utils.parse_nested_query("x[y][][z]=1&x[y][][w]=2"). - should.equal "x" => {"y" => [{"z" => "1", "w" => "2"}]} - - Rack::Utils.parse_nested_query("x[y][][v][w]=1"). - should.equal "x" => {"y" => [{"v" => {"w" => "1"}}]} - Rack::Utils.parse_nested_query("x[y][][z]=1&x[y][][v][w]=2"). - should.equal "x" => {"y" => [{"z" => "1", "v" => {"w" => "2"}}]} - - Rack::Utils.parse_nested_query("x[y][][z]=1&x[y][][z]=2"). - should.equal "x" => {"y" => [{"z" => "1"}, {"z" => "2"}]} - Rack::Utils.parse_nested_query("x[y][][z]=1&x[y][][w]=a&x[y][][z]=2&x[y][][w]=3"). - should.equal "x" => {"y" => [{"z" => "1", "w" => "a"}, {"z" => "2", "w" => "3"}]} - - lambda { Rack::Utils.parse_nested_query("x[y]=1&x[y]z=2") }. - should.raise(TypeError). - message.should.equal "expected Hash (got String) for param `y'" - - lambda { Rack::Utils.parse_nested_query("x[y]=1&x[]=1") }. - should.raise(TypeError). - message.should.match(/expected Array \(got [^)]*\) for param `x'/) - - lambda { Rack::Utils.parse_nested_query("x[y]=1&x[y][][w]=2") }. - should.raise(TypeError). - message.should.equal "expected Array (got String) for param `y'" - end - - should "build query strings correctly" do - Rack::Utils.build_query("foo" => "bar").should.be equal_query_to("foo=bar") - Rack::Utils.build_query("foo" => ["bar", "quux"]). - should.be equal_query_to("foo=bar&foo=quux") - Rack::Utils.build_query("foo" => "1", "bar" => "2"). - should.be equal_query_to("foo=1&bar=2") - Rack::Utils.build_query("my weird field" => "q1!2\"'w$5&7/z8)?"). - should.be equal_query_to("my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F") - end - - should "build nested query strings correctly" do - Rack::Utils.build_nested_query("foo" => nil).should.equal "foo" - Rack::Utils.build_nested_query("foo" => "").should.equal "foo=" - Rack::Utils.build_nested_query("foo" => "bar").should.equal "foo=bar" - - Rack::Utils.build_nested_query("foo" => "1", "bar" => "2"). - should.be equal_query_to("foo=1&bar=2") - Rack::Utils.build_nested_query("my weird field" => "q1!2\"'w$5&7/z8)?"). - should.be equal_query_to("my+weird+field=q1%212%22%27w%245%267%2Fz8%29%3F") - - Rack::Utils.build_nested_query("foo" => [nil]). - should.equal "foo[]" - Rack::Utils.build_nested_query("foo" => [""]). - should.equal "foo[]=" - Rack::Utils.build_nested_query("foo" => ["bar"]). - should.equal "foo[]=bar" - - # The ordering of the output query string is unpredictable with 1.8's - # unordered hash. Test that build_nested_query performs the inverse - # function of parse_nested_query. - [{"foo" => nil, "bar" => ""}, - {"foo" => "bar", "baz" => ""}, - {"foo" => ["1", "2"]}, - {"foo" => "bar", "baz" => ["1", "2", "3"]}, - {"foo" => ["bar"], "baz" => ["1", "2", "3"]}, - {"foo" => ["1", "2"]}, - {"foo" => "bar", "baz" => ["1", "2", "3"]}, - {"x" => {"y" => {"z" => "1"}}}, - {"x" => {"y" => {"z" => ["1"]}}}, - {"x" => {"y" => {"z" => ["1", "2"]}}}, - {"x" => {"y" => [{"z" => "1"}]}}, - {"x" => {"y" => [{"z" => ["1"]}]}}, - {"x" => {"y" => [{"z" => "1", "w" => "2"}]}}, - {"x" => {"y" => [{"v" => {"w" => "1"}}]}}, - {"x" => {"y" => [{"z" => "1", "v" => {"w" => "2"}}]}}, - {"x" => {"y" => [{"z" => "1"}, {"z" => "2"}]}}, - {"x" => {"y" => [{"z" => "1", "w" => "a"}, {"z" => "2", "w" => "3"}]}} - ].each { |params| - qs = Rack::Utils.build_nested_query(params) - Rack::Utils.parse_nested_query(qs).should.equal params - } - - lambda { Rack::Utils.build_nested_query("foo=bar") }. - should.raise(ArgumentError). - message.should.equal "value must be a Hash" - end - - should "parse query strings that have a non-existent value" do - key = "post/2011/08/27/Deux-%22rat%C3%A9s%22-de-l-Universit" - Rack::Utils.parse_query(key).should.equal Rack::Utils.unescape(key) => nil - end - - should "build query strings without = with non-existent values" do - key = "post/2011/08/27/Deux-%22rat%C3%A9s%22-de-l-Universit" - key = Rack::Utils.unescape(key) - Rack::Utils.build_query(key => nil).should.equal Rack::Utils.escape(key) - end - - should "parse q-values" do - # XXX handle accept-extension - Rack::Utils.q_values("foo;q=0.5,bar,baz;q=0.9").should.equal [ - [ 'foo', 0.5 ], - [ 'bar', 1.0 ], - [ 'baz', 0.9 ] - ] - end - - should "select best quality match" do - Rack::Utils.best_q_match("text/html", %w[text/html]).should.equal "text/html" - - # More specific matches are preferred - Rack::Utils.best_q_match("text/*;q=0.5,text/html;q=1.0", %w[text/html]).should.equal "text/html" - - # Higher quality matches are preferred - Rack::Utils.best_q_match("text/*;q=0.5,text/plain;q=1.0", %w[text/plain text/html]).should.equal "text/plain" - - # All else equal, the available mimes are preferred in order - Rack::Utils.best_q_match("text/*", %w[text/html text/plain]).should.equal "text/html" - Rack::Utils.best_q_match("text/plain,text/html", %w[text/html text/plain]).should.equal "text/html" - end - - should "escape html entities [&><'\"/]" do - Rack::Utils.escape_html("foo").should.equal "foo" - Rack::Utils.escape_html("f&o").should.equal "f&o" - Rack::Utils.escape_html("fo").should.equal "f>o" - Rack::Utils.escape_html("f'o").should.equal "f'o" - Rack::Utils.escape_html('f"o').should.equal "f"o" - Rack::Utils.escape_html("f/o").should.equal "f/o" - Rack::Utils.escape_html("").should.equal "<foo></foo>" - end - - should "escape html entities even on MRI when it's bugged" do - test_escape = lambda do - kcodeu do - Rack::Utils.escape_html("\300<").should.equal "\300<" - end - end - - if RUBY_VERSION.to_f < 1.9 - test_escape.call - else - test_escape.should.raise(ArgumentError) - end - end - - if "".respond_to?(:encode) - should "escape html entities in unicode strings" do - # the following will cause warnings if the regex is poorly encoded: - Rack::Utils.escape_html("☃").should.equal "☃" - end - end - - should "figure out which encodings are acceptable" do - helper = lambda do |a, b| - Rack::Request.new(Rack::MockRequest.env_for("", "HTTP_ACCEPT_ENCODING" => a)) - Rack::Utils.select_best_encoding(a, b) - end - - helper.call(%w(), [["x", 1]]).should.equal(nil) - helper.call(%w(identity), [["identity", 0.0]]).should.equal(nil) - helper.call(%w(identity), [["*", 0.0]]).should.equal(nil) - - helper.call(%w(identity), [["compress", 1.0], ["gzip", 1.0]]).should.equal("identity") - - helper.call(%w(compress gzip identity), [["compress", 1.0], ["gzip", 1.0]]).should.equal("compress") - helper.call(%w(compress gzip identity), [["compress", 0.5], ["gzip", 1.0]]).should.equal("gzip") - - helper.call(%w(foo bar identity), []).should.equal("identity") - helper.call(%w(foo bar identity), [["*", 1.0]]).should.equal("foo") - helper.call(%w(foo bar identity), [["*", 1.0], ["foo", 0.9]]).should.equal("bar") - - helper.call(%w(foo bar identity), [["foo", 0], ["bar", 0]]).should.equal("identity") - helper.call(%w(foo bar baz identity), [["*", 0], ["identity", 0.1]]).should.equal("identity") - end - - should "return the bytesize of String" do - Rack::Utils.bytesize("FOO\xE2\x82\xAC").should.equal 6 - end - - should "should perform constant time string comparison" do - Rack::Utils.secure_compare('a', 'a').should.equal true - Rack::Utils.secure_compare('a', 'b').should.equal false - end - - should "return status code for integer" do - Rack::Utils.status_code(200).should.equal 200 - end - - should "return status code for string" do - Rack::Utils.status_code("200").should.equal 200 - end - - should "return status code for symbol" do - Rack::Utils.status_code(:ok).should.equal 200 - end - - should "return rfc2822 format from rfc2822 helper" do - Rack::Utils.rfc2822(Time.at(0).gmtime).should == "Thu, 01 Jan 1970 00:00:00 -0000" - end - - should "return rfc2109 format from rfc2109 helper" do - Rack::Utils.rfc2109(Time.at(0).gmtime).should == "Thu, 01-Jan-1970 00:00:00 GMT" - end -end - -describe Rack::Utils, "byte_range" do - should "ignore missing or syntactically invalid byte ranges" do - Rack::Utils.byte_ranges({},500).should.equal nil - Rack::Utils.byte_ranges({"HTTP_RANGE" => "foobar"},500).should.equal nil - Rack::Utils.byte_ranges({"HTTP_RANGE" => "furlongs=123-456"},500).should.equal nil - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes="},500).should.equal nil - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=-"},500).should.equal nil - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=123,456"},500).should.equal nil - # A range of non-positive length is syntactically invalid and ignored: - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=456-123"},500).should.equal nil - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=456-455"},500).should.equal nil - end - - should "parse simple byte ranges" do - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=123-456"},500).should.equal [(123..456)] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=123-"},500).should.equal [(123..499)] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=-100"},500).should.equal [(400..499)] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=0-0"},500).should.equal [(0..0)] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=499-499"},500).should.equal [(499..499)] - end - - should "parse several byte ranges" do - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=500-600,601-999"},1000).should.equal [(500..600),(601..999)] - end - - should "truncate byte ranges" do - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=123-999"},500).should.equal [(123..499)] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=600-999"},500).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=-999"},500).should.equal [(0..499)] - end - - should "ignore unsatisfiable byte ranges" do - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=500-501"},500).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=500-"},500).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=999-"},500).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=-0"},500).should.equal [] - end - - should "handle byte ranges of empty files" do - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=123-456"},0).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=0-"},0).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=-100"},0).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=0-0"},0).should.equal [] - Rack::Utils.byte_ranges({"HTTP_RANGE" => "bytes=-0"},0).should.equal [] - end -end - -describe Rack::Utils::HeaderHash do - should "retain header case" do - h = Rack::Utils::HeaderHash.new("Content-MD5" => "d5ff4e2a0 ...") - h['ETag'] = 'Boo!' - h.to_hash.should.equal "Content-MD5" => "d5ff4e2a0 ...", "ETag" => 'Boo!' - end - - should "check existence of keys case insensitively" do - h = Rack::Utils::HeaderHash.new("Content-MD5" => "d5ff4e2a0 ...") - h.should.include 'content-md5' - h.should.not.include 'ETag' - end - - should "merge case-insensitively" do - h = Rack::Utils::HeaderHash.new("ETag" => 'HELLO', "content-length" => '123') - merged = h.merge("Etag" => 'WORLD', 'Content-Length' => '321', "Foo" => 'BAR') - merged.should.equal "Etag"=>'WORLD', "Content-Length"=>'321', "Foo"=>'BAR' - end - - should "overwrite case insensitively and assume the new key's case" do - h = Rack::Utils::HeaderHash.new("Foo-Bar" => "baz") - h["foo-bar"] = "bizzle" - h["FOO-BAR"].should.equal "bizzle" - h.length.should.equal 1 - h.to_hash.should.equal "foo-bar" => "bizzle" - end - - should "be converted to real Hash" do - h = Rack::Utils::HeaderHash.new("foo" => "bar") - h.to_hash.should.be.instance_of Hash - end - - should "convert Array values to Strings when converting to Hash" do - h = Rack::Utils::HeaderHash.new("foo" => ["bar", "baz"]) - h.to_hash.should.equal({ "foo" => "bar\nbaz" }) - end - - should "replace hashes correctly" do - h = Rack::Utils::HeaderHash.new("Foo-Bar" => "baz") - j = {"foo" => "bar"} - h.replace(j) - h["foo"].should.equal "bar" - end - - should "be able to delete the given key case-sensitively" do - h = Rack::Utils::HeaderHash.new("foo" => "bar") - h.delete("foo") - h["foo"].should.be.nil - h["FOO"].should.be.nil - end - - should "be able to delete the given key case-insensitively" do - h = Rack::Utils::HeaderHash.new("foo" => "bar") - h.delete("FOO") - h["foo"].should.be.nil - h["FOO"].should.be.nil - end - - should "return the deleted value when #delete is called on an existing key" do - h = Rack::Utils::HeaderHash.new("foo" => "bar") - h.delete("Foo").should.equal("bar") - end - - should "return nil when #delete is called on a non-existant key" do - h = Rack::Utils::HeaderHash.new("foo" => "bar") - h.delete("Hello").should.be.nil - end - - should "avoid unnecessary object creation if possible" do - a = Rack::Utils::HeaderHash.new("foo" => "bar") - b = Rack::Utils::HeaderHash.new(a) - b.object_id.should.equal(a.object_id) - b.should.equal(a) - end - - should "convert Array values to Strings when responding to #each" do - h = Rack::Utils::HeaderHash.new("foo" => ["bar", "baz"]) - h.each do |k,v| - k.should.equal("foo") - v.should.equal("bar\nbaz") - end - end - - should "not create headers out of thin air" do - h = Rack::Utils::HeaderHash.new - h['foo'] - h['foo'].should.be.nil - h.should.not.include 'foo' - end -end - -describe Rack::Utils::Context do - class ContextTest - attr_reader :app - def initialize app; @app=app; end - def call env; context env; end - def context env, app=@app; app.call(env); end - end - test_target1 = proc{|e| e.to_s+' world' } - test_target2 = proc{|e| e.to_i+2 } - test_target3 = proc{|e| nil } - test_target4 = proc{|e| [200,{'Content-Type'=>'text/plain', 'Content-Length'=>'0'},['']] } - test_app = ContextTest.new test_target4 - - should "set context correctly" do - test_app.app.should.equal test_target4 - c1 = Rack::Utils::Context.new(test_app, test_target1) - c1.for.should.equal test_app - c1.app.should.equal test_target1 - c2 = Rack::Utils::Context.new(test_app, test_target2) - c2.for.should.equal test_app - c2.app.should.equal test_target2 - end - - should "alter app on recontexting" do - c1 = Rack::Utils::Context.new(test_app, test_target1) - c2 = c1.recontext(test_target2) - c2.for.should.equal test_app - c2.app.should.equal test_target2 - c3 = c2.recontext(test_target3) - c3.for.should.equal test_app - c3.app.should.equal test_target3 - end - - should "run different apps" do - c1 = Rack::Utils::Context.new test_app, test_target1 - c2 = c1.recontext test_target2 - c3 = c2.recontext test_target3 - c4 = c3.recontext test_target4 - a4 = Rack::Lint.new c4 - a5 = Rack::Lint.new test_app - r1 = c1.call('hello') - r1.should.equal 'hello world' - r2 = c2.call(2) - r2.should.equal 4 - r3 = c3.call(:misc_symbol) - r3.should.be.nil - r4 = Rack::MockRequest.new(a4).get('/') - r4.status.should.equal 200 - r5 = Rack::MockRequest.new(a5).get('/') - r5.status.should.equal 200 - r4.body.should.equal r5.body - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_webrick.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_webrick.rb deleted file mode 100644 index 5d64772..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/spec_webrick.rb +++ /dev/null @@ -1,143 +0,0 @@ -require 'rack/mock' -require File.expand_path('../testrequest', __FILE__) - -Thread.abort_on_exception = true - -describe Rack::Handler::WEBrick do - extend TestRequest::Helpers - - @server = WEBrick::HTTPServer.new(:Host => @host='127.0.0.1', - :Port => @port=9202, - :Logger => WEBrick::Log.new(nil, WEBrick::BasicLog::WARN), - :AccessLog => []) - @server.mount "/test", Rack::Handler::WEBrick, - Rack::Lint.new(TestRequest.new) - Thread.new { @server.start } - trap(:INT) { @server.shutdown } - - should "respond" do - lambda { - GET("/test") - }.should.not.raise - end - - should "be a WEBrick" do - GET("/test") - status.should.equal 200 - response["SERVER_SOFTWARE"].should =~ /WEBrick/ - response["HTTP_VERSION"].should.equal "HTTP/1.1" - response["SERVER_PROTOCOL"].should.equal "HTTP/1.1" - response["SERVER_PORT"].should.equal "9202" - response["SERVER_NAME"].should.equal "127.0.0.1" - end - - should "have rack headers" do - GET("/test") - response["rack.version"].should.equal [1,2] - response["rack.multithread"].should.be.true - response["rack.multiprocess"].should.be.false - response["rack.run_once"].should.be.false - end - - should "have CGI headers on GET" do - GET("/test") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/test" - response["PATH_INFO"].should.be.equal "" - response["QUERY_STRING"].should.equal "" - response["test.postdata"].should.equal "" - - GET("/test/foo?quux=1") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/test/foo" - response["PATH_INFO"].should.equal "/foo" - response["QUERY_STRING"].should.equal "quux=1" - - GET("/test/foo%25encoding?quux=1") - response["REQUEST_METHOD"].should.equal "GET" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/test/foo%25encoding" - response["PATH_INFO"].should.equal "/foo%25encoding" - response["QUERY_STRING"].should.equal "quux=1" - end - - should "have CGI headers on POST" do - POST("/test", {"rack-form-data" => "23"}, {'X-test-header' => '42'}) - status.should.equal 200 - response["REQUEST_METHOD"].should.equal "POST" - response["SCRIPT_NAME"].should.equal "/test" - response["REQUEST_PATH"].should.equal "/test" - response["PATH_INFO"].should.equal "" - response["QUERY_STRING"].should.equal "" - response["HTTP_X_TEST_HEADER"].should.equal "42" - response["test.postdata"].should.equal "rack-form-data=23" - end - - should "support HTTP auth" do - GET("/test", {:user => "ruth", :passwd => "secret"}) - response["HTTP_AUTHORIZATION"].should.equal "Basic cnV0aDpzZWNyZXQ=" - end - - should "set status" do - GET("/test?secret") - status.should.equal 403 - response["rack.url_scheme"].should.equal "http" - end - - should "correctly set cookies" do - @server.mount "/cookie-test", Rack::Handler::WEBrick, - Rack::Lint.new(lambda { |req| - res = Rack::Response.new - res.set_cookie "one", "1" - res.set_cookie "two", "2" - res.finish - }) - - Net::HTTP.start(@host, @port) { |http| - res = http.get("/cookie-test") - res.code.to_i.should.equal 200 - res.get_fields("set-cookie").should.equal ["one=1", "two=2"] - } - end - - should "provide a .run" do - block_ran = false - catch(:done) { - Rack::Handler::WEBrick.run(lambda {}, - { - :Host => '127.0.0.1', - :Port => 9210, - :Logger => WEBrick::Log.new(nil, WEBrick::BasicLog::WARN), - :AccessLog => []}) { |server| - block_ran = true - server.should.be.kind_of WEBrick::HTTPServer - @s = server - throw :done - } - } - block_ran.should.be.true - @s.shutdown - end - - should "return repeated headers" do - @server.mount "/headers", Rack::Handler::WEBrick, - Rack::Lint.new(lambda { |req| - [ - 401, - { "Content-Type" => "text/plain", - "WWW-Authenticate" => "Bar realm=X\nBaz realm=Y" }, - [""] - ] - }) - - Net::HTTP.start(@host, @port) { |http| - res = http.get("/headers") - res.code.to_i.should.equal 401 - res["www-authenticate"].should.equal "Bar realm=X, Baz realm=Y" - } - end - - @server.shutdown -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/static/another/index.html b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/static/another/index.html deleted file mode 100644 index d93e6fc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/static/another/index.html +++ /dev/null @@ -1 +0,0 @@ -another index! diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/static/index.html b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/static/index.html deleted file mode 100644 index fc2d9ad..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/static/index.html +++ /dev/null @@ -1 +0,0 @@ -index! diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/testrequest.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/testrequest.rb deleted file mode 100644 index c5e339a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/testrequest.rb +++ /dev/null @@ -1,78 +0,0 @@ -require 'yaml' -require 'net/http' -require 'rack/lint' - -class TestRequest - NOSERIALIZE = [Method, Proc, Rack::Lint::InputWrapper] - - def call(env) - status = env["QUERY_STRING"] =~ /secret/ ? 403 : 200 - env["test.postdata"] = env["rack.input"].read - minienv = env.dup - # This may in the future want to replace with a dummy value instead. - minienv.delete_if { |k,v| NOSERIALIZE.any? { |c| v.kind_of?(c) } } - body = minienv.to_yaml - size = body.respond_to?(:bytesize) ? body.bytesize : body.size - [status, {"Content-Type" => "text/yaml", "Content-Length" => size.to_s}, [body]] - end - - module Helpers - attr_reader :status, :response - - ROOT = File.expand_path(File.dirname(__FILE__) + "/..") - ENV["RUBYOPT"] = "-I#{ROOT}/lib -rubygems" - - def root - ROOT - end - - def rackup - "#{ROOT}/bin/rackup" - end - - def GET(path, header={}) - Net::HTTP.start(@host, @port) { |http| - user = header.delete(:user) - passwd = header.delete(:passwd) - - get = Net::HTTP::Get.new(path, header) - get.basic_auth user, passwd if user && passwd - http.request(get) { |response| - @status = response.code.to_i - begin - @response = YAML.load(response.body) - rescue TypeError, ArgumentError - @response = nil - end - } - } - end - - def POST(path, formdata={}, header={}) - Net::HTTP.start(@host, @port) { |http| - user = header.delete(:user) - passwd = header.delete(:passwd) - - post = Net::HTTP::Post.new(path, header) - post.form_data = formdata - post.basic_auth user, passwd if user && passwd - http.request(post) { |response| - @status = response.code.to_i - @response = YAML.load(response.body) - } - } - end - end -end - -class StreamingRequest - def self.call(env) - [200, {"Content-Type" => "text/plain"}, new] - end - - def each - yield "hello there!\n" - sleep 5 - yield "that is all.\n" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/unregistered_handler/rack/handler/unregistered.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/unregistered_handler/rack/handler/unregistered.rb deleted file mode 100644 index 6dd9436..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/unregistered_handler/rack/handler/unregistered.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Rack - module Handler - # this class doesn't do anything, we're just seeing if we get it. - class Unregistered - end - end -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/unregistered_handler/rack/handler/unregistered_long_one.rb b/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/unregistered_handler/rack/handler/unregistered_long_one.rb deleted file mode 100644 index 1920685..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-1.5.2/test/unregistered_handler/rack/handler/unregistered_long_one.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Rack - module Handler - # this class doesn't do anything, we're just seeing if we get it. - class UnregisteredLongOne - end - end -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/License b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/License deleted file mode 100644 index 858737c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/License +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2011 Konstantin Haase - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/README.md b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/README.md deleted file mode 100644 index 725572c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/README.md +++ /dev/null @@ -1,90 +0,0 @@ -You should use protection! - -This gem protects against typical web attacks. -Should work for all Rack apps, including Rails. - -# Usage - -Use all protections you probably want to use: - -``` ruby -# config.ru -require 'rack/protection' -use Rack::Protection -run MyApp -``` - -Skip a single protection middleware: - -``` ruby -# config.ru -require 'rack/protection' -use Rack::Protection, :except => :path_traversal -run MyApp -``` - -Use a single protection middleware: - -``` ruby -# config.ru -require 'rack/protection' -use Rack::Protection::AuthenticityToken -run MyApp -``` - -# Prevented Attacks - -## Cross Site Request Forgery - -Prevented by: - -* `Rack::Protection::AuthenticityToken` (not included by `use Rack::Protection`) -* `Rack::Protection::FormToken` (not included by `use Rack::Protection`) -* `Rack::Protection::JsonCsrf` -* `Rack::Protection::RemoteReferrer` (not included by `use Rack::Protection`) -* `Rack::Protection::RemoteToken` -* `Rack::Protection::HttpOrigin` - -## Cross Site Scripting - -Prevented by: - -* `Rack::Protection::EscapedParams` (not included by `use Rack::Protection`) -* `Rack::Protection::XSSHeader` (Internet Explorer only) - -## Clickjacking - -Prevented by: - -* `Rack::Protection::FrameOptions` - -## Directory Traversal - -Prevented by: - -* `Rack::Protection::PathTraversal` - -## Session Hijacking - -Prevented by: - -* `Rack::Protection::SessionHijacking` - -## IP Spoofing - -Prevented by: - -* `Rack::Protection::IPSpoofing` - -# Installation - - gem install rack-protection - -# Instrumentation - -Instrumentation is enabled by passing in an instrumenter as an option. -``` -use Rack::Protection, instrumenter: ActiveSupport::Notifications -``` - -The instrumenter is passed a namespace (String) and environment (Hash). The namespace is 'rack.protection' and the attack type can be obtained from the environment key 'rack.protection.attack'. diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/Rakefile b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/Rakefile deleted file mode 100644 index b642a1a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/Rakefile +++ /dev/null @@ -1,48 +0,0 @@ -# encoding: utf-8 -$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) - -begin - require 'bundler' - Bundler::GemHelper.install_tasks -rescue LoadError => e - $stderr.puts e -end - -desc "run specs" -task(:spec) { ruby '-S rspec spec' } - -desc "generate gemspec" -task 'rack-protection.gemspec' do - require 'rack/protection/version' - content = File.binread 'rack-protection.gemspec' - - # fetch data - fields = { - :authors => `git shortlog -sn`.force_encoding('utf-8').scan(/[^\d\s].*/), - :email => `git shortlog -sne`.force_encoding('utf-8').scan(/[^<]+@[^>]+/), - :files => `git ls-files`.force_encoding('utf-8').split("\n").reject { |f| f =~ /^(\.|Gemfile)/ } - } - - # double email :( - fields[:email].delete("konstantin.haase@gmail.com") - - # insert data - fields.each do |field, values| - updated = " s.#{field} = [" - updated << values.map { |v| "\n %p" % v }.join(',') - updated << "\n ]" - content.sub!(/ s\.#{field} = \[\n( .*\n)* \]/, updated) - end - - # set version - content.sub! /(s\.version.*=\s+).*/, "\\1\"#{Rack::Protection::VERSION}\"" - - # escape unicode - content.gsub!(/./) { |c| c.bytesize > 1 ? "\\u{#{c.codepoints.first.to_s(16)}}" : c } - - File.open('rack-protection.gemspec', 'w') { |f| f << content } -end - -task :gemspec => 'rack-protection.gemspec' -task :default => :spec -task :test => :spec diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack-protection.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack-protection.rb deleted file mode 100644 index 1633086..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack-protection.rb +++ /dev/null @@ -1 +0,0 @@ -require "rack/protection" diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection.rb deleted file mode 100644 index 604e749..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection.rb +++ /dev/null @@ -1,40 +0,0 @@ -require 'rack/protection/version' -require 'rack' - -module Rack - module Protection - autoload :AuthenticityToken, 'rack/protection/authenticity_token' - autoload :Base, 'rack/protection/base' - autoload :EscapedParams, 'rack/protection/escaped_params' - autoload :FormToken, 'rack/protection/form_token' - autoload :FrameOptions, 'rack/protection/frame_options' - autoload :HttpOrigin, 'rack/protection/http_origin' - autoload :IPSpoofing, 'rack/protection/ip_spoofing' - autoload :JsonCsrf, 'rack/protection/json_csrf' - autoload :PathTraversal, 'rack/protection/path_traversal' - autoload :RemoteReferrer, 'rack/protection/remote_referrer' - autoload :RemoteToken, 'rack/protection/remote_token' - autoload :SessionHijacking, 'rack/protection/session_hijacking' - autoload :XSSHeader, 'rack/protection/xss_header' - - def self.new(app, options = {}) - # does not include: RemoteReferrer, AuthenticityToken and FormToken - except = Array options[:except] - use_these = Array options[:use] - Rack::Builder.new do - use ::Rack::Protection::RemoteReferrer, options if use_these.include? :remote_referrer - use ::Rack::Protection::AuthenticityToken,options if use_these.include? :authenticity_token - use ::Rack::Protection::FormToken, options if use_these.include? :form_token - use ::Rack::Protection::FrameOptions, options unless except.include? :frame_options - use ::Rack::Protection::HttpOrigin, options unless except.include? :http_origin - use ::Rack::Protection::IPSpoofing, options unless except.include? :ip_spoofing - use ::Rack::Protection::JsonCsrf, options unless except.include? :json_csrf - use ::Rack::Protection::PathTraversal, options unless except.include? :path_traversal - use ::Rack::Protection::RemoteToken, options unless except.include? :remote_token - use ::Rack::Protection::SessionHijacking, options unless except.include? :session_hijacking - use ::Rack::Protection::XSSHeader, options unless except.include? :xss_header - run app - end.to_app - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/authenticity_token.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/authenticity_token.rb deleted file mode 100644 index e4524e4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/authenticity_token.rb +++ /dev/null @@ -1,31 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: CSRF - # Supported browsers:: all - # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery - # - # Only accepts unsafe HTTP requests if a given access token matches the token - # included in the session. - # - # Compatible with Rails and rack-csrf. - # - # Options: - # - # authenticity_param: Defines the param's name that should contain the token on a request. - # - class AuthenticityToken < Base - default_options :authenticity_param => 'authenticity_token' - - def accepts?(env) - session = session env - token = session[:csrf] ||= session['_csrf_token'] || random_string - safe?(env) || - env['HTTP_X_CSRF_TOKEN'] == token || - Request.new(env).params[options[:authenticity_param]] == token - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/base.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/base.rb deleted file mode 100755 index fe6ab37..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/base.rb +++ /dev/null @@ -1,121 +0,0 @@ -require 'rack/protection' -require 'digest' -require 'logger' -require 'uri' - -module Rack - module Protection - class Base - DEFAULT_OPTIONS = { - :reaction => :default_reaction, :logging => true, - :message => 'Forbidden', :encryptor => Digest::SHA1, - :session_key => 'rack.session', :status => 403, - :allow_empty_referrer => true, - :report_key => "protection.failed", - :html_types => %w[text/html application/xhtml] - } - - attr_reader :app, :options - - def self.default_options(options) - define_method(:default_options) { super().merge(options) } - end - - def self.default_reaction(reaction) - alias_method(:default_reaction, reaction) - end - - def default_options - DEFAULT_OPTIONS - end - - def initialize(app, options = {}) - @app, @options = app, default_options.merge(options) - end - - def safe?(env) - %w[GET HEAD OPTIONS TRACE].include? env['REQUEST_METHOD'] - end - - def accepts?(env) - raise NotImplementedError, "#{self.class} implementation pending" - end - - def call(env) - unless accepts? env - instrument env - result = react env - end - result or app.call(env) - end - - def react(env) - result = send(options[:reaction], env) - result if Array === result and result.size == 3 - end - - def warn(env, message) - return unless options[:logging] - l = options[:logger] || env['rack.logger'] || ::Logger.new(env['rack.errors']) - l.warn(message) - end - - def instrument(env) - return unless i = options[:instrumenter] - env['rack.protection.attack'] = self.class.name.split('::').last.downcase - i.instrument('rack.protection', env) - end - - def deny(env) - warn env, "attack prevented by #{self.class}" - [options[:status], {'Content-Type' => 'text/plain'}, [options[:message]]] - end - - def report(env) - warn env, "attack reported by #{self.class}" - env[options[:report_key]] = true - end - - def session?(env) - env.include? options[:session_key] - end - - def session(env) - return env[options[:session_key]] if session? env - fail "you need to set up a session middleware *before* #{self.class}" - end - - def drop_session(env) - session(env).clear if session? env - end - - def referrer(env) - ref = env['HTTP_REFERER'].to_s - return if !options[:allow_empty_referrer] and ref.empty? - URI.parse(ref).host || Request.new(env).host - rescue URI::InvalidURIError - end - - def origin(env) - env['HTTP_ORIGIN'] || env['HTTP_X_ORIGIN'] - end - - def random_string(secure = defined? SecureRandom) - secure ? SecureRandom.hex(16) : "%032x" % rand(2**128-1) - rescue NotImplementedError - random_string false - end - - def encrypt(value) - options[:encryptor].hexdigest value.to_s - end - - alias default_reaction deny - - def html?(headers) - return false unless header = headers.detect { |k,v| k.downcase == 'content-type' } - options[:html_types].include? header.last[/^\w+\/\w+/] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/escaped_params.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/escaped_params.rb deleted file mode 100644 index 3283dec..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/escaped_params.rb +++ /dev/null @@ -1,87 +0,0 @@ -require 'rack/protection' -require 'rack/utils' - -begin - require 'escape_utils' -rescue LoadError -end - -module Rack - module Protection - ## - # Prevented attack:: XSS - # Supported browsers:: all - # More infos:: http://en.wikipedia.org/wiki/Cross-site_scripting - # - # Automatically escapes Rack::Request#params so they can be embedded in HTML - # or JavaScript without any further issues. Calls +html_safe+ on the escaped - # strings if defined, to avoid double-escaping in Rails. - # - # Options: - # escape:: What escaping modes to use, should be Symbol or Array of Symbols. - # Available: :html (default), :javascript, :url - class EscapedParams < Base - extend Rack::Utils - - class << self - alias escape_url escape - public :escape_html - end - - default_options :escape => :html, - :escaper => defined?(EscapeUtils) ? EscapeUtils : self - - def initialize(*) - super - - modes = Array options[:escape] - @escaper = options[:escaper] - @html = modes.include? :html - @javascript = modes.include? :javascript - @url = modes.include? :url - - if @javascript and not @escaper.respond_to? :escape_javascript - fail("Use EscapeUtils for JavaScript escaping.") - end - end - - def call(env) - request = Request.new(env) - get_was = handle(request.GET) - post_was = handle(request.POST) rescue nil - app.call env - ensure - request.GET.replace get_was if get_was - request.POST.replace post_was if post_was - end - - def handle(hash) - was = hash.dup - hash.replace escape(hash) - was - end - - def escape(object) - case object - when Hash then escape_hash(object) - when Array then object.map { |o| escape(o) } - when String then escape_string(object) - else nil - end - end - - def escape_hash(hash) - hash = hash.dup - hash.each { |k,v| hash[k] = escape(v) } - hash - end - - def escape_string(str) - str = @escaper.escape_url(str) if @url - str = @escaper.escape_html(str) if @html - str = @escaper.escape_javascript(str) if @javascript - str - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/form_token.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/form_token.rb deleted file mode 100644 index eb12af7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/form_token.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: CSRF - # Supported browsers:: all - # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery - # - # Only accepts submitted forms if a given access token matches the token - # included in the session. Does not expect such a token from Ajax request. - # - # This middleware is not used when using the Rack::Protection collection, - # since it might be a security issue, depending on your application - # - # Compatible with Rails and rack-csrf. - class FormToken < AuthenticityToken - def accepts?(env) - env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" or super - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/frame_options.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/frame_options.rb deleted file mode 100644 index bce75c4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/frame_options.rb +++ /dev/null @@ -1,37 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: Clickjacking - # Supported browsers:: Internet Explorer 8, Firefox 3.6.9, Opera 10.50, - # Safari 4.0, Chrome 4.1.249.1042 and later - # More infos:: https://developer.mozilla.org/en/The_X-FRAME-OPTIONS_response_header - # - # Sets X-Frame-Options header to tell the browser avoid embedding the page - # in a frame. - # - # Options: - # - # frame_options:: Defines who should be allowed to embed the page in a - # frame. Use :deny to forbid any embedding, :sameorigin - # to allow embedding from the same origin (default). - class FrameOptions < Base - default_options :frame_options => :sameorigin - - def frame_options - @frame_options ||= begin - frame_options = options[:frame_options] - frame_options = options[:frame_options].to_s.upcase unless frame_options.respond_to? :to_str - frame_options.to_str - end - end - - def call(env) - status, headers, body = @app.call(env) - headers['X-Frame-Options'] ||= frame_options if html? headers - [status, headers, body] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/http_origin.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/http_origin.rb deleted file mode 100644 index 4eb9e4d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/http_origin.rb +++ /dev/null @@ -1,32 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: CSRF - # Supported browsers:: Google Chrome 2, Safari 4 and later - # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery - # http://tools.ietf.org/html/draft-abarth-origin - # - # Does not accept unsafe HTTP requests when value of Origin HTTP request header - # does not match default or whitelisted URIs. - class HttpOrigin < Base - DEFAULT_PORTS = { 'http' => 80, 'https' => 443, 'coffee' => 80 } - default_reaction :deny - - def base_url(env) - request = Rack::Request.new(env) - port = ":#{request.port}" unless request.port == DEFAULT_PORTS[request.scheme] - "#{request.scheme}://#{request.host}#{port}" - end - - def accepts?(env) - return true if safe? env - return true unless origin = env['HTTP_ORIGIN'] - return true if base_url(env) == origin - Array(options[:origin_whitelist]).include? origin - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/ip_spoofing.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/ip_spoofing.rb deleted file mode 100644 index 3e404ad..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/ip_spoofing.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: IP spoofing - # Supported browsers:: all - # More infos:: http://blog.c22.cc/2011/04/22/surveymonkey-ip-spoofing/ - # - # Detect (some) IP spoofing attacks. - class IPSpoofing < Base - default_reaction :deny - - def accepts?(env) - return true unless env.include? 'HTTP_X_FORWARDED_FOR' - ips = env['HTTP_X_FORWARDED_FOR'].split(/\s*,\s*/) - return false if env.include? 'HTTP_CLIENT_IP' and not ips.include? env['HTTP_CLIENT_IP'] - return false if env.include? 'HTTP_X_REAL_IP' and not ips.include? env['HTTP_X_REAL_IP'] - true - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/json_csrf.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/json_csrf.rb deleted file mode 100644 index f163f68..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/json_csrf.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: CSRF - # Supported browsers:: all - # More infos:: http://flask.pocoo.org/docs/security/#json-security - # - # JSON GET APIs are vulnerable to being embedded as JavaScript while the - # Array prototype has been patched to track data. Checks the referrer - # even on GET requests if the content type is JSON. - class JsonCsrf < Base - alias react deny - - def call(env) - request = Request.new(env) - status, headers, body = app.call(env) - - if has_vector? request, headers - warn env, "attack prevented by #{self.class}" - react(env) or [status, headers, body] - else - [status, headers, body] - end - end - - def has_vector?(request, headers) - return false if request.xhr? - return false unless headers['Content-Type'].to_s.split(';', 2).first =~ /^\s*application\/json\s*$/ - origin(request.env).nil? and referrer(request.env) != request.host - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/path_traversal.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/path_traversal.rb deleted file mode 100644 index 0f58a64..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/path_traversal.rb +++ /dev/null @@ -1,47 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: Directory traversal - # Supported browsers:: all - # More infos:: http://en.wikipedia.org/wiki/Directory_traversal - # - # Unescapes '/' and '.', expands +path_info+. - # Thus GET /foo/%2e%2e%2fbar becomes GET /bar. - class PathTraversal < Base - def call(env) - path_was = env["PATH_INFO"] - env["PATH_INFO"] = cleanup path_was if path_was && !path_was.empty? - app.call env - ensure - env["PATH_INFO"] = path_was - end - - def cleanup(path) - if path.respond_to?(:encoding) - # Ruby 1.9+ M17N - encoding = path.encoding - dot = '.'.encode(encoding) - slash = '/'.encode(encoding) - else - # Ruby 1.8 - dot = '.' - slash = '/' - end - - parts = [] - unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash) - - unescaped.split(slash).each do |part| - next if part.empty? or part == dot - part == '..' ? parts.pop : parts << part - end - - cleaned = slash + parts.join(slash) - cleaned << slash if parts.any? and unescaped =~ %r{/\.{0,2}$} - cleaned - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/remote_referrer.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/remote_referrer.rb deleted file mode 100644 index 5375ebc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/remote_referrer.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: CSRF - # Supported browsers:: all - # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery - # - # Does not accept unsafe HTTP requests if the Referer [sic] header is set to - # a different host. - class RemoteReferrer < Base - default_reaction :deny - - def accepts?(env) - safe?(env) or referrer(env) == Request.new(env).host - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/remote_token.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/remote_token.rb deleted file mode 100644 index ed25e59..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/remote_token.rb +++ /dev/null @@ -1,22 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: CSRF - # Supported browsers:: all - # More infos:: http://en.wikipedia.org/wiki/Cross-site_request_forgery - # - # Only accepts unsafe HTTP requests if a given access token matches the token - # included in the session *or* the request comes from the same origin. - # - # Compatible with Rails and rack-csrf. - class RemoteToken < AuthenticityToken - default_reaction :deny - - def accepts?(env) - super or referrer(env) == Request.new(env).host - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/session_hijacking.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/session_hijacking.rb deleted file mode 100644 index 4ab047a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/session_hijacking.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: Session Hijacking - # Supported browsers:: all - # More infos:: http://en.wikipedia.org/wiki/Session_hijacking - # - # Tracks request properties like the user agent in the session and empties - # the session if those properties change. This essentially prevents attacks - # from Firesheep. Since all headers taken into consideration can be - # spoofed, too, this will not prevent determined hijacking attempts. - class SessionHijacking < Base - default_reaction :drop_session - default_options :tracking_key => :tracking, :encrypt_tracking => true, - :track => %w[HTTP_USER_AGENT HTTP_ACCEPT_LANGUAGE] - - def accepts?(env) - session = session env - key = options[:tracking_key] - if session.include? key - session[key].all? { |k,v| v == encrypt(env[k]) } - else - session[key] = {} - options[:track].each { |k| session[key][k] = encrypt(env[k]) } - end - end - - def encrypt(value) - value = value.to_s.downcase - options[:encrypt_tracking] ? super(value) : value - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/version.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/version.rb deleted file mode 100644 index dba6c9b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/version.rb +++ /dev/null @@ -1,16 +0,0 @@ -module Rack - module Protection - def self.version - VERSION - end - - SIGNATURE = [1, 5, 3] - VERSION = SIGNATURE.join('.') - - VERSION.extend Comparable - def VERSION.<=>(other) - other = other.split('.').map { |i| i.to_i } if other.respond_to? :split - SIGNATURE <=> Array(other) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/xss_header.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/xss_header.rb deleted file mode 100644 index 6bb1486..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/lib/rack/protection/xss_header.rb +++ /dev/null @@ -1,25 +0,0 @@ -require 'rack/protection' - -module Rack - module Protection - ## - # Prevented attack:: Non-permanent XSS - # Supported browsers:: Internet Explorer 8 and later - # More infos:: http://blogs.msdn.com/b/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx - # - # Sets X-XSS-Protection header to tell the browser to block attacks. - # - # Options: - # xss_mode:: How the browser should prevent the attack (default: :block) - class XSSHeader < Base - default_options :xss_mode => :block, :nosniff => true - - def call(env) - status, headers, body = @app.call(env) - headers['X-XSS-Protection'] ||= "1; mode=#{options[:xss_mode]}" if html? headers - headers['X-Content-Type-Options'] ||= 'nosniff' if options[:nosniff] - [status, headers, body] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/rack-protection.gemspec b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/rack-protection.gemspec deleted file mode 100644 index 0a86646..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/rack-protection.gemspec +++ /dev/null @@ -1,118 +0,0 @@ -# Run `rake rack-protection.gemspec` to update the gemspec. -Gem::Specification.new do |s| - # general infos - s.name = "rack-protection" - s.version = "1.5.3" - s.description = "You should use protection!" - s.homepage = "http://github.com/rkh/rack-protection" - s.summary = s.description - s.license = 'MIT' - - # generated from git shortlog -sn - s.authors = [ - "Konstantin Haase", - "Alex Rodionov", - "Patrick Ellis", - "Jason Staten", - "ITO Nobuaki", - "Jeff Welling", - "Matteo Centenaro", - "Egor Homakov", - "Florian Gilcher", - "Fojas", - "Igor Bochkariov", - "Mael Clerambault", - "Martin Mauch", - "Renne Nissinen", - "SAKAI, Kazuaki", - "Stanislav Savulchik", - "Steve Agalloco", - "TOBY", - "Thais Camilo and Konstantin Haase", - "Vipul A M", - "Akzhan Abdulin", - "brookemckim", - "Bj\u{f8}rge N\u{e6}ss", - "Chris Heald", - "Chris Mytton", - "Corey Ward", - "Dario Cravero", - "David Kellum" - ] - - # generated from git shortlog -sne - s.email = [ - "konstantin.mailinglists@googlemail.com", - "p0deje@gmail.com", - "jstaten07@gmail.com", - "patrick@soundcloud.com", - "jeff.welling@gmail.com", - "bugant@gmail.com", - "daydream.trippers@gmail.com", - "florian.gilcher@asquera.de", - "developer@fojasaur.us", - "ujifgc@gmail.com", - "mael@clerambault.fr", - "martin.mauch@gmail.com", - "rennex@iki.fi", - "kaz.july.7@gmail.com", - "s.savulchik@gmail.com", - "steve.agalloco@gmail.com", - "toby.net.info.mail+git@gmail.com", - "dev+narwen+rkh@rkh.im", - "vipulnsward@gmail.com", - "akzhan.abdulin@gmail.com", - "brooke@digitalocean.com", - "bjoerge@bengler.no", - "cheald@gmail.com", - "self@hecticjeff.net", - "coreyward@me.com", - "dario@uxtemple.com", - "dek-oss@gravitext.com", - "homakov@gmail.com" - ] - - # generated from git ls-files - s.files = [ - "License", - "README.md", - "Rakefile", - "lib/rack-protection.rb", - "lib/rack/protection.rb", - "lib/rack/protection/authenticity_token.rb", - "lib/rack/protection/base.rb", - "lib/rack/protection/escaped_params.rb", - "lib/rack/protection/form_token.rb", - "lib/rack/protection/frame_options.rb", - "lib/rack/protection/http_origin.rb", - "lib/rack/protection/ip_spoofing.rb", - "lib/rack/protection/json_csrf.rb", - "lib/rack/protection/path_traversal.rb", - "lib/rack/protection/remote_referrer.rb", - "lib/rack/protection/remote_token.rb", - "lib/rack/protection/session_hijacking.rb", - "lib/rack/protection/version.rb", - "lib/rack/protection/xss_header.rb", - "rack-protection.gemspec", - "spec/authenticity_token_spec.rb", - "spec/base_spec.rb", - "spec/escaped_params_spec.rb", - "spec/form_token_spec.rb", - "spec/frame_options_spec.rb", - "spec/http_origin_spec.rb", - "spec/ip_spoofing_spec.rb", - "spec/json_csrf_spec.rb", - "spec/path_traversal_spec.rb", - "spec/protection_spec.rb", - "spec/remote_referrer_spec.rb", - "spec/remote_token_spec.rb", - "spec/session_hijacking_spec.rb", - "spec/spec_helper.rb", - "spec/xss_header_spec.rb" - ] - - # dependencies - s.add_dependency "rack" - s.add_development_dependency "rack-test" - s.add_development_dependency "rspec", "~> 2.0" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/authenticity_token_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/authenticity_token_spec.rb deleted file mode 100644 index ec8e34b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/authenticity_token_spec.rb +++ /dev/null @@ -1,48 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::AuthenticityToken do - it_behaves_like "any rack application" - - it "denies post requests without any token" do - post('/').should_not be_ok - end - - it "accepts post requests with correct X-CSRF-Token header" do - post('/', {}, 'rack.session' => {:csrf => "a"}, 'HTTP_X_CSRF_TOKEN' => "a") - last_response.should be_ok - end - - it "denies post requests with wrong X-CSRF-Token header" do - post('/', {}, 'rack.session' => {:csrf => "a"}, 'HTTP_X_CSRF_TOKEN' => "b") - last_response.should_not be_ok - end - - it "accepts post form requests with correct authenticity_token field" do - post('/', {"authenticity_token" => "a"}, 'rack.session' => {:csrf => "a"}) - last_response.should be_ok - end - - it "denies post form requests with wrong authenticity_token field" do - post('/', {"authenticity_token" => "a"}, 'rack.session' => {:csrf => "b"}) - last_response.should_not be_ok - end - - it "prevents ajax requests without a valid token" do - post('/', {}, "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest").should_not be_ok - end - - it "allows for a custom authenticity token param" do - mock_app do - use Rack::Protection::AuthenticityToken, :authenticity_param => 'csrf_param' - run proc { |e| [200, {'Content-Type' => 'text/plain'}, ['hi']] } - end - - post('/', {"csrf_param" => "a"}, 'rack.session' => {:csrf => "a"}) - last_response.should be_ok - end - - it "sets a new csrf token for the session in env, even after a 'safe' request" do - get('/', {}, {}) - env['rack.session'][:csrf].should_not be_nil - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/base_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/base_spec.rb deleted file mode 100644 index 415634a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/base_spec.rb +++ /dev/null @@ -1,40 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::Base do - - subject { described_class.new(lambda {}) } - - describe "#random_string" do - it "outputs a string of 32 characters" do - subject.random_string.length.should == 32 - end - end - - describe "#referrer" do - it "Reads referrer from Referer header" do - env = {"HTTP_HOST" => "foo.com", "HTTP_REFERER" => "http://bar.com/valid"} - subject.referrer(env).should == "bar.com" - end - - it "Reads referrer from Host header when Referer header is relative" do - env = {"HTTP_HOST" => "foo.com", "HTTP_REFERER" => "/valid"} - subject.referrer(env).should == "foo.com" - end - - it "Reads referrer from Host header when Referer header is missing" do - env = {"HTTP_HOST" => "foo.com"} - subject.referrer(env).should == "foo.com" - end - - it "Returns nil when Referer header is missing and allow_empty_referrer is false" do - env = {"HTTP_HOST" => "foo.com"} - subject.options[:allow_empty_referrer] = false - subject.referrer(env).should be_nil - end - - it "Returns nil when Referer header is invalid" do - env = {"HTTP_HOST" => "foo.com", "HTTP_REFERER" => "http://bar.com/bad|uri"} - subject.referrer(env).should be_nil - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/escaped_params_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/escaped_params_spec.rb deleted file mode 100644 index 17afa80..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/escaped_params_spec.rb +++ /dev/null @@ -1,43 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::EscapedParams do - it_behaves_like "any rack application" - - context 'escaping' do - it 'escapes html entities' do - mock_app do |env| - request = Rack::Request.new(env) - [200, {'Content-Type' => 'text/plain'}, [request.params['foo']]] - end - get '/', :foo => "" - body.should == '<bar>' - end - - it 'leaves normal params untouched' do - mock_app do |env| - request = Rack::Request.new(env) - [200, {'Content-Type' => 'text/plain'}, [request.params['foo']]] - end - get '/', :foo => "bar" - body.should == 'bar' - end - - it 'copes with nested arrays' do - mock_app do |env| - request = Rack::Request.new(env) - [200, {'Content-Type' => 'text/plain'}, [request.params['foo']['bar']]] - end - get '/', :foo => {:bar => ""} - body.should == '<bar>' - end - - it 'leaves cache-breaker params untouched' do - mock_app do |env| - [200, {'Content-Type' => 'text/plain'}, ['hi']] - end - - get '/?95df8d9bf5237ad08df3115ee74dcb10' - body.should == 'hi' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/form_token_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/form_token_spec.rb deleted file mode 100644 index 0c4aa37..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/form_token_spec.rb +++ /dev/null @@ -1,33 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::FormToken do - it_behaves_like "any rack application" - - it "denies post requests without any token" do - post('/').should_not be_ok - end - - it "accepts post requests with correct X-CSRF-Token header" do - post('/', {}, 'rack.session' => {:csrf => "a"}, 'HTTP_X_CSRF_TOKEN' => "a") - last_response.should be_ok - end - - it "denies post requests with wrong X-CSRF-Token header" do - post('/', {}, 'rack.session' => {:csrf => "a"}, 'HTTP_X_CSRF_TOKEN' => "b") - last_response.should_not be_ok - end - - it "accepts post form requests with correct authenticity_token field" do - post('/', {"authenticity_token" => "a"}, 'rack.session' => {:csrf => "a"}) - last_response.should be_ok - end - - it "denies post form requests with wrong authenticity_token field" do - post('/', {"authenticity_token" => "a"}, 'rack.session' => {:csrf => "b"}) - last_response.should_not be_ok - end - - it "accepts ajax requests without a valid token" do - post('/', {}, "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest").should be_ok - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/frame_options_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/frame_options_spec.rb deleted file mode 100644 index a34ab0a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/frame_options_spec.rb +++ /dev/null @@ -1,39 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::FrameOptions do - it_behaves_like "any rack application" - - it 'should set the X-Frame-Options' do - get('/', {}, 'wants' => 'text/html').headers["X-Frame-Options"].should == "SAMEORIGIN" - end - - it 'should not set the X-Frame-Options for other content types' do - get('/', {}, 'wants' => 'text/foo').headers["X-Frame-Options"].should be_nil - end - - it 'should allow changing the protection mode' do - # I have no clue what other modes are available - mock_app do - use Rack::Protection::FrameOptions, :frame_options => :deny - run DummyApp - end - - get('/', {}, 'wants' => 'text/html').headers["X-Frame-Options"].should == "DENY" - end - - - it 'should allow changing the protection mode to a string' do - # I have no clue what other modes are available - mock_app do - use Rack::Protection::FrameOptions, :frame_options => "ALLOW-FROM foo" - run DummyApp - end - - get('/', {}, 'wants' => 'text/html').headers["X-Frame-Options"].should == "ALLOW-FROM foo" - end - - it 'should not override the header if already set' do - mock_app with_headers("X-Frame-Options" => "allow") - get('/', {}, 'wants' => 'text/html').headers["X-Frame-Options"].should == "allow" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/http_origin_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/http_origin_spec.rb deleted file mode 100644 index 7fff61f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/http_origin_spec.rb +++ /dev/null @@ -1,38 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::HttpOrigin do - it_behaves_like "any rack application" - - before(:each) do - mock_app do - use Rack::Protection::HttpOrigin - run DummyApp - end - end - - %w(GET HEAD POST PUT DELETE).each do |method| - it "accepts #{method} requests with no Origin" do - send(method.downcase, '/').should be_ok - end - end - - %w(GET HEAD).each do |method| - it "accepts #{method} requests with non-whitelisted Origin" do - send(method.downcase, '/', {}, 'HTTP_ORIGIN' => 'http://malicious.com').should be_ok - end - end - - %w(POST PUT DELETE).each do |method| - it "denies #{method} requests with non-whitelisted Origin" do - send(method.downcase, '/', {}, 'HTTP_ORIGIN' => 'http://malicious.com').should_not be_ok - end - - it "accepts #{method} requests with whitelisted Origin" do - mock_app do - use Rack::Protection::HttpOrigin, :origin_whitelist => ['http://www.friend.com'] - run DummyApp - end - send(method.downcase, '/', {}, 'HTTP_ORIGIN' => 'http://www.friend.com').should be_ok - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/ip_spoofing_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/ip_spoofing_spec.rb deleted file mode 100644 index 7290837..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/ip_spoofing_spec.rb +++ /dev/null @@ -1,35 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::IPSpoofing do - it_behaves_like "any rack application" - - it 'accepts requests without X-Forward-For header' do - get('/', {}, 'HTTP_CLIENT_IP' => '1.2.3.4', 'HTTP_X_REAL_IP' => '4.3.2.1') - last_response.should be_ok - end - - it 'accepts requests with proper X-Forward-For header' do - get('/', {}, 'HTTP_CLIENT_IP' => '1.2.3.4', - 'HTTP_X_FORWARDED_FOR' => '192.168.1.20, 1.2.3.4, 127.0.0.1') - last_response.should be_ok - end - - it 'denies requests where the client spoofs X-Forward-For but not the IP' do - get('/', {}, 'HTTP_CLIENT_IP' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '1.2.3.5') - last_response.should_not be_ok - end - - it 'denies requests where the client spoofs the IP but not X-Forward-For' do - get('/', {}, 'HTTP_CLIENT_IP' => '1.2.3.5', - 'HTTP_X_FORWARDED_FOR' => '192.168.1.20, 1.2.3.4, 127.0.0.1') - last_response.should_not be_ok - end - - it 'denies requests where IP and X-Forward-For are spoofed but not X-Real-IP' do - get('/', {}, - 'HTTP_CLIENT_IP' => '1.2.3.5', - 'HTTP_X_FORWARDED_FOR' => '1.2.3.5', - 'HTTP_X_REAL_IP' => '1.2.3.4') - last_response.should_not be_ok - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/json_csrf_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/json_csrf_spec.rb deleted file mode 100644 index 264f948..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/json_csrf_spec.rb +++ /dev/null @@ -1,58 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::JsonCsrf do - it_behaves_like "any rack application" - - describe 'json response' do - before do - mock_app { |e| [200, {'Content-Type' => 'application/json'}, []]} - end - - it "denies get requests with json responses with a remote referrer" do - get('/', {}, 'HTTP_REFERER' => 'http://evil.com').should_not be_ok - end - - it "accepts requests with json responses with a remote referrer when there's an origin header set" do - get('/', {}, 'HTTP_REFERER' => 'http://good.com', 'HTTP_ORIGIN' => 'http://good.com').should be_ok - end - - it "accepts requests with json responses with a remote referrer when there's an x-origin header set" do - get('/', {}, 'HTTP_REFERER' => 'http://good.com', 'HTTP_X_ORIGIN' => 'http://good.com').should be_ok - end - - it "accepts get requests with json responses with a local referrer" do - get('/', {}, 'HTTP_REFERER' => '/').should be_ok - end - - it "accepts get requests with json responses with no referrer" do - get('/', {}).should be_ok - end - - it "accepts XHR requests" do - get('/', {}, 'HTTP_REFERER' => 'http://evil.com', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest').should be_ok - end - - end - - describe 'not json response' do - - it "accepts get requests with 304 headers" do - mock_app { |e| [304, {}, []]} - get('/', {}).status.should == 304 - end - - end - - describe 'with drop_session as default reaction' do - it 'still denies' do - mock_app do - use Rack::Protection, :reaction => :drop_session - run proc { |e| [200, {'Content-Type' => 'application/json'}, []]} - end - - session = {:foo => :bar} - get('/', {}, 'HTTP_REFERER' => 'http://evil.com', 'rack.session' => session) - last_response.should_not be_ok - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/path_traversal_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/path_traversal_spec.rb deleted file mode 100644 index 9ebd7f0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/path_traversal_spec.rb +++ /dev/null @@ -1,41 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::PathTraversal do - it_behaves_like "any rack application" - - context 'escaping' do - before do - mock_app { |e| [200, {'Content-Type' => 'text/plain'}, [e['PATH_INFO']]] } - end - - %w[/foo/bar /foo/bar/ / /.f /a.x].each do |path| - it("does not touch #{path.inspect}") { get(path).body.should == path } - end - - { # yes, this is ugly, feel free to change that - '/..' => '/', '/a/../b' => '/b', '/a/../b/' => '/b/', '/a/.' => '/a/', - '/%2e.' => '/', '/a/%2E%2e/b' => '/b', '/a%2f%2E%2e%2Fb/' => '/b/', - '//' => '/', '/%2fetc%2Fpasswd' => '/etc/passwd' - }.each do |a, b| - it("replaces #{a.inspect} with #{b.inspect}") { get(a).body.should == b } - end - - it 'should be able to deal with PATH_INFO = nil (fcgi?)' do - app = Rack::Protection::PathTraversal.new(proc { 42 }) - app.call({}).should be == 42 - end - end - - if "".respond_to?(:encoding) # Ruby 1.9+ M17N - context "PATH_INFO's encoding" do - before do - @app = Rack::Protection::PathTraversal.new(proc { |e| [200, {'Content-Type' => 'text/plain'}, [e['PATH_INFO'].encoding.to_s]] }) - end - - it 'should remain unchanged as ASCII-8BIT' do - body = @app.call({ 'PATH_INFO' => '/'.encode('ASCII-8BIT') })[2][0] - body.should == 'ASCII-8BIT' - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/protection_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/protection_spec.rb deleted file mode 100755 index 083670c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/protection_spec.rb +++ /dev/null @@ -1,105 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection do - it_behaves_like "any rack application" - - it 'passes on options' do - mock_app do - use Rack::Protection, :track => ['HTTP_FOO'] - run proc { |e| [200, {'Content-Type' => 'text/plain'}, ['hi']] } - end - - session = {:foo => :bar} - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_ENCODING' => 'a' - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_ENCODING' => 'b' - session[:foo].should be == :bar - - get '/', {}, 'rack.session' => session, 'HTTP_FOO' => 'BAR' - session.should be_empty - end - - it 'passes errors through if :reaction => :report is used' do - mock_app do - use Rack::Protection, :reaction => :report - run proc { |e| [200, {'Content-Type' => 'text/plain'}, [e["protection.failed"].to_s]] } - end - - session = {:foo => :bar} - post('/', {}, 'rack.session' => session, 'HTTP_ORIGIN' => 'http://malicious.com') - last_response.should be_ok - body.should == "true" - end - - describe "#react" do - it 'prevents attacks and warns about it' do - io = StringIO.new - mock_app do - use Rack::Protection, :logger => Logger.new(io) - run DummyApp - end - post('/', {}, 'rack.session' => {}, 'HTTP_ORIGIN' => 'http://malicious.com') - io.string.should match /prevented.*Origin/ - end - - it 'reports attacks if reaction is to report' do - io = StringIO.new - mock_app do - use Rack::Protection, :reaction => :report, :logger => Logger.new(io) - run DummyApp - end - post('/', {}, 'rack.session' => {}, 'HTTP_ORIGIN' => 'http://malicious.com') - io.string.should match /reported.*Origin/ - io.string.should_not match /prevented.*Origin/ - end - - it 'passes errors to reaction method if specified' do - io = StringIO.new - Rack::Protection::Base.send(:define_method, :special) { |*args| io << args.inspect } - mock_app do - use Rack::Protection, :reaction => :special, :logger => Logger.new(io) - run DummyApp - end - post('/', {}, 'rack.session' => {}, 'HTTP_ORIGIN' => 'http://malicious.com') - io.string.should match /HTTP_ORIGIN.*malicious.com/ - io.string.should_not match /reported|prevented/ - end - end - - describe "#html?" do - context "given an appropriate content-type header" do - subject { Rack::Protection::Base.new(nil).html? 'content-type' => "text/html" } - it { should be_true } - end - - context "given an inappropriate content-type header" do - subject { Rack::Protection::Base.new(nil).html? 'content-type' => "image/gif" } - it { should be_false } - end - - context "given no content-type header" do - subject { Rack::Protection::Base.new(nil).html?({}) } - it { should be_false } - end - end - - describe "#instrument" do - let(:env) { { 'rack.protection.attack' => 'base' } } - let(:instrumenter) { double('Instrumenter') } - - after do - app.instrument(env) - end - - context 'with an instrumenter specified' do - let(:app) { Rack::Protection::Base.new(nil, :instrumenter => instrumenter) } - - it { instrumenter.should_receive(:instrument).with('rack.protection', env) } - end - - context 'with no instrumenter specified' do - let(:app) { Rack::Protection::Base.new(nil) } - - it { instrumenter.should_not_receive(:instrument) } - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/remote_referrer_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/remote_referrer_spec.rb deleted file mode 100644 index 657cd40..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/remote_referrer_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::RemoteReferrer do - it_behaves_like "any rack application" - - it "accepts post requests with no referrer" do - post('/').should be_ok - end - - it "does not accept post requests with no referrer if allow_empty_referrer is false" do - mock_app do - use Rack::Protection::RemoteReferrer, :allow_empty_referrer => false - run DummyApp - end - post('/').should_not be_ok - end - - it "should allow post request with a relative referrer" do - post('/', {}, 'HTTP_REFERER' => '/').should be_ok - end - - it "accepts post requests with the same host in the referrer" do - post('/', {}, 'HTTP_REFERER' => 'http://example.com/foo', 'HTTP_HOST' => 'example.com') - last_response.should be_ok - end - - it "denies post requests with a remote referrer" do - post('/', {}, 'HTTP_REFERER' => 'http://example.com/foo', 'HTTP_HOST' => 'example.org') - last_response.should_not be_ok - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/remote_token_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/remote_token_spec.rb deleted file mode 100644 index e1abf84..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/remote_token_spec.rb +++ /dev/null @@ -1,42 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::RemoteToken do - it_behaves_like "any rack application" - - it "accepts post requests with no referrer" do - post('/').should be_ok - end - - it "accepts post requests with a local referrer" do - post('/', {}, 'HTTP_REFERER' => '/').should be_ok - end - - it "denies post requests with a remote referrer and no token" do - post('/', {}, 'HTTP_REFERER' => 'http://example.com/foo', 'HTTP_HOST' => 'example.org') - last_response.should_not be_ok - end - - it "accepts post requests with a remote referrer and correct X-CSRF-Token header" do - post('/', {}, 'HTTP_REFERER' => 'http://example.com/foo', 'HTTP_HOST' => 'example.org', - 'rack.session' => {:csrf => "a"}, 'HTTP_X_CSRF_TOKEN' => "a") - last_response.should be_ok - end - - it "denies post requests with a remote referrer and wrong X-CSRF-Token header" do - post('/', {}, 'HTTP_REFERER' => 'http://example.com/foo', 'HTTP_HOST' => 'example.org', - 'rack.session' => {:csrf => "a"}, 'HTTP_X_CSRF_TOKEN' => "b") - last_response.should_not be_ok - end - - it "accepts post form requests with a remote referrer and correct authenticity_token field" do - post('/', {"authenticity_token" => "a"}, 'HTTP_REFERER' => 'http://example.com/foo', - 'HTTP_HOST' => 'example.org', 'rack.session' => {:csrf => "a"}) - last_response.should be_ok - end - - it "denies post form requests with a remote referrer and wrong authenticity_token field" do - post('/', {"authenticity_token" => "a"}, 'HTTP_REFERER' => 'http://example.com/foo', - 'HTTP_HOST' => 'example.org', 'rack.session' => {:csrf => "b"}) - last_response.should_not be_ok - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/session_hijacking_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/session_hijacking_spec.rb deleted file mode 100644 index 21cd13f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/session_hijacking_spec.rb +++ /dev/null @@ -1,55 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::SessionHijacking do - it_behaves_like "any rack application" - - it "accepts a session without changes to tracked parameters" do - session = {:foo => :bar} - get '/', {}, 'rack.session' => session - get '/', {}, 'rack.session' => session - session[:foo].should == :bar - end - - it "denies requests with a changing User-Agent header" do - session = {:foo => :bar} - get '/', {}, 'rack.session' => session, 'HTTP_USER_AGENT' => 'a' - get '/', {}, 'rack.session' => session, 'HTTP_USER_AGENT' => 'b' - session.should be_empty - end - - it "accepts requests with a changing Accept-Encoding header" do - # this is tested because previously it led to clearing the session - session = {:foo => :bar} - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_ENCODING' => 'a' - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_ENCODING' => 'b' - session.should_not be_empty - end - - it "denies requests with a changing Accept-Language header" do - session = {:foo => :bar} - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_LANGUAGE' => 'a' - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_LANGUAGE' => 'b' - session.should be_empty - end - - it "accepts requests with the same Accept-Language header" do - session = {:foo => :bar} - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_LANGUAGE' => 'a' - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_LANGUAGE' => 'a' - session.should_not be_empty - end - - it "comparison of Accept-Language header is not case sensitive" do - session = {:foo => :bar} - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_LANGUAGE' => 'a' - get '/', {}, 'rack.session' => session, 'HTTP_ACCEPT_LANGUAGE' => 'A' - session.should_not be_empty - end - - it "accepts requests with a changing Version header"do - session = {:foo => :bar} - get '/', {}, 'rack.session' => session, 'HTTP_VERSION' => '1.0' - get '/', {}, 'rack.session' => session, 'HTTP_VERSION' => '1.1' - session[:foo].should == :bar - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/spec_helper.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/spec_helper.rb deleted file mode 100644 index 6a3a8f8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/spec_helper.rb +++ /dev/null @@ -1,163 +0,0 @@ -require 'rack/protection' -require 'rack/test' -require 'rack' -require 'forwardable' -require 'stringio' - -if defined? Gem.loaded_specs and Gem.loaded_specs.include? 'rack' - version = Gem.loaded_specs['rack'].version.to_s -else - version = Rack.release + '.0' -end - -if version == "1.3" - Rack::Session::Abstract::ID.class_eval do - private - def prepare_session(env) - session_was = env[ENV_SESSION_KEY] - env[ENV_SESSION_KEY] = SessionHash.new(self, env) - env[ENV_SESSION_OPTIONS_KEY] = OptionsHash.new(self, env, @default_options) - env[ENV_SESSION_KEY].merge! session_was if session_was - end - end -end - -unless Rack::MockResponse.method_defined? :header - Rack::MockResponse.send(:alias_method, :header, :headers) -end - -module DummyApp - def self.call(env) - Thread.current[:last_env] = env - body = (env['REQUEST_METHOD'] == 'HEAD' ? '' : 'ok') - [200, {'Content-Type' => env['wants'] || 'text/plain'}, [body]] - end -end - -module TestHelpers - extend Forwardable - def_delegators :last_response, :body, :headers, :status, :errors - def_delegators :current_session, :env_for - attr_writer :app - - def app - @app || mock_app(DummyApp) - end - - def mock_app(app = nil, &block) - app = block if app.nil? and block.arity == 1 - if app - klass = described_class - mock_app do - use Rack::Head - use(Rack::Config) { |e| e['rack.session'] ||= {}} - use klass - run app - end - else - @app = Rack::Lint.new Rack::Builder.new(&block).to_app - end - end - - def with_headers(headers) - proc { [200, {'Content-Type' => 'text/plain'}.merge(headers), ['ok']] } - end - - def env - Thread.current[:last_env] - end -end - -# see http://blog.101ideas.cz/posts/pending-examples-via-not-implemented-error-in-rspec.html -module NotImplementedAsPending - def self.included(base) - base.class_eval do - alias_method :__finish__, :finish - remove_method :finish - end - end - - def finish(reporter) - if @exception.is_a?(NotImplementedError) - from = @exception.backtrace[0] - message = "#{@exception.message} (from #{from})" - @pending_declared_in_example = message - metadata[:pending] = true - @exception = nil - end - - __finish__(reporter) - end - - RSpec::Core::Example.send :include, self -end - -RSpec.configure do |config| - config.expect_with :rspec, :stdlib - config.include Rack::Test::Methods - config.include TestHelpers -end - -shared_examples_for 'any rack application' do - it "should not interfere with normal get requests" do - get('/').should be_ok - body.should == 'ok' - end - - it "should not interfere with normal head requests" do - head('/').should be_ok - end - - it 'should not leak changes to env' do - klass = described_class - detector = Struct.new(:app) - - detector.send(:define_method, :call) do |env| - was = env.dup - res = app.call(env) - was.each do |k,v| - next if env[k] == v - fail "env[#{k.inspect}] changed from #{v.inspect} to #{env[k].inspect}" - end - res - end - - mock_app do - use Rack::Head - use(Rack::Config) { |e| e['rack.session'] ||= {}} - use detector - use klass - run DummyApp - end - - get('/..', :foo => '').should be_ok - end - - it 'allows passing on values in env' do - klass = described_class - detector = Struct.new(:app) - changer = Struct.new(:app) - - detector.send(:define_method, :call) do |env| - res = app.call(env) - env['foo.bar'].should == 42 - res - end - - changer.send(:define_method, :call) do |env| - env['foo.bar'] = 42 - app.call(env) - end - - mock_app do - use Rack::Head - use(Rack::Config) { |e| e['rack.session'] ||= {}} - use detector - use klass - use changer - run DummyApp - end - - get('/').should be_ok - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/xss_header_spec.rb b/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/xss_header_spec.rb deleted file mode 100644 index 05c9469..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rack-protection-1.5.3/spec/xss_header_spec.rb +++ /dev/null @@ -1,56 +0,0 @@ -require File.expand_path('../spec_helper.rb', __FILE__) - -describe Rack::Protection::XSSHeader do - it_behaves_like "any rack application" - - it 'should set the X-XSS-Protection' do - get('/', {}, 'wants' => 'text/html;charset=utf-8').headers["X-XSS-Protection"].should == "1; mode=block" - end - - it 'should set the X-XSS-Protection for XHTML' do - get('/', {}, 'wants' => 'application/xhtml+xml').headers["X-XSS-Protection"].should == "1; mode=block" - end - - it 'should not set the X-XSS-Protection for other content types' do - get('/', {}, 'wants' => 'application/foo').headers["X-XSS-Protection"].should be_nil - end - - it 'should allow changing the protection mode' do - # I have no clue what other modes are available - mock_app do - use Rack::Protection::XSSHeader, :xss_mode => :foo - run DummyApp - end - - get('/', {}, 'wants' => 'application/xhtml').headers["X-XSS-Protection"].should == "1; mode=foo" - end - - it 'should not override the header if already set' do - mock_app with_headers("X-XSS-Protection" => "0") - get('/', {}, 'wants' => 'text/html').headers["X-XSS-Protection"].should == "0" - end - - it 'should set the X-Content-Type-Options' do - get('/', {}, 'wants' => 'text/html').header["X-Content-Type-Options"].should == "nosniff" - end - - - it 'should set the X-Content-Type-Options for other content types' do - get('/', {}, 'wants' => 'application/foo').header["X-Content-Type-Options"].should == "nosniff" - end - - - it 'should allow changing the nosniff-mode off' do - mock_app do - use Rack::Protection::XSSHeader, :nosniff => false - run DummyApp - end - - get('/').headers["X-Content-Type-Options"].should be_nil - end - - it 'should not override the header if already set X-Content-Type-Options' do - mock_app with_headers("X-Content-Type-Options" => "sniff") - get('/', {}, 'wants' => 'text/html').headers["X-Content-Type-Options"].should == "sniff" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.document b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.document deleted file mode 100644 index 8b5bcdf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.document +++ /dev/null @@ -1,8 +0,0 @@ -README -LICENSE -NEWS -ChangeLog -lib -ext/raindrops/raindrops.c -ext/raindrops/linux_inet_diag.c -ext/raindrops/linux_tcp_info.c diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.gitignore b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.gitignore deleted file mode 100644 index 0a82218..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -*.o -*.so -*.log -*.rbc -Makefile -/GIT-VERSION-FILE -/local.mk -/NEWS -/ChangeLog -/.manifest -/man -/pkg -/doc -/LATEST -/tmp -/.rbx diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.wrongdoc.yml b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.wrongdoc.yml deleted file mode 100644 index f31fa66..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/.wrongdoc.yml +++ /dev/null @@ -1,6 +0,0 @@ ---- -cgit_url: http://bogomips.org/raindrops.git -git_url: git://bogomips.org/raindrops.git -rdoc_url: http://raindrops.bogomips.org/ -public_email: raindrops@librelist.org -private_email: raindrops@bogomips.org diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/COPYING b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/COPYING deleted file mode 100644 index cca7fc2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/COPYING +++ /dev/null @@ -1,165 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - - This version of the GNU Lesser General Public License incorporates -the terms and conditions of version 3 of the GNU General Public -License, supplemented by the additional permissions listed below. - - 0. Additional Definitions. - - As used herein, "this License" refers to version 3 of the GNU Lesser -General Public License, and the "GNU GPL" refers to version 3 of the GNU -General Public License. - - "The Library" refers to a covered work governed by this License, -other than an Application or a Combined Work as defined below. - - An "Application" is any work that makes use of an interface provided -by the Library, but which is not otherwise based on the Library. -Defining a subclass of a class defined by the Library is deemed a mode -of using an interface provided by the Library. - - A "Combined Work" is a work produced by combining or linking an -Application with the Library. The particular version of the Library -with which the Combined Work was made is also called the "Linked -Version". - - The "Minimal Corresponding Source" for a Combined Work means the -Corresponding Source for the Combined Work, excluding any source code -for portions of the Combined Work that, considered in isolation, are -based on the Application, and not on the Linked Version. - - The "Corresponding Application Code" for a Combined Work means the -object code and/or source code for the Application, including any data -and utility programs needed for reproducing the Combined Work from the -Application, but excluding the System Libraries of the Combined Work. - - 1. Exception to Section 3 of the GNU GPL. - - You may convey a covered work under sections 3 and 4 of this License -without being bound by section 3 of the GNU GPL. - - 2. Conveying Modified Versions. - - If you modify a copy of the Library, and, in your modifications, a -facility refers to a function or data to be supplied by an Application -that uses the facility (other than as an argument passed when the -facility is invoked), then you may convey a copy of the modified -version: - - a) under this License, provided that you make a good faith effort to - ensure that, in the event an Application does not supply the - function or data, the facility still operates, and performs - whatever part of its purpose remains meaningful, or - - b) under the GNU GPL, with none of the additional permissions of - this License applicable to that copy. - - 3. Object Code Incorporating Material from Library Header Files. - - The object code form of an Application may incorporate material from -a header file that is part of the Library. You may convey such object -code under terms of your choice, provided that, if the incorporated -material is not limited to numerical parameters, data structure -layouts and accessors, or small macros, inline functions and templates -(ten or fewer lines in length), you do both of the following: - - a) Give prominent notice with each copy of the object code that the - Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the object code with a copy of the GNU GPL and this license - document. - - 4. Combined Works. - - You may convey a Combined Work under terms of your choice that, -taken together, effectively do not restrict modification of the -portions of the Library contained in the Combined Work and reverse -engineering for debugging such modifications, if you also do each of -the following: - - a) Give prominent notice with each copy of the Combined Work that - the Library is used in it and that the Library and its use are - covered by this License. - - b) Accompany the Combined Work with a copy of the GNU GPL and this license - document. - - c) For a Combined Work that displays copyright notices during - execution, include the copyright notice for the Library among - these notices, as well as a reference directing the user to the - copies of the GNU GPL and this license document. - - d) Do one of the following: - - 0) Convey the Minimal Corresponding Source under the terms of this - License, and the Corresponding Application Code in a form - suitable for, and under terms that permit, the user to - recombine or relink the Application with a modified version of - the Linked Version to produce a modified Combined Work, in the - manner specified by section 6 of the GNU GPL for conveying - Corresponding Source. - - 1) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (a) uses at run time - a copy of the Library already present on the user's computer - system, and (b) will operate properly with a modified version - of the Library that is interface-compatible with the Linked - Version. - - e) Provide Installation Information, but only if you would otherwise - be required to provide such information under section 6 of the - GNU GPL, and only to the extent that such information is - necessary to install and execute a modified version of the - Combined Work produced by recombining or relinking the - Application with a modified version of the Linked Version. (If - you use option 4d0, the Installation Information must accompany - the Minimal Corresponding Source and Corresponding Application - Code. If you use option 4d1, you must provide the Installation - Information in the manner specified by section 6 of the GNU GPL - for conveying Corresponding Source.) - - 5. Combined Libraries. - - You may place library facilities that are a work based on the -Library side by side in a single library together with other library -facilities that are not Applications and are not covered by this -License, and convey such a combined library under terms of your -choice, if you do both of the following: - - a) Accompany the combined library with a copy of the same work based - on the Library, uncombined with any other library facilities, - conveyed under the terms of this License. - - b) Give prominent notice with the combined library that part of it - is a work based on the Library, and explaining where to find the - accompanying uncombined form of the same work. - - 6. Revised Versions of the GNU Lesser General Public License. - - The Free Software Foundation may publish revised and/or new versions -of the GNU Lesser General Public License from time to time. Such new -versions will be similar in spirit to the present version, but may -differ in detail to address new problems or concerns. - - Each version is given a distinguishing version number. If the -Library as you received it specifies that a certain numbered version -of the GNU Lesser General Public License "or any later version" -applies to it, you have the option of following the terms and -conditions either of that published version or of any later version -published by the Free Software Foundation. If the Library as you -received it does not specify a version number of the GNU Lesser -General Public License, you may choose any version of the GNU Lesser -General Public License ever published by the Free Software Foundation. - - If the Library as you received it specifies that a proxy can decide -whether future versions of the GNU Lesser General Public License shall -apply, that proxy's public statement of acceptance of any version is -permanent authorization for you to choose that version for the -Library. diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/GIT-VERSION-GEN b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/GIT-VERSION-GEN deleted file mode 100755 index f643739..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/GIT-VERSION-GEN +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/sh - -GVF=GIT-VERSION-FILE -DEF_VER=v0.13.0 - -LF=' -' - -# First see if there is a version file (included in release tarballs), -# then try git-describe, then default. -if test -f version -then - VN=$(cat version) || VN="$DEF_VER" -elif test -d .git -o -f .git && - VN=$(git describe --abbrev=4 HEAD 2>/dev/null) && - case "$VN" in - *$LF*) (exit 1) ;; - v[0-9]*) - git update-index -q --refresh - test -z "$(git diff-index --name-only HEAD --)" || - VN="$VN-dirty" ;; - esac -then - VN=$(echo "$VN" | sed -e 's/-/./g'); -else - VN="$DEF_VER" -fi - -VN=$(expr "$VN" : v*'\(.*\)') - -if test -r $GVF -then - VC=$(sed -e 's/^GIT_VERSION = //' <$GVF) -else - VC=unset -fi -test "$VN" = "$VC" || { - echo >&2 "GIT_VERSION = $VN" - echo "GIT_VERSION = $VN" >$GVF -} diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/GNUmakefile b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/GNUmakefile deleted file mode 100644 index 3f7829a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/GNUmakefile +++ /dev/null @@ -1,5 +0,0 @@ -all:: -RSYNC_DEST := bogomips.org:/srv/raindrops -rfproject := rainbows -rfpackage := raindrops -include pkg.mk diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/LICENSE b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/LICENSE deleted file mode 100644 index a3dbff6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -raindrops is copyrighted Free Software by all contributors, see logs in -revision control for names and email addresses of all of them. - -You can redistribute it and/or modify it under the terms of the GNU -Lesser General Public License (LGPL) as published by the Free Software -Foundation, version {2.1}[http://www.gnu.org/licenses/lgpl-2.1.txt] or -later. Currently version {3}[http://www.gnu.org/licenses/lgpl-3.0.txt], -is preferred (see link:COPYING). - -raindrops is distributed in the hope that it will be useful, but WITHOUT -ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or -FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public -License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with the raindrops; if not, see diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/README b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/README deleted file mode 100644 index 3b76b06..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/README +++ /dev/null @@ -1,108 +0,0 @@ -= raindrops - real-time stats for preforking Rack servers - -Raindrops is a real-time stats toolkit to show statistics for Rack HTTP -servers. It is designed for preforking servers such as Rainbows! and -Unicorn, but should support any Rack HTTP server under Ruby 2.0, 1.9, -1.8 and Rubinius on platforms supporting POSIX shared memory. It may -also be used as a generic scoreboard for sharing atomic counters across -multiple processes. - -== Features - -* counters are shared across all forked children and lock-free - -* counters are kept on separate cache lines to reduce contention under SMP - -* may expose server statistics as a Rack Middleware endpoint - (default: "/_raindrops") - -* middleware displays the number of actively processing and writing - clients from a single request regardless of which worker process - it hits. - -== Linux-only Extra Features! - -* Middleware response includes extra stats for bound TCP and - Unix domain sockets (configurable, it can include stats from - other TCP or UNIX domain socket servers). - -* TCP socket stats use efficient inet_diag facilities via netlink - instead of parsing /proc/net/tcp to minimize overhead. - This was fun to discover and write. - -* TCP_Info reporting may be used to check stat for every accepted client - on TCP servers - -Users of older Linux kernels need to ensure that the the "inet_diag" -and "tcp_diag" kernel modules are loaded as they do not autoload correctly - -== Install - -We recommend GCC 4+ (or compatible) to support the -{atomic builtins}[http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html] -(__sync_{add,sub}_and_fetch()). For non-GCC 4+ users, we also support -compilation with the -{libatomic_ops}[http://www.hpl.hp.com/research/linux/atomic_ops/] -package starting with Raindrops 0.4.0. - -If you're using a packaged Ruby distribution, make sure you have a C -compiler and the matching Ruby development libraries and headers. - -If you use RubyGems: - - gem install raindrops - -Otherwise grab the latest tarball from: - -http://raindrops.bogomips.org/files/ - -Unpack it, and run "ruby setup.rb" - -== Usage - -See Raindrops::Middleware and Raindrops::LastDataRecv documentation for -use Rack servers. The entire library is fully-documented and we are -responsive on the mailing list (mailto:raindrops@librelist.org) if you -have any questions or comments. - -== Development - -You can get the latest source via git from the following locations: - - git://bogomips.org/raindrops.git - git://repo.or.cz/raindrops.git (mirror) - -You may browse the code from the web and download the latest snapshot -tarballs here: - -* http://bogomips.org/raindrops.git (cgit) -* http://repo.or.cz/w/raindrops.git (gitweb) - -Inline patches (from "git format-patch") to the mailing list are -preferred because they allow code review and comments in the reply to -the patch. - -We will adhere to mostly the same conventions for patch submissions as -git itself. See the Documentation/SubmittingPatches document -distributed with git on on patch submission guidelines to follow. Just -don't email the git mailing list or maintainer with raindrops patches. - -raindrops is currently dual-licensed under the LGPLv2.1 and LGPLv3. To -allow for a transition to future versions of the LGPL, contributors are -required to sign-off changes allowing allowing the project leader to -relicense raindrops under newer versions of the LGPL (which should be -similar in spirit to the existing LGPL). - -== Contact - -All feedback (bug reports, user/development discussion, patches, pull -requests) go to the mailing list: mailto:raindrops@librelist.org - -The mailing list is mirrored to Gmane, all information about the -group is here: - -http://gmane.org/info.php?group=gmane.comp.lang.ruby.raindrops.general - -Mailing list archives in mbox format may be downloaded here: - -http://raindrops.bogomips.org/archives/ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/Rakefile b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/Rakefile deleted file mode 100644 index e8890b6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/Rakefile +++ /dev/null @@ -1,28 +0,0 @@ -desc "read news article from STDIN and post to rubyforge" -task :publish_news do - require 'rubyforge' - spec = Gem::Specification.load('raindrops.gemspec') - tmp = Tempfile.new('rf-news') - _, subject, body = `git cat-file tag v#{spec.version}`.split(/\n\n/, 3) - tmp.puts subject - tmp.puts - tmp.puts spec.description.strip - tmp.puts "" - tmp.puts "* #{spec.homepage}" - tmp.puts "* #{spec.email}" - tmp.puts "* #{git_url}" - tmp.print "\nChanges:\n\n" - tmp.puts body - tmp.flush - system(ENV["VISUAL"], tmp.path) or abort "#{ENV["VISUAL"]} failed: #$?" - msg = File.readlines(tmp.path) - subject = msg.shift - blank = msg.shift - blank == "\n" or abort "no newline after subject!" - subject.strip! - body = msg.join("").strip! - - rf = RubyForge.new.configure - rf.login - rf.post_news('rainbows', subject, body) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/TODO b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/TODO deleted file mode 100644 index 7820941..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/TODO +++ /dev/null @@ -1 +0,0 @@ -* pure Ruby version for non-forking servers (patches welcome!) diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/linux-listener-stats.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/linux-listener-stats.rb deleted file mode 100755 index 1008995..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/linux-listener-stats.rb +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/ruby -# -*- encoding: binary -*- -$stdout.sync = $stderr.sync = true -# this is used to show or watch the number of active and queued -# connections on any listener socket from the command line - -require 'raindrops' -require 'optparse' -require 'ipaddr' -require 'time' -begin - require 'sleepy_penguin' -rescue LoadError -end -usage = "Usage: #$0 [-d DELAY] [-t QUEUED_THRESHOLD] ADDR..." -ARGV.size > 0 or abort usage -delay = false -all = false -queued_thresh = -1 -# "normal" exits when driven on the command-line -trap(:INT) { exit 130 } -trap(:PIPE) { exit 0 } - -OptionParser.new('', 24, ' ') do |opts| - opts.banner = usage - opts.on('-d', '--delay=DELAY', Float) { |n| delay = n } - opts.on('-t', '--queued-threshold=INT', Integer) { |n| queued_thresh = n } - opts.on('-a', '--all') { all = true } - opts.parse! ARGV -end - -begin - require 'aggregate' -rescue LoadError - $stderr.puts "Aggregate missing, USR1 and USR2 handlers unavailable" -end if delay - -if delay && defined?(SleepyPenguin::TimerFD) - @tfd = SleepyPenguin::TimerFD.new - @tfd.settime nil, delay, delay - def delay_for(seconds) - @tfd.expirations - end -else - alias delay_for sleep -end - -agg_active = agg_queued = nil -if delay && defined?(Aggregate) - agg_active = Aggregate.new - agg_queued = Aggregate.new - - def dump_aggregate(label, agg) - $stderr.write "--- #{label} ---\n" - %w(count min max outliers_low outliers_high mean std_dev).each do |f| - $stderr.write "#{f}=#{agg.__send__ f}\n" - end - $stderr.write "#{agg}\n\n" - end - - trap(:USR1) do - dump_aggregate "active", agg_active - dump_aggregate "queued", agg_queued - end - trap(:USR2) do - agg_active = Aggregate.new - agg_queued = Aggregate.new - end - $stderr.puts "USR1(dump_aggregate) and USR2(reset) handlers ready for PID=#$$" -end - -ARGV.each do |addr| - addr =~ %r{\A(127\..+):(\d+)\z} or next - host, port = $1, $2 - hex_port = '%X' % port.to_i - ip_addr = IPAddr.new(host) - hex_host = ip_addr.hton.each_byte.inject('') { |s,o| s << '%02X' % o } - socks = File.readlines('/proc/net/tcp') - hex_addr = "#{hex_host}:#{hex_port}" - if socks.grep(/^\s+\d+:\s+#{hex_addr}\s+/).empty? && - ! socks.grep(/^\s+\d+:\s+00000000:#{hex_port}\s+/).empty? - warn "W: #{host}:#{port} (#{hex_addr}) not found in /proc/net/tcp" - warn "W: Did you mean 0.0.0.0:#{port}?" - end -end - -len = "address".size -now = nil -tcp, unix = [], [] -ARGV.each do |addr| - bs = addr.respond_to?(:bytesize) ? addr.bytesize : addr.size - len = bs if bs > len - (addr =~ %r{\A/} ? unix : tcp) << addr -end -combined = {} -tcp_args = unix_args = nil -unless tcp.empty? && unix.empty? - tcp_args = tcp - unix_args = unix -end -sock = Raindrops::InetDiagSocket.new if tcp - -len = 35 if len > 35 -fmt = "%20s % #{len}s % 10u % 10u\n" -$stderr.printf fmt.tr('u','s'), *%w(timestamp address active queued) - -begin - if now - combined.clear - now = nil - end - combined.merge! Raindrops::Linux.tcp_listener_stats(tcp_args, sock) - combined.merge! Raindrops::Linux.unix_listener_stats(unix_args) - combined.each do |addr,stats| - active, queued = stats.active, stats.queued - if agg_active - agg_active << active - agg_queued << queued - end - next if queued < queued_thresh - printf fmt, now ||= Time.now.utc.iso8601, addr, active, queued - end -end while delay && delay_for(delay) diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/middleware.ru b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/middleware.ru deleted file mode 100644 index 642016b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/middleware.ru +++ /dev/null @@ -1,5 +0,0 @@ -# sample stand-alone rackup application for Raindrops::Middleware -require 'rack/lobster' -require 'raindrops' -use Raindrops::Middleware -run Rack::Lobster.new diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/watcher.ru b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/watcher.ru deleted file mode 100644 index a3e7fdb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/watcher.ru +++ /dev/null @@ -1,4 +0,0 @@ -# Sample standalone Rack application, recommended use is with Zbatery -# See zbatery.conf.rb -require "raindrops" -run Raindrops::Watcher.new diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/watcher_demo.ru b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/watcher_demo.ru deleted file mode 100644 index 1173461..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/watcher_demo.ru +++ /dev/null @@ -1,13 +0,0 @@ -# This is a snippet of the config that powers -# http://raindrops-demo.bogomips.org/ -# This may be used with the packaged zbatery.conf.rb -# -# zbatery -c zbatery.conf.ru watcher_demo.ru -E none -require "raindrops" -use Raindrops::Middleware -listeners = %w( - 0.0.0.0:9418 - 0.0.0.0:80 - /tmp/.r -) -run Raindrops::Watcher.new :listeners => listeners diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/zbatery.conf.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/zbatery.conf.rb deleted file mode 100644 index 3f67c7a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/examples/zbatery.conf.rb +++ /dev/null @@ -1,13 +0,0 @@ -# Used for running Raindrops::Watcher, which requires a multi-threaded -# Rack server capable of streaming a response. Threads must be used, -# so Zbatery is recommended: http://zbatery.bogomip.org/ -Rainbows! do - use :ThreadSpawn -end -log_dir = "/var/log/zbatery" -if File.writable?(log_dir) && File.directory?(log_dir) - stderr_path "#{log_dir}/raindrops-demo.stderr.log" - stdout_path "#{log_dir}/raindrops-demo.stdout.log" - listen "/tmp/.r" - pid "/tmp/.raindrops.pid" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/.RUBYARCHDIR.time b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/.RUBYARCHDIR.time deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/extconf.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/extconf.rb deleted file mode 100644 index f012808..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/extconf.rb +++ /dev/null @@ -1,55 +0,0 @@ -require 'mkmf' - -dir_config('atomic_ops') -have_func('mmap', 'sys/mman.h') or abort 'mmap() not found' -have_func('munmap', 'sys/mman.h') or abort 'munmap() not found' - -$CPPFLAGS += " -D_GNU_SOURCE " -have_func('mremap', 'sys/mman.h') - -$CPPFLAGS += " -D_BSD_SOURCE " -have_func("getpagesize", "unistd.h") -have_func('rb_thread_blocking_region') -have_func('rb_thread_io_blocking_region') - -checking_for "GCC 4+ atomic builtins" do - # we test CMPXCHG anyways even though we don't need it to filter out - # ancient i386-only targets without CMPXCHG - src = < -#ifdef HAVE_RUBY_ST_H -# include -#else -# include -#endif -#include "my_fileno.h" -#ifdef __linux__ - -/* Ruby 1.8.6+ macros (for compatibility with Ruby 1.9) */ -#ifndef RSTRING_LEN -# define RSTRING_LEN(s) (RSTRING(s)->len) -#endif - -/* partial emulation of the 1.9 rb_thread_blocking_region under 1.8 */ -#if !defined(HAVE_RB_THREAD_BLOCKING_REGION) && \ - !defined(HAVE_RB_THREAD_IO_BLOCKING_REGION) -# include -# define RUBY_UBF_IO ((rb_unblock_function_t *)-1) -typedef void rb_unblock_function_t(void *); -typedef VALUE rb_blocking_function_t(void *); -static VALUE -rb_thread_blocking_region( - rb_blocking_function_t *func, void *data1, - rb_unblock_function_t *ubf, void *data2) -{ - VALUE rv; - - TRAP_BEG; - rv = func(data1); - TRAP_END; - - return rv; -} -#endif /* ! HAVE_RB_THREAD_BLOCKING_REGION */ - -#ifdef HAVE_RB_THREAD_IO_BLOCKING_REGION -VALUE rb_thread_io_blocking_region(rb_blocking_function_t *, void *, int); -#else -# define rb_thread_io_blocking_region(fn,data,fd) \ - rb_thread_blocking_region((fn),(data),RUBY_UBF_IO,0) -#endif /* HAVE_RB_THREAD_IO_BLOCKING_REGION */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -union any_addr { - struct sockaddr_storage ss; - struct sockaddr sa; - struct sockaddr_in in; - struct sockaddr_in6 in6; -}; - -static size_t page_size; -static unsigned g_seq; -static VALUE cListenStats, cIDSock; -static ID id_new; - -struct listen_stats { - uint32_t active; - uint32_t queued; - uint32_t listener_p; -}; - -#define OPLEN (sizeof(struct inet_diag_bc_op) + \ - sizeof(struct inet_diag_hostcond) + \ - sizeof(struct sockaddr_storage)) - -struct nogvl_args { - st_table *table; - struct iovec iov[3]; /* last iov holds inet_diag bytecode */ - struct listen_stats stats; - int fd; -}; - -#ifdef SOCK_CLOEXEC -# define my_SOCK_RAW (SOCK_RAW|SOCK_CLOEXEC) -# define FORCE_CLOEXEC(v) (v) -#else -# define my_SOCK_RAW SOCK_RAW -static VALUE FORCE_CLOEXEC(VALUE io) -{ - int fd = my_fileno(io); - int flags = fcntl(fd, F_SETFD, FD_CLOEXEC); - if (flags == -1) - rb_sys_fail("fcntl(F_SETFD, FD_CLOEXEC)"); - return io; -} -#endif - -/* - * call-seq: - * Raindrops::InetDiagSocket.new -> Socket - * - * Creates a new Socket object for the netlink inet_diag facility - */ -static VALUE ids_s_new(VALUE klass) -{ - VALUE argv[3]; - - argv[0] = INT2NUM(AF_NETLINK); - argv[1] = INT2NUM(my_SOCK_RAW); - argv[2] = INT2NUM(NETLINK_INET_DIAG); - - return FORCE_CLOEXEC(rb_call_super(3, argv)); -} - -/* creates a Ruby ListenStats Struct based on our internal listen_stats */ -static VALUE rb_listen_stats(struct listen_stats *stats) -{ - VALUE active = UINT2NUM(stats->active); - VALUE queued = UINT2NUM(stats->queued); - - return rb_struct_new(cListenStats, active, queued); -} - -static int st_free_data(st_data_t key, st_data_t value, st_data_t ignored) -{ - xfree((void *)key); - xfree((void *)value); - - return ST_DELETE; -} - -/* - * call-seq: - * remove_scope_id(ip_address) - * - * Returns copy of IP address with Scope ID removed, - * if address has it (only IPv6 actually may have it). - */ -static VALUE remove_scope_id(const char *addr) -{ - VALUE rv = rb_str_new2(addr); - long len = RSTRING_LEN(rv); - char *ptr = RSTRING_PTR(rv); - char *pct = memchr(ptr, '%', len); - - /* - * remove scoped portion - * Ruby equivalent: rv.sub!(/%([^\]]*)\]/, "]") - */ - if (pct) { - size_t newlen = pct - ptr; - char *rbracket = memchr(pct, ']', len - newlen); - - if (rbracket) { - size_t move = len - (rbracket - ptr); - - memmove(pct, rbracket, move); - newlen += move; - - rb_str_set_len(rv, newlen); - } else { - rb_raise(rb_eArgError, - "']' not found in IPv6 addr=%s", ptr); - } - } - return rv; -} - -static int st_to_hash(st_data_t key, st_data_t value, VALUE hash) -{ - struct listen_stats *stats = (struct listen_stats *)value; - - if (stats->listener_p) { - VALUE k = remove_scope_id((const char *)key); - VALUE v = rb_listen_stats(stats); - - OBJ_FREEZE(k); - rb_hash_aset(hash, k, v); - } - return st_free_data(key, value, 0); -} - -static int st_AND_hash(st_data_t key, st_data_t value, VALUE hash) -{ - struct listen_stats *stats = (struct listen_stats *)value; - - if (stats->listener_p) { - VALUE k = remove_scope_id((const char *)key); - - if (rb_hash_lookup(hash, k) == Qtrue) { - VALUE v = rb_listen_stats(stats); - OBJ_FREEZE(k); - rb_hash_aset(hash, k, v); - } - } - return st_free_data(key, value, 0); -} - -static const char *addr_any(sa_family_t family) -{ - static const char ipv4[] = "0.0.0.0"; - static const char ipv6[] = "[::]"; - - if (family == AF_INET) - return ipv4; - assert(family == AF_INET6 && "unknown family"); - return ipv6; -} - -static void bug_warn(void) -{ - fprintf(stderr, "Please report how you produced this at "\ - "raindrops@librelist.org\n"); - fflush(stderr); -} - -static struct listen_stats *stats_for(st_table *table, struct inet_diag_msg *r) -{ - char *key, *port, *old_key; - size_t alloca_len; - struct listen_stats *stats; - size_t keylen; - size_t portlen = sizeof("65535"); - union any_addr sa; - socklen_t len = sizeof(struct sockaddr_storage); - int rc; - int flags = NI_NUMERICHOST | NI_NUMERICSERV; - - switch ((sa.ss.ss_family = r->idiag_family)) { - case AF_INET: { - sa.in.sin_port = r->id.idiag_sport; - sa.in.sin_addr.s_addr = r->id.idiag_src[0]; - keylen = INET_ADDRSTRLEN; - alloca_len = keylen + 1 + portlen; - key = alloca(alloca_len); - key[keylen] = 0; /* will be ':' later */ - port = key + keylen + 1; - rc = getnameinfo(&sa.sa, len, - key, keylen, port, portlen, flags); - break; - } - case AF_INET6: { - sa.in6.sin6_port = r->id.idiag_sport; - memcpy(&sa.in6.sin6_addr, &r->id.idiag_src, sizeof(__be32[4])); - keylen = INET6_ADDRSTRLEN; - /* [ ] */ - alloca_len = 1 + keylen + 1 + 1 + portlen; - key = alloca(alloca_len); - *key = '['; - key[1 + keylen + 1] = 0; /* will be ':' later */ - port = 1 + key + keylen + 1 + 1; - rc = getnameinfo(&sa.sa, len, - key + 1, keylen, port, portlen, flags); - break; - } - default: - assert(0 && "unsupported address family, could that be IPv7?!"); - } - if (rc != 0) { - fprintf(stderr, "BUG: getnameinfo: %s\n", gai_strerror(rc)); - bug_warn(); - *key = 0; - } - - keylen = strlen(key); - portlen = strlen(port); - - switch (sa.ss.ss_family) { - case AF_INET: - key[keylen] = ':'; - memmove(key + keylen + 1, port, portlen + 1); - break; - case AF_INET6: - key[keylen] = ']'; - key[keylen + 1] = ':'; - memmove(key + keylen + 2, port, portlen + 1); - keylen++; - break; - default: - assert(0 && "unsupported address family, could that be IPv7?!"); - } - - if (st_lookup(table, (st_data_t)key, (st_data_t *)&stats)) - return stats; - - old_key = key; - - if (r->idiag_state == TCP_ESTABLISHED) { - int n = snprintf(key, alloca_len, "%s:%u", - addr_any(sa.ss.ss_family), - ntohs(r->id.idiag_sport)); - if (n <= 0) { - fprintf(stderr, "BUG: snprintf: %d\n", n); - bug_warn(); - } - if (st_lookup(table, (st_data_t)key, (st_data_t *)&stats)) - return stats; - if (n <= 0) { - key = xmalloc(1); - *key = '\0'; - } else { - old_key = key; - key = xmalloc(n + 1); - memcpy(key, old_key, n + 1); - } - } else { - key = xmalloc(keylen + 1 + portlen + 1); - memcpy(key, old_key, keylen + 1 + portlen + 1); - } - stats = xcalloc(1, sizeof(struct listen_stats)); - st_insert(table, (st_data_t)key, (st_data_t)stats); - return stats; -} - -static void table_incr_active(st_table *table, struct inet_diag_msg *r) -{ - struct listen_stats *stats = stats_for(table, r); - ++stats->active; -} - -static void table_set_queued(st_table *table, struct inet_diag_msg *r) -{ - struct listen_stats *stats = stats_for(table, r); - stats->listener_p = 1; - stats->queued = r->idiag_rqueue; -} - -/* inner loop of inet_diag, called for every socket returned by netlink */ -static inline void r_acc(struct nogvl_args *args, struct inet_diag_msg *r) -{ - /* - * inode == 0 means the connection is still in the listen queue - * and has not yet been accept()-ed by the server. The - * inet_diag bytecode cannot filter this for us. - */ - if (r->idiag_inode == 0) - return; - if (r->idiag_state == TCP_ESTABLISHED) { - if (args->table) - table_incr_active(args->table, r); - else - args->stats.active++; - } else { /* if (r->idiag_state == TCP_LISTEN) */ - if (args->table) - table_set_queued(args->table, r); - else - args->stats.queued = r->idiag_rqueue; - } - /* - * we wont get anything else because of the idiag_states filter - */ -} - -static const char err_sendmsg[] = "sendmsg"; -static const char err_recvmsg[] = "recvmsg"; -static const char err_nlmsg[] = "nlmsg"; - -struct diag_req { - struct nlmsghdr nlh; - struct inet_diag_req r; -}; - -static void prep_msghdr( - struct msghdr *msg, - struct nogvl_args *args, - struct sockaddr_nl *nladdr, - size_t iovlen) -{ - memset(msg, 0, sizeof(struct msghdr)); - msg->msg_name = (void *)nladdr; - msg->msg_namelen = sizeof(struct sockaddr_nl); - msg->msg_iov = args->iov; - msg->msg_iovlen = iovlen; -} - -static void prep_diag_args( - struct nogvl_args *args, - struct sockaddr_nl *nladdr, - struct rtattr *rta, - struct diag_req *req, - struct msghdr *msg) -{ - memset(req, 0, sizeof(struct diag_req)); - memset(nladdr, 0, sizeof(struct sockaddr_nl)); - - nladdr->nl_family = AF_NETLINK; - - req->nlh.nlmsg_len = sizeof(struct diag_req) + - RTA_LENGTH(args->iov[2].iov_len); - req->nlh.nlmsg_type = TCPDIAG_GETSOCK; - req->nlh.nlmsg_flags = NLM_F_ROOT | NLM_F_MATCH | NLM_F_REQUEST; - req->nlh.nlmsg_pid = getpid(); - req->r.idiag_states = (1<rta_type = INET_DIAG_REQ_BYTECODE; - rta->rta_len = RTA_LENGTH(args->iov[2].iov_len); - - args->iov[0].iov_base = req; - args->iov[0].iov_len = sizeof(struct diag_req); - args->iov[1].iov_base = rta; - args->iov[1].iov_len = sizeof(struct rtattr); - - prep_msghdr(msg, args, nladdr, 3); -} - -static void prep_recvmsg_buf(struct nogvl_args *args) -{ - /* reuse buffer that was allocated for bytecode */ - args->iov[0].iov_len = page_size; - args->iov[0].iov_base = args->iov[2].iov_base; -} - -/* does the inet_diag stuff with netlink(), this is called w/o GVL */ -static VALUE diag(void *ptr) -{ - struct nogvl_args *args = ptr; - struct sockaddr_nl nladdr; - struct rtattr rta; - struct diag_req req; - struct msghdr msg; - const char *err = NULL; - unsigned seq = ++g_seq; - - prep_diag_args(args, &nladdr, &rta, &req, &msg); - req.nlh.nlmsg_seq = seq; - - if (sendmsg(args->fd, &msg, 0) < 0) { - err = err_sendmsg; - goto out; - } - - prep_recvmsg_buf(args); - - while (1) { - ssize_t readed; - size_t r; - struct nlmsghdr *h = (struct nlmsghdr *)args->iov[0].iov_base; - - prep_msghdr(&msg, args, &nladdr, 1); - readed = recvmsg(args->fd, &msg, 0); - if (readed < 0) { - if (errno == EINTR) - continue; - err = err_recvmsg; - goto out; - } - if (readed == 0) - goto out; - r = (size_t)readed; - for ( ; NLMSG_OK(h, r); h = NLMSG_NEXT(h, r)) { - if (h->nlmsg_seq != seq) - continue; - if (h->nlmsg_type == NLMSG_DONE) - goto out; - if (h->nlmsg_type == NLMSG_ERROR) { - err = err_nlmsg; - goto out; - } - r_acc(args, NLMSG_DATA(h)); - } - } -out: - { - int save_errno = errno; - if (err && args->table) { - st_foreach(args->table, st_free_data, 0); - st_free_table(args->table); - } - errno = save_errno; - } - return (VALUE)err; -} - -/* populates sockaddr_storage struct by parsing +addr+ */ -static void parse_addr(union any_addr *inet, VALUE addr) -{ - char *host_ptr; - char *check; - char *colon = NULL; - char *rbracket = NULL; - void *dst; - long host_len; - int af, rc; - uint16_t *portdst; - unsigned long port; - - Check_Type(addr, T_STRING); - host_ptr = StringValueCStr(addr); - host_len = RSTRING_LEN(addr); - if (*host_ptr == '[') { /* ipv6 address format (rfc2732) */ - rbracket = memchr(host_ptr + 1, ']', host_len - 1); - - if (rbracket == NULL) - rb_raise(rb_eArgError, "']' not found in IPv6 addr=%s", - host_ptr); - if (rbracket[1] != ':') - rb_raise(rb_eArgError, "':' not found in IPv6 addr=%s", - host_ptr); - colon = rbracket + 1; - host_ptr++; - *rbracket = 0; - inet->ss.ss_family = af = AF_INET6; - dst = &inet->in6.sin6_addr; - portdst = &inet->in6.sin6_port; - } else { /* ipv4 */ - colon = memchr(host_ptr, ':', host_len); - inet->ss.ss_family = af = AF_INET; - dst = &inet->in.sin_addr; - portdst = &inet->in.sin_port; - } - - if (!colon) - rb_raise(rb_eArgError, "port not found in: `%s'", host_ptr); - port = strtoul(colon + 1, &check, 10); - *colon = 0; - rc = inet_pton(af, host_ptr, dst); - *colon = ':'; - if (rbracket) *rbracket = ']'; - if (*check || ((uint16_t)port != port)) - rb_raise(rb_eArgError, "invalid port: %s", colon + 1); - if (rc != 1) - rb_raise(rb_eArgError, "inet_pton failed for: `%s' with %d", - host_ptr, rc); - *portdst = ntohs((uint16_t)port); -} - -/* generates inet_diag bytecode to match all addrs */ -static void gen_bytecode_all(struct iovec *iov) -{ - struct inet_diag_bc_op *op; - struct inet_diag_hostcond *cond; - - /* iov_len was already set and base allocated in a parent function */ - assert(iov->iov_len == OPLEN && iov->iov_base && "iov invalid"); - op = iov->iov_base; - op->code = INET_DIAG_BC_S_COND; - op->yes = OPLEN; - op->no = sizeof(struct inet_diag_bc_op) + OPLEN; - cond = (struct inet_diag_hostcond *)(op + 1); - cond->family = AF_UNSPEC; - cond->port = -1; - cond->prefix_len = 0; -} - -/* generates inet_diag bytecode to match a single addr */ -static void gen_bytecode(struct iovec *iov, union any_addr *inet) -{ - struct inet_diag_bc_op *op; - struct inet_diag_hostcond *cond; - - /* iov_len was already set and base allocated in a parent function */ - assert(iov->iov_len == OPLEN && iov->iov_base && "iov invalid"); - op = iov->iov_base; - op->code = INET_DIAG_BC_S_COND; - op->yes = OPLEN; - op->no = sizeof(struct inet_diag_bc_op) + OPLEN; - - cond = (struct inet_diag_hostcond *)(op + 1); - cond->family = inet->ss.ss_family; - switch (inet->ss.ss_family) { - case AF_INET: { - cond->port = ntohs(inet->in.sin_port); - cond->prefix_len = inet->in.sin_addr.s_addr == 0 ? 0 : - sizeof(inet->in.sin_addr.s_addr) * CHAR_BIT; - *cond->addr = inet->in.sin_addr.s_addr; - } - break; - case AF_INET6: { - cond->port = ntohs(inet->in6.sin6_port); - cond->prefix_len = memcmp(&in6addr_any, &inet->in6.sin6_addr, - sizeof(struct in6_addr)) == 0 ? - 0 : sizeof(inet->in6.sin6_addr) * CHAR_BIT; - memcpy(&cond->addr, &inet->in6.sin6_addr, - sizeof(struct in6_addr)); - } - break; - default: - assert(0 && "unsupported address family, could that be IPv7?!"); - } -} - -static void nl_errcheck(VALUE r) -{ - const char *err = (const char *)r; - - if (err) { - if (err == err_nlmsg) - rb_raise(rb_eRuntimeError, "NLMSG_ERROR"); - else - rb_sys_fail(err); - } -} - -static VALUE tcp_stats(struct nogvl_args *args, VALUE addr) -{ - union any_addr query_addr; - - parse_addr(&query_addr, addr); - gen_bytecode(&args->iov[2], &query_addr); - - memset(&args->stats, 0, sizeof(struct listen_stats)); - nl_errcheck(rb_thread_io_blocking_region(diag, args, args->fd)); - - return rb_listen_stats(&args->stats); -} - -/* - * call-seq: - * Raindrops::Linux.tcp_listener_stats([addrs[, sock]]) => hash - * - * If specified, +addr+ may be a string or array of strings representing - * listen addresses to filter for. Returns a hash with given addresses as - * keys and ListenStats objects as the values or a hash of all addresses. - * - * addrs = %w(0.0.0.0:80 127.0.0.1:8080) - * - * If +addr+ is nil or not specified, all (IPv4) addresses are returned. - * If +sock+ is specified, it should be a Raindrops::InetDiagSock object. - */ -static VALUE tcp_listener_stats(int argc, VALUE *argv, VALUE self) -{ - VALUE rv = rb_hash_new(); - struct nogvl_args args; - VALUE addrs, sock; - - rb_scan_args(argc, argv, "02", &addrs, &sock); - - /* - * allocating page_size instead of OP_LEN since we'll reuse the - * buffer for recvmsg() later, we already checked for - * OPLEN <= page_size at initialization - */ - args.iov[2].iov_len = OPLEN; - args.iov[2].iov_base = alloca(page_size); - args.table = NULL; - if (NIL_P(sock)) - sock = rb_funcall(cIDSock, id_new, 0); - args.fd = my_fileno(sock); - - switch (TYPE(addrs)) { - case T_STRING: - rb_hash_aset(rv, addrs, tcp_stats(&args, addrs)); - return rv; - case T_ARRAY: { - long i; - long len = RARRAY_LEN(addrs); - VALUE cur; - - if (len == 1) { - cur = rb_ary_entry(addrs, 0); - - rb_hash_aset(rv, cur, tcp_stats(&args, cur)); - return rv; - } - for (i = 0; i < len; i++) { - union any_addr check; - VALUE cur = rb_ary_entry(addrs, i); - - parse_addr(&check, cur); - rb_hash_aset(rv, cur, Qtrue); - } - /* fall through */ - } - case T_NIL: - args.table = st_init_strtable(); - gen_bytecode_all(&args.iov[2]); - break; - default: - rb_raise(rb_eArgError, - "addr must be an array of strings, a string, or nil"); - } - - nl_errcheck(rb_thread_io_blocking_region(diag, &args, args.fd)); - - st_foreach(args.table, NIL_P(addrs) ? st_to_hash : st_AND_hash, rv); - st_free_table(args.table); - - /* let GC deal with corner cases */ - if (argc < 2) rb_io_close(sock); - return rv; -} - -void Init_raindrops_linux_inet_diag(void) -{ - VALUE cRaindrops = rb_const_get(rb_cObject, rb_intern("Raindrops")); - VALUE mLinux = rb_define_module_under(cRaindrops, "Linux"); - - rb_require("socket"); - cIDSock = rb_const_get(rb_cObject, rb_intern("Socket")); - id_new = rb_intern("new"); - - /* - * Document-class: Raindrops::InetDiagSocket - * - * This is a subclass of +Socket+ specifically for talking - * to the inet_diag facility of Netlink. - */ - cIDSock = rb_define_class_under(cRaindrops, "InetDiagSocket", cIDSock); - rb_define_singleton_method(cIDSock, "new", ids_s_new, 0); - - cListenStats = rb_const_get(cRaindrops, rb_intern("ListenStats")); - - rb_define_module_function(mLinux, "tcp_listener_stats", - tcp_listener_stats, -1); - - page_size = getpagesize(); - - assert(OPLEN <= page_size && "bytecode OPLEN is not <= PAGE_SIZE"); -} -#endif /* __linux__ */ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/linux_tcp_info.c b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/linux_tcp_info.c deleted file mode 100644 index dcdb153..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/linux_tcp_info.c +++ /dev/null @@ -1,173 +0,0 @@ -#ifdef __linux__ -#include -#include -#include -#include -#ifdef TCP_INFO -#include "my_fileno.h" - -#define TCPI_ATTR_READER(x) \ -static VALUE tcp_info_##x(VALUE self) \ -{ \ - struct tcp_info *info = DATA_PTR(self); \ - return UINT2NUM((uint32_t)info->tcpi_##x); \ -} - -TCPI_ATTR_READER(state) -TCPI_ATTR_READER(ca_state) -TCPI_ATTR_READER(retransmits) -TCPI_ATTR_READER(probes) -TCPI_ATTR_READER(backoff) -TCPI_ATTR_READER(options) -TCPI_ATTR_READER(snd_wscale) -TCPI_ATTR_READER(rcv_wscale) -TCPI_ATTR_READER(rto) -TCPI_ATTR_READER(ato) -TCPI_ATTR_READER(snd_mss) -TCPI_ATTR_READER(rcv_mss) -TCPI_ATTR_READER(unacked) -TCPI_ATTR_READER(sacked) -TCPI_ATTR_READER(lost) -TCPI_ATTR_READER(retrans) -TCPI_ATTR_READER(fackets) -TCPI_ATTR_READER(last_data_sent) -TCPI_ATTR_READER(last_ack_sent) -TCPI_ATTR_READER(last_data_recv) -TCPI_ATTR_READER(last_ack_recv) -TCPI_ATTR_READER(pmtu) -TCPI_ATTR_READER(rcv_ssthresh) -TCPI_ATTR_READER(rtt) -TCPI_ATTR_READER(rttvar) -TCPI_ATTR_READER(snd_ssthresh) -TCPI_ATTR_READER(snd_cwnd) -TCPI_ATTR_READER(advmss) -TCPI_ATTR_READER(reordering) -TCPI_ATTR_READER(rcv_rtt) -TCPI_ATTR_READER(rcv_space) -TCPI_ATTR_READER(total_retrans) - -static VALUE alloc(VALUE klass) -{ - struct tcp_info *info = xmalloc(sizeof(struct tcp_info)); - - /* Data_Make_Struct has an extra memset 0 which is so wasteful */ - return Data_Wrap_Struct(klass, NULL, -1, info); -} - -/* - * call-seq: - * - * Raindrops::TCP_Info.new(tcp_socket) -> TCP_Info object - * - * Reads a TCP_Info object from any given +tcp_socket+. See the tcp(7) - * manpage and /usr/include/linux/tcp.h for more details. - */ -static VALUE init(VALUE self, VALUE io) -{ - int fd = my_fileno(io); - struct tcp_info *info = DATA_PTR(self); - socklen_t len = (socklen_t)sizeof(struct tcp_info); - int rc = getsockopt(fd, IPPROTO_TCP, TCP_INFO, info, &len); - - if (rc != 0) - rb_sys_fail("getsockopt"); - - return self; -} - -void Init_raindrops_linux_tcp_info(void) -{ - VALUE cRaindrops = rb_const_get(rb_cObject, rb_intern("Raindrops")); - VALUE cTCP_Info; - - /* - * Document-class: Raindrops::TCP_Info - * - * This is used to wrap "struct tcp_info" as described in tcp(7) - * and /usr/include/linux/tcp.h. The following readers methods - * are defined corresponding to the "tcpi_" fields in the - * tcp_info struct. - * - * In particular, the +last_data_recv+ field is useful for measuring - * the amount of time a client spent in the listen queue before - * +accept()+, but only if +TCP_DEFER_ACCEPT+ is used with the - * listen socket (it is on by default in Unicorn). - * - * - state - * - ca_state - * - retransmits - * - probes - * - backoff - * - options - * - snd_wscale - * - rcv_wscale - * - rto - * - ato - * - snd_mss - * - rcv_mss - * - unacked - * - sacked - * - lost - * - retrans - * - fackets - * - last_data_sent - * - last_ack_sent - * - last_data_recv - * - last_ack_recv - * - pmtu - * - rcv_ssthresh - * - rtt - * - rttvar - * - snd_ssthresh - * - snd_cwnd - * - advmss - * - reordering - * - rcv_rtt - * - rcv_space - * - total_retrans - * - * http://kernel.org/doc/man-pages/online/pages/man7/tcp.7.html - */ - cTCP_Info = rb_define_class_under(cRaindrops, "TCP_Info", rb_cObject); - rb_define_alloc_func(cTCP_Info, alloc); - rb_define_private_method(cTCP_Info, "initialize", init, 1); - rb_define_method(cTCP_Info, "get!", init, 1); - -#define TCPI_DEFINE_METHOD(x) \ - rb_define_method(cTCP_Info, #x, tcp_info_##x, 0) - - TCPI_DEFINE_METHOD(state); - TCPI_DEFINE_METHOD(ca_state); - TCPI_DEFINE_METHOD(retransmits); - TCPI_DEFINE_METHOD(probes); - TCPI_DEFINE_METHOD(backoff); - TCPI_DEFINE_METHOD(options); - TCPI_DEFINE_METHOD(snd_wscale); - TCPI_DEFINE_METHOD(rcv_wscale); - TCPI_DEFINE_METHOD(rto); - TCPI_DEFINE_METHOD(ato); - TCPI_DEFINE_METHOD(snd_mss); - TCPI_DEFINE_METHOD(rcv_mss); - TCPI_DEFINE_METHOD(unacked); - TCPI_DEFINE_METHOD(sacked); - TCPI_DEFINE_METHOD(lost); - TCPI_DEFINE_METHOD(retrans); - TCPI_DEFINE_METHOD(fackets); - TCPI_DEFINE_METHOD(last_data_sent); - TCPI_DEFINE_METHOD(last_ack_sent); - TCPI_DEFINE_METHOD(last_data_recv); - TCPI_DEFINE_METHOD(last_ack_recv); - TCPI_DEFINE_METHOD(pmtu); - TCPI_DEFINE_METHOD(rcv_ssthresh); - TCPI_DEFINE_METHOD(rtt); - TCPI_DEFINE_METHOD(rttvar); - TCPI_DEFINE_METHOD(snd_ssthresh); - TCPI_DEFINE_METHOD(snd_cwnd); - TCPI_DEFINE_METHOD(advmss); - TCPI_DEFINE_METHOD(reordering); - TCPI_DEFINE_METHOD(rcv_rtt); - TCPI_DEFINE_METHOD(rcv_space); - TCPI_DEFINE_METHOD(total_retrans); -} -#endif /* TCP_INFO */ -#endif /* __linux__ */ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/my_fileno.h b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/my_fileno.h deleted file mode 100644 index bdf1a5f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/my_fileno.h +++ /dev/null @@ -1,36 +0,0 @@ -#include -#ifdef HAVE_RUBY_IO_H -# include -#else -# include -# include -#endif - -#if ! HAVE_RB_IO_T -# define rb_io_t OpenFile -#endif - -#ifdef GetReadFile -# define FPTR_TO_FD(fptr) (fileno(GetReadFile(fptr))) -#else -# if !HAVE_RB_IO_T || (RUBY_VERSION_MAJOR == 1 && RUBY_VERSION_MINOR == 8) -# define FPTR_TO_FD(fptr) fileno(fptr->f) -# else -# define FPTR_TO_FD(fptr) fptr->fd -# endif -#endif - -static int my_fileno(VALUE io) -{ - rb_io_t *fptr; - int fd; - - if (TYPE(io) != T_FILE) - io = rb_convert_type(io, T_FILE, "IO", "to_io"); - GetOpenFile(io, fptr); - fd = FPTR_TO_FD(fptr); - - if (fd < 0) - rb_raise(rb_eIOError, "closed stream"); - return fd; -} diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops.c b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops.c deleted file mode 100644 index 65c16e7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops.c +++ /dev/null @@ -1,433 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "raindrops_atomic.h" - -#ifndef SIZET2NUM -# define SIZET2NUM(x) ULONG2NUM(x) -#endif -#ifndef NUM2SIZET -# define NUM2SIZET(x) NUM2ULONG(x) -#endif - -/* - * most modern CPUs have a cache-line size of 64 or 128. - * We choose a bigger one by default since our structure is not - * heavily used - */ -static size_t raindrop_size = 128; -static size_t rd_page_size; - -#define PAGE_MASK (~(rd_page_size - 1)) -#define PAGE_ALIGN(addr) (((addr) + rd_page_size - 1) & PAGE_MASK) - -/* each raindrop is a counter */ -struct raindrop { - unsigned long counter; -} __attribute__((packed)); - -/* allow mmap-ed regions to store more than one raindrop */ -struct raindrops { - size_t size; - size_t capa; - pid_t pid; - struct raindrop *drops; -}; - -/* called by GC */ -static void gcfree(void *ptr) -{ - struct raindrops *r = ptr; - - if (r->drops != MAP_FAILED) { - int rv = munmap(r->drops, raindrop_size * r->capa); - if (rv != 0) - rb_bug("munmap failed in gc: %s", strerror(errno)); - } - - xfree(ptr); -} - -/* automatically called at creation (before initialize) */ -static VALUE alloc(VALUE klass) -{ - struct raindrops *r; - VALUE rv = Data_Make_Struct(klass, struct raindrops, NULL, gcfree, r); - - r->drops = MAP_FAILED; - return rv; -} - -static struct raindrops *get(VALUE self) -{ - struct raindrops *r; - - Data_Get_Struct(self, struct raindrops, r); - - if (r->drops == MAP_FAILED) - rb_raise(rb_eStandardError, "invalid or freed Raindrops"); - - return r; -} - -/* - * call-seq: - * Raindrops.new(size) -> raindrops object - * - * Initializes a Raindrops object to hold +size+ counters. +size+ is - * only a hint and the actual number of counters the object has is - * dependent on the CPU model, number of cores, and page size of - * the machine. The actual size of the object will always be equal - * or greater than the specified +size+. - */ -static VALUE init(VALUE self, VALUE size) -{ - struct raindrops *r = DATA_PTR(self); - int tries = 1; - size_t tmp; - - if (r->drops != MAP_FAILED) - rb_raise(rb_eRuntimeError, "already initialized"); - - r->size = NUM2SIZET(size); - if (r->size < 1) - rb_raise(rb_eArgError, "size must be >= 1"); - - tmp = PAGE_ALIGN(raindrop_size * r->size); - r->capa = tmp / raindrop_size; - assert(PAGE_ALIGN(raindrop_size * r->capa) == tmp && "not aligned"); - -retry: - r->drops = mmap(NULL, tmp, - PROT_READ|PROT_WRITE, MAP_ANON|MAP_SHARED, -1, 0); - if (r->drops == MAP_FAILED) { - if ((errno == EAGAIN || errno == ENOMEM) && tries-- > 0) { - rb_gc(); - goto retry; - } - rb_sys_fail("mmap"); - } - r->pid = getpid(); - - return self; -} - -/* - * mremap() is currently broken with MAP_SHARED - * https://bugzilla.kernel.org/show_bug.cgi?id=8691 - */ -#if defined(HAVE_MREMAP) && !defined(MREMAP_WORKS_WITH_MAP_SHARED) -# undef HAVE_MREMAP -#endif - -#ifdef HAVE_MREMAP -#ifndef MREMAP_MAYMOVE -# warn MREMAP_MAYMOVE undefined -# define MREMAP_MAYMOVE 0 -#endif -static void resize(struct raindrops *r, size_t new_rd_size) -{ - size_t old_size = raindrop_size * r->capa; - size_t new_size = PAGE_ALIGN(raindrop_size * new_rd_size); - void *old_address = r->drops; - void *rv; - - if (r->pid != getpid()) - rb_raise(rb_eRuntimeError, "cannot mremap() from child"); - - rv = mremap(old_address, old_size, new_size, MREMAP_MAYMOVE); - if (rv == MAP_FAILED) { - if (errno == EAGAIN || errno == ENOMEM) { - rb_gc(); - rv = mremap(old_address, old_size, new_size, 0); - } - if (rv == MAP_FAILED) - rb_sys_fail("mremap"); - } - r->drops = rv; - r->size = new_rd_size; - r->capa = new_size / raindrop_size; - assert(r->capa >= r->size && "bad sizing"); -} -#else /* ! HAVE_MREMAP */ -/* - * we cannot use munmap + mmap to reallocate the buffer since it may - * already be shared by other processes, so we just fail - */ -static void resize(struct raindrops *r, size_t new_rd_size) -{ - rb_raise(rb_eRangeError, "mremap(2) is not available"); -} -#endif /* ! HAVE_MREMAP */ - -/* - * call-seq: - * rd.size = new_size - * - * Increases or decreases the current capacity of our Raindrop. - * Raises RangeError if +new_size+ is too big or small for the - * current backing store - */ -static VALUE setsize(VALUE self, VALUE new_size) -{ - size_t new_rd_size = NUM2SIZET(new_size); - struct raindrops *r = get(self); - - if (new_rd_size <= r->capa) - r->size = new_rd_size; - else - resize(r, new_rd_size); - - return new_size; -} - -/* - * call-seq: - * rd.capa -> Integer - * - * Returns the number of slots allocated (but not necessarily used) by - * the Raindrops object. - */ -static VALUE capa(VALUE self) -{ - return SIZET2NUM(get(self)->capa); -} - -/* - * call-seq: - * rd.dup -> rd_copy - * - * Duplicates and snapshots the current state of a Raindrops object. - */ -static VALUE init_copy(VALUE dest, VALUE source) -{ - struct raindrops *dst = DATA_PTR(dest); - struct raindrops *src = get(source); - - init(dest, SIZET2NUM(src->size)); - memcpy(dst->drops, src->drops, raindrop_size * src->size); - - return dest; -} - -static unsigned long *addr_of(VALUE self, VALUE index) -{ - struct raindrops *r = get(self); - unsigned long off = FIX2ULONG(index) * raindrop_size; - - if (off >= raindrop_size * r->size) - rb_raise(rb_eArgError, "offset overrun"); - - return (unsigned long *)((unsigned long)r->drops + off); -} - -static unsigned long incr_decr_arg(int argc, const VALUE *argv) -{ - if (argc > 2 || argc < 1) - rb_raise(rb_eArgError, - "wrong number of arguments (%d for 1+)", argc); - - return argc == 2 ? NUM2ULONG(argv[1]) : 1; -} - -/* - * call-seq: - * rd.incr(index[, number]) -> result - * - * Increments the value referred to by the +index+ by +number+. - * +number+ defaults to +1+ if unspecified. - */ -static VALUE incr(int argc, VALUE *argv, VALUE self) -{ - unsigned long nr = incr_decr_arg(argc, argv); - - return ULONG2NUM(__sync_add_and_fetch(addr_of(self, argv[0]), nr)); -} - -/* - * call-seq: - * rd.decr(index[, number]) -> result - * - * Decrements the value referred to by the +index+ by +number+. - * +number+ defaults to +1+ if unspecified. - */ -static VALUE decr(int argc, VALUE *argv, VALUE self) -{ - unsigned long nr = incr_decr_arg(argc, argv); - - return ULONG2NUM(__sync_sub_and_fetch(addr_of(self, argv[0]), nr)); -} - -/* - * call-seq: - * rd.to_ary -> Array - * - * converts the Raindrops structure to an Array - */ -static VALUE to_ary(VALUE self) -{ - struct raindrops *r = get(self); - VALUE rv = rb_ary_new2(r->size); - size_t i; - unsigned long base = (unsigned long)r->drops; - - for (i = 0; i < r->size; i++) { - rb_ary_push(rv, ULONG2NUM(*((unsigned long *)base))); - base += raindrop_size; - } - - return rv; -} - -/* - * call-seq: - * rd.size -> Integer - * - * Returns the number of counters a Raindrops object can hold. Due to - * page alignment, this is always equal or greater than the number of - * requested slots passed to Raindrops.new - */ -static VALUE size(VALUE self) -{ - return SIZET2NUM(get(self)->size); -} - -/* - * call-seq: - * rd[index] = value - * - * Assigns +value+ to the slot designated by +index+ - */ -static VALUE aset(VALUE self, VALUE index, VALUE value) -{ - unsigned long *addr = addr_of(self, index); - - *addr = NUM2ULONG(value); - - return value; -} - -/* - * call-seq: - * rd[index] -> value - * - * Returns the value of the slot designated by +index+ - */ -static VALUE aref(VALUE self, VALUE index) -{ - return ULONG2NUM(*addr_of(self, index)); -} - -#ifdef __linux__ -void Init_raindrops_linux_inet_diag(void); -void Init_raindrops_linux_tcp_info(void); -#endif - -#ifndef _SC_NPROCESSORS_CONF -# if defined _SC_NPROCESSORS_ONLN -# define _SC_NPROCESSORS_CONF _SC_NPROCESSORS_ONLN -# elif defined _SC_NPROC_ONLN -# define _SC_NPROCESSORS_CONF _SC_NPROC_ONLN -# elif defined _SC_CRAY_NCPU -# define _SC_NPROCESSORS_CONF _SC_CRAY_NCPU -# endif -#endif - -/* - * call-seq: - * rd.evaporate! -> nil - * - * Releases mmap()-ed memory allocated for the Raindrops object back - * to the OS. The Ruby garbage collector will also release memory - * automatically when it is not needed, but this forces release - * under high memory pressure. - */ -static VALUE evaporate_bang(VALUE self) -{ - struct raindrops *r = get(self); - void *addr = r->drops; - - r->drops = MAP_FAILED; - if (munmap(addr, raindrop_size * r->capa) != 0) - rb_sys_fail("munmap"); - return Qnil; -} - -void Init_raindrops_ext(void) -{ - VALUE cRaindrops = rb_define_class("Raindrops", rb_cObject); - long tmp = 2; - -#ifdef _SC_NPROCESSORS_CONF - tmp = sysconf(_SC_NPROCESSORS_CONF); -#endif - /* no point in padding on single CPU machines */ - if (tmp == 1) - raindrop_size = sizeof(unsigned long); -#ifdef _SC_LEVEL1_DCACHE_LINESIZE - if (tmp != 1) { - tmp = sysconf(_SC_LEVEL1_DCACHE_LINESIZE); - if (tmp > 0) - raindrop_size = (size_t)tmp; - } -#endif -#if defined(_SC_PAGE_SIZE) - rd_page_size = (size_t)sysconf(_SC_PAGE_SIZE); -#elif defined(_SC_PAGESIZE) - rd_page_size = (size_t)sysconf(_SC_PAGESIZE); -#elif defined(HAVE_GETPAGESIZE) - rd_page_size = (size_t)getpagesize(); -#elif defined(PAGE_SIZE) - rd_page_size = (size_t)PAGE_SIZE; -#elif defined(PAGESIZE) - rd_page_size = (size_t)PAGESIZE; -#else -# error unable to detect page size for mmap() -#endif - if ((rd_page_size == (size_t)-1) || (rd_page_size < raindrop_size)) - rb_raise(rb_eRuntimeError, - "system page size invalid: %llu", - (unsigned long long)rd_page_size); - - /* - * The size of one page of memory for a mmap()-ed Raindrops region. - * Typically 4096 bytes under Linux. - */ - rb_define_const(cRaindrops, "PAGE_SIZE", SIZET2NUM(rd_page_size)); - - /* - * The size (in bytes) of a slot in a Raindrops object. - * This is the size of a word on single CPU systems and - * the size of the L1 cache line size if detectable. - * - * Defaults to 128 bytes if undetectable. - */ - rb_define_const(cRaindrops, "SIZE", SIZET2NUM(raindrop_size)); - - /* - * The maximum value a raindrop counter can hold - */ - rb_define_const(cRaindrops, "MAX", ULONG2NUM((unsigned long)-1)); - - rb_define_alloc_func(cRaindrops, alloc); - - rb_define_method(cRaindrops, "initialize", init, 1); - rb_define_method(cRaindrops, "incr", incr, -1); - rb_define_method(cRaindrops, "decr", decr, -1); - rb_define_method(cRaindrops, "to_ary", to_ary, 0); - rb_define_method(cRaindrops, "[]", aref, 1); - rb_define_method(cRaindrops, "[]=", aset, 2); - rb_define_method(cRaindrops, "size", size, 0); - rb_define_method(cRaindrops, "size=", setsize, 1); - rb_define_method(cRaindrops, "capa", capa, 0); - rb_define_method(cRaindrops, "initialize_copy", init_copy, 1); - rb_define_method(cRaindrops, "evaporate!", evaporate_bang, 0); - -#ifdef __linux__ - Init_raindrops_linux_inet_diag(); - Init_raindrops_linux_tcp_info(); -#endif -} diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops_atomic.h b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops_atomic.h deleted file mode 100644 index fd5f23b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops_atomic.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * use wrappers around libatomic-ops for folks that don't have GCC - * or a new enough version of GCC - */ -#ifndef HAVE_GCC_ATOMIC_BUILTINS -#include - -static inline unsigned long -__sync_add_and_fetch(unsigned long *dst, unsigned long incr) -{ - AO_t tmp = AO_fetch_and_add((AO_t *)dst, (AO_t)incr); - - return (unsigned long)tmp + incr; -} - -static inline unsigned long -__sync_sub_and_fetch(unsigned long *dst, unsigned long incr) -{ - AO_t tmp = AO_fetch_and_add((AO_t *)dst, (AO_t)(-(long)incr)); - - return (unsigned long)tmp - incr; -} -#endif /* HAVE_GCC_ATOMIC_BUILTINS */ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops_ext.bundle b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops_ext.bundle deleted file mode 100755 index 014de41..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/ext/raindrops/raindrops_ext.bundle and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops.rb deleted file mode 100644 index 7acde22..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops.rb +++ /dev/null @@ -1,48 +0,0 @@ -# -*- encoding: binary -*- -# -# Each Raindrops object is a container that holds several counters. -# It is internally a page-aligned, shared memory area that allows -# atomic increments, decrements, assignments and reads without any -# locking. -# -# rd = Raindrops.new 4 -# rd.incr(0, 1) -> 1 -# rd.to_ary -> [ 1, 0, 0, 0 ] -# -# Unlike many classes in this package, the core Raindrops class is -# intended to be portable to all reasonably modern *nix systems -# supporting mmap(). Please let us know if you have portability -# issues, patches or pull requests at mailto:raindrops@librelist.org -class Raindrops - - # Used to represent the number of +active+ and +queued+ sockets for - # a single listen socket across all threads and processes on a - # machine. - # - # For TCP listeners, only sockets in the TCP_ESTABLISHED state are - # accounted for. For Unix domain listeners, only CONNECTING and - # CONNECTED Unix domain sockets are accounted for. - # - # +active+ connections is the number of accept()-ed but not-yet-closed - # sockets in all threads/processes sharing the given listener. - # - # +queued+ connections is the number of un-accept()-ed sockets in the - # queue of a given listen socket. - # - # These stats are currently only available under \Linux - class ListenStats < Struct.new(:active, :queued) - - # the sum of +active+ and +queued+ sockets - def total - active + queued - end - end - - autoload :Linux, 'raindrops/linux' - autoload :Struct, 'raindrops/struct' - autoload :Middleware, 'raindrops/middleware' - autoload :Aggregate, 'raindrops/aggregate' - autoload :LastDataRecv, 'raindrops/last_data_recv' - autoload :Watcher, 'raindrops/watcher' -end -require 'raindrops_ext' diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate.rb deleted file mode 100644 index 998d514..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate.rb +++ /dev/null @@ -1,8 +0,0 @@ -# -*- encoding: binary -*- -# -# raindrops may use the {aggregate}[http://github.com/josephruscio/aggregate] -# RubyGem to aggregate statistics from TCP_Info lookups. -module Raindrops::Aggregate - autoload :PMQ, "raindrops/aggregate/pmq" - autoload :LastDataRecv, "raindrops/aggregate/last_data_recv" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate/last_data_recv.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate/last_data_recv.rb deleted file mode 100644 index eca89a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate/last_data_recv.rb +++ /dev/null @@ -1,87 +0,0 @@ -# -*- encoding: binary -*- -require "socket" -# -# -# This module is used to extend TCPServer and Kgio::TCPServer objects -# and aggregate +last_data_recv+ times for all accepted clients. It -# is designed to be used with Raindrops::LastDataRecv Rack application -# but can be easily changed to work with other stats collection devices. -# -# Methods wrapped include: -# - TCPServer#accept -# - TCPServer#accept_nonblock -# - Kgio::TCPServer#kgio_accept -# - Kgio::TCPServer#kgio_tryaccept -module Raindrops::Aggregate::LastDataRecv - # :stopdoc: - TCP_Info = Raindrops::TCP_Info - # :startdoc: - - # The integer value of +last_data_recv+ is sent to this object. - # This is usually a duck type compatible with the \Aggregate class, - # but can be *anything* that accepts the *<<* method. - attr_accessor :raindrops_aggregate - - @@default_aggregate = nil - - # By default, this is a Raindrops::Aggregate::PMQ object - # It may be anything that responds to *<<* - def self.default_aggregate - @@default_aggregate ||= Raindrops::Aggregate::PMQ.new - end - - # Assign any object that responds to *<<* - def self.default_aggregate=(agg) - @@default_aggregate = agg - end - - # automatically extends any TCPServer objects used by Unicorn - def self.cornify! - Unicorn::HttpServer::LISTENERS.each do |sock| - sock.extend(self) if TCPServer === sock - end - end - - # each extended object needs to have TCP_DEFER_ACCEPT enabled - # for accuracy. - def self.extended(obj) - obj.raindrops_aggregate = default_aggregate - # obj.setsockopt Socket::SOL_TCP, tcp_defer_accept = 9, seconds = 60 - obj.setsockopt Socket::SOL_TCP, 9, 60 - end - - # :stopdoc: - - def kgio_tryaccept(*args) - count! super - end - - def kgio_accept(*args) - count! super - end - - def accept - count! super - end - - def accept_nonblock - count! super - end - - # :startdoc: - - # The +last_data_recv+ member of Raindrops::TCP_Info can be used to - # infer the time a client spent in the listen queue before it was - # accepted. - # - # We require TCP_DEFER_ACCEPT on the listen socket for - # +last_data_recv+ to be accurate - def count!(io) - if io - x = TCP_Info.new(io) - @raindrops_aggregate << x.last_data_recv - end - io - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate/pmq.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate/pmq.rb deleted file mode 100644 index a2dd45e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/aggregate/pmq.rb +++ /dev/null @@ -1,239 +0,0 @@ -# -*- encoding: binary -*- -require "tempfile" -require "aggregate" -require "posix_mq" -require "fcntl" -require "io/extra" -require "thread" - -# \Aggregate + POSIX message queues support for Ruby 1.9 and \Linux -# -# This class is duck-type compatible with \Aggregate and allows us to -# aggregate and share statistics from multiple processes/threads aided -# POSIX message queues. This is designed to be used with the -# Raindrops::LastDataRecv Rack application, but can be used independently -# on compatible Runtimes. -# -# Unlike the core of raindrops, this is only supported on Ruby 1.9 and -# Linux 2.6. Using this class requires the following additional RubyGems -# or libraries: -# -# * aggregate (tested with 0.2.2) -# * io-extra (tested with 1.2.3) -# * posix_mq (tested with 1.0.0) -# -# == Design -# -# There is one master thread which aggregates statistics. Individual -# worker processes or threads will write to a shared POSIX message -# queue (default: "/raindrops") that the master reads from. At a -# predefined interval, the master thread will write out to a shared, -# anonymous temporary file that workers may read from -# -# Setting +:worker_interval+ and +:master_interval+ to +1+ will result -# in perfect accuracy but at the cost of a high synchronization -# overhead. Larger intervals mean less frequent messaging for higher -# performance but lower accuracy. -class Raindrops::Aggregate::PMQ - - # :stopdoc: - # These constants are for Linux. This is designed for aggregating - # TCP_INFO. - RDLOCK = [ Fcntl::F_RDLCK ].pack("s @256") - WRLOCK = [ Fcntl::F_WRLCK ].pack("s @256") - UNLOCK = [ Fcntl::F_UNLCK ].pack("s @256") - # :startdoc: - - # returns the number of dropped messages sent to a POSIX message - # queue if non-blocking operation was desired with :lossy - attr_reader :nr_dropped - - # - # Creates a new Raindrops::Aggregate::PMQ object - # - # Raindrops::Aggregate::PMQ.new(options = {}) -> aggregate - # - # +options+ is a hash that accepts the following keys: - # - # * :queue - name of the POSIX message queue (default: "/raindrops") - # * :worker_interval - interval to send to the master (default: 10) - # * :master_interval - interval to for the master to write out (default: 5) - # * :lossy - workers drop packets if master cannot keep up (default: false) - # * :aggregate - \Aggregate object (default: \Aggregate.new) - # * :mq_umask - umask for creatingthe POSIX message queue (default: 0666) - # - def initialize(params = {}) - opts = { - :queue => ENV["RAINDROPS_MQUEUE"] || "/raindrops", - :worker_interval => 10, - :master_interval => 5, - :lossy => false, - :mq_attr => nil, - :mq_umask => 0666, - :aggregate => Aggregate.new, - }.merge! params - @master_interval = opts[:master_interval] - @worker_interval = opts[:worker_interval] - @aggregate = opts[:aggregate] - @worker_queue = @worker_interval ? [] : nil - @mutex = Mutex.new - - @mq_name = opts[:queue] - mq = POSIX_MQ.new @mq_name, :w, opts[:mq_umask], opts[:mq_attr] - Tempfile.open("raindrops_pmq") do |t| - @wr = File.open(t.path, "wb") - @rd = File.open(t.path, "rb") - end - @cached_aggregate = @aggregate - flush_master - @mq_send = if opts[:lossy] - @nr_dropped = 0 - mq.nonblock = true - mq.method :trysend - else - mq.method :send - end - end - - # adds a sample to the underlying \Aggregate object - def << val - if q = @worker_queue - q << val - if q.size >= @worker_interval - mq_send(q) or @nr_dropped += 1 - q.clear - end - else - mq_send(val) or @nr_dropped += 1 - end - end - - def mq_send(val) # :nodoc: - @cached_aggregate = nil - @mq_send.call Marshal.dump(val) - end - - # - # Starts running a master loop, usually in a dedicated thread or process: - # - # Thread.new { agg.master_loop } - # - # Any worker can call +agg.stop_master_loop+ to stop the master loop - # (possibly causing the thread or process to exit) - def master_loop - buf = "" - a = @aggregate - nr = 0 - mq = POSIX_MQ.new @mq_name, :r # this one is always blocking - begin - if (nr -= 1) < 0 - nr = @master_interval - flush_master - end - mq.shift(buf) - data = begin - Marshal.load(buf) or return - rescue ArgumentError, TypeError - next - end - Array === data ? data.each { |x| a << x } : a << data - rescue Errno::EINTR - rescue => e - warn "Unhandled exception in #{__FILE__}:#{__LINE__}: #{e}" - break - end while true - ensure - flush_master - end - - # Loads the last shared \Aggregate from the master thread/process - def aggregate - @cached_aggregate ||= begin - flush - Marshal.load(synchronize(@rd, RDLOCK) do |rd| - IO.pread rd.fileno, rd.stat.size, 0 - end) - end - end - - # Flushes the currently aggregate statistics to a temporary file. - # There is no need to call this explicitly as +:worker_interval+ defines - # how frequently your data will be flushed for workers to read. - def flush_master - dump = Marshal.dump @aggregate - synchronize(@wr, WRLOCK) do |wr| - wr.truncate 0 - IO.pwrite wr.fileno, dump, 0 - end - end - - # stops the currently running master loop, may be called from any - # worker thread or process - def stop_master_loop - sleep 0.1 until mq_send(false) - rescue Errno::EINTR - retry - end - - def lock! io, type # :nodoc: - io.fcntl Fcntl::F_SETLKW, type - rescue Errno::EINTR - retry - end - - # we use both a mutex for thread-safety and fcntl lock for process-safety - def synchronize io, type # :nodoc: - @mutex.synchronize do - begin - lock! io, type - yield io - ensure - lock! io, UNLOCK - end - end - end - - # flushes the local queue of the worker process, sending all pending - # data to the master. There is no need to call this explicitly as - # +:worker_interval+ defines how frequently your queue will be flushed - def flush - if q = @local_queue && ! q.empty? - mq_send q - q.clear - end - nil - end - - # proxy for \Aggregate#count - def count; aggregate.count; end - - # proxy for \Aggregate#max - def max; aggregate.max; end - - # proxy for \Aggregate#min - def min; aggregate.min; end - - # proxy for \Aggregate#sum - def sum; aggregate.sum; end - - # proxy for \Aggregate#mean - def mean; aggregate.mean; end - - # proxy for \Aggregate#std_dev - def std_dev; aggregate.std_dev; end - - # proxy for \Aggregate#outliers_low - def outliers_low; aggregate.outliers_low; end - - # proxy for \Aggregate#outliers_high - def outliers_high; aggregate.outliers_high; end - - # proxy for \Aggregate#to_s - def to_s(*args); aggregate.to_s(*args); end - - # proxy for \Aggregate#each - def each; aggregate.each { |*args| yield(*args) }; end - - # proxy for \Aggregate#each_nonzero - def each_nonzero; aggregate.each_nonzero { |*args| yield(*args) }; end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/last_data_recv.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/last_data_recv.rb deleted file mode 100644 index b4808a1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/last_data_recv.rb +++ /dev/null @@ -1,102 +0,0 @@ -# -*- encoding: binary -*- -require "raindrops" - -# This is highly experimental! -# -# A self-contained Rack application for aggregating in the -# +tcpi_last_data_recv+ field in +struct+ +tcp_info+ defined in -# +/usr/include/linux/tcp.h+. This is only useful for \Linux 2.6 and later. -# This primarily supports Unicorn and derived servers, but may also be -# used with any Ruby web server using the core TCPServer class in Ruby. -# -# Hitting the Rack endpoint configured for this application will return -# a an ASCII histogram response body with the following headers: -# -# - X-Count - number of requests received -# -# The following headers are only present if X-Count is greater than one. -# -# - X-Min - lowest last_data_recv time recorded (in milliseconds) -# - X-Max - highest last_data_recv time recorded (in milliseconds) -# - X-Mean - mean last_data_recv time recorded (rounded, in milliseconds) -# - X-Std-Dev - standard deviation of last_data_recv times -# - X-Outliers-Low - number of low outliers (hopefully many!) -# - X-Outliers-High - number of high outliers (hopefully zero!) -# -# == To use with Unicorn and derived servers (preload_app=false): -# -# Put the following in our Unicorn config file (not config.ru): -# -# require "raindrops/last_data_recv" -# -# Then follow the instructions below for config.ru: -# -# == To use with any Rack server using TCPServer -# -# Setup a route for Raindrops::LastDataRecv in your Rackup config file -# (typically config.ru): -# -# require "raindrops" -# map "/raindrops/last_data_recv" do -# run Raindrops::LastDataRecv.new -# end -# map "/" do -# use SomeMiddleware -# use MoreMiddleware -# # ... -# run YourAppHere.new -# end -# -# == To use with any other Ruby web server that uses TCPServer -# -# Put the following in any piece of Ruby code loaded after the server has -# bound its TCP listeners: -# -# ObjectSpace.each_object(TCPServer) do |s| -# s.extend Raindrops::Aggregate::LastDataRecv -# end -# -# Thread.new do -# Raindrops::Aggregate::LastDataRecv.default_aggregate.master_loop -# end -# -# Then follow the above instructions for config.ru -# -class Raindrops::LastDataRecv - # :stopdoc: - - # trigger autoloads - if defined?(Unicorn) - agg = Raindrops::Aggregate::LastDataRecv.default_aggregate - AGGREGATE_THREAD = Thread.new { agg.master_loop } - end - # :startdoc - - def initialize(opts = {}) - if defined?(Unicorn::HttpServer::LISTENERS) - Raindrops::Aggregate::LastDataRecv.cornify! - end - @aggregate = - opts[:aggregate] || Raindrops::Aggregate::LastDataRecv.default_aggregate - end - - def call(_) - a = @aggregate - count = a.count - headers = { - "Content-Type" => "text/plain", - "X-Count" => count.to_s, - } - if count > 1 - headers["X-Min"] = a.min.to_s - headers["X-Max"] = a.max.to_s - headers["X-Mean"] = a.mean.round.to_s - headers["X-Std-Dev"] = a.std_dev.round.to_s - headers["X-Outliers-Low"] = a.outliers_low.to_s - headers["X-Outliers-High"] = a.outliers_high.to_s - end - body = a.to_s - headers["Content-Length"] = body.size.to_s - [ 200, headers, [ body ] ] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/linux.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/linux.rb deleted file mode 100644 index 7cfb653..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/linux.rb +++ /dev/null @@ -1,78 +0,0 @@ -# -*- encoding: binary -*- - -# For reporting TCP ListenStats, users of older \Linux kernels need to ensure -# that the the "inet_diag" and "tcp_diag" kernel modules are loaded as they do -# not autoload correctly. The inet_diag facilities of \Raindrops is useful -# for periodic snapshot reporting of listen queue sizes. -# -# Instead of snapshotting, Raindrops::Aggregate::LastDataRecv may be used -# to aggregate statistics from +all+ accepted sockets as they arrive -# based on the +last_data_recv+ field in Raindrops::TCP_Info -require 'pathname' - -module Raindrops::Linux - - # The standard proc path for active UNIX domain sockets, feel free to call - # String#replace on this if your /proc is mounted in a non-standard location - # for whatever reason - PROC_NET_UNIX_ARGS = %w(/proc/net/unix) - defined?(::Encoding) and PROC_NET_UNIX_ARGS.push({ :encoding => "binary" }) - - # Get ListenStats from an array of +paths+ - # - # Socket state mapping from integer => symbol, based on socket_state - # enum from include/linux/net.h in the \Linux kernel: - # typedef enum { - # SS_FREE = 0, /* not allocated */ - # SS_UNCONNECTED, /* unconnected to any socket */ - # SS_CONNECTING, /* in process of connecting */ - # SS_CONNECTED, /* connected to socket */ - # SS_DISCONNECTING /* in process of disconnecting */ - # } socket_state; - # * SS_CONNECTING maps to ListenStats#queued - # * SS_CONNECTED maps to ListenStats#active - # - # This method may be significantly slower than its tcp_listener_stats - # counterpart due to the latter being able to use inet_diag via netlink. - # This parses /proc/net/unix as there is no other (known) way - # to expose Unix domain socket statistics over netlink. - def unix_listener_stats(paths = nil) - rv = Hash.new { |h,k| h[k.freeze] = Raindrops::ListenStats.new(0, 0) } - if nil == paths - paths = [ '[^\n]+' ] - else - paths = paths.map do |path| - path = path.dup - path.force_encoding(Encoding::BINARY) if defined?(Encoding) - if File.symlink?(path) - link = path - path = Pathname.new(link).realpath.to_s - rv[link] = rv[path] # vivify ListenerStats - else - rv[path] # vivify ListenerStats - end - Regexp.escape(path) - end - end - paths = /^\w+: \d+ \d+ (\d+) \d+ (\d+)\s+\d+ (#{paths.join('|')})$/n - - # no point in pread since we can't stat for size on this file - File.read(*PROC_NET_UNIX_ARGS).scan(paths) do |s| - path = s[-1] - case s[0] - when "00000000" # client sockets - case s[1].to_i - when 2 then rv[path].queued += 1 - when 3 then rv[path].active += 1 - end - else - # listeners, vivify empty stats - rv[path] - end - end - - rv - end - module_function :unix_listener_stats - -end # Raindrops::Linux diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/middleware.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/middleware.rb deleted file mode 100644 index 7c647ec..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/middleware.rb +++ /dev/null @@ -1,150 +0,0 @@ -# -*- encoding: binary -*- -require 'raindrops' - -# Raindrops::Middleware is Rack middleware that allows snapshotting -# current activity from an HTTP request. For all operating systems, -# it returns at least the following fields: -# -# * calling - the number of application dispatchers on your machine -# * writing - the number of clients being written to on your machine -# -# Additional fields are available for \Linux users. -# -# It should be loaded at the top of Rack middleware stack before other -# middlewares for maximum accuracy. -# -# === Usage (Rainbows!/Unicorn preload_app=false) -# -# If you're using preload_app=false (the default) in your Rainbows!/Unicorn -# config file, you'll need to create the global Stats object before -# forking. -# -# require 'raindrops' -# $stats ||= Raindrops::Middleware::Stats.new -# -# In your Rack config.ru: -# -# use Raindrops::Middleware, :stats => $stats -# -# === Usage (Rainbows!/Unicorn preload_app=true) -# -# If you're using preload_app=true in your Rainbows!/Unicorn -# config file, just add the middleware to your stack: -# -# In your Rack config.ru: -# -# use Raindrops::Middleware -# -# === Linux-only extras! -# -# To get bound listener statistics under \Linux, you need to specify the -# listener names for your server. You can even include listen sockets for -# *other* servers on the same machine. This can be handy for monitoring -# your nginx proxy as well. -# -# In your Rack config.ru, just pass the :listeners argument as an array of -# strings (along with any other arguments). You can specify any -# combination of TCP or Unix domain socket names: -# -# use Raindrops::Middleware, :listeners => %w(0.0.0.0:80 /tmp/.sock) -# -# If you're running Unicorn 0.98.0 or later, you don't have to pass in -# the :listeners array, Raindrops will automatically detect the listeners -# used by Unicorn master process. This does not detect listeners in -# different processes, of course. -# -# The response body includes the following stats for each listener -# (see also Raindrops::ListenStats): -# -# * active - total number of active clients on that listener -# * queued - total number of queued (pre-accept()) clients on that listener -# -# = Demo Server -# -# There is a server running this middleware (and Watcher) at -# http://raindrops-demo.bogomips.org/_raindrops -# -# Also check out the Watcher demo at http://raindrops-demo.bogomips.org/ -# -# The demo server is only limited to 30 users, so be sure not to abuse it -# by using the /tail/ endpoint too much. -# -class Raindrops::Middleware - attr_accessor :app, :stats, :path, :tcp, :unix # :nodoc: - - # A Raindrops::Struct used to count the number of :calling and :writing - # clients. This struct is intended to be shared across multiple processes - # and both counters are updated atomically. - # - # This is supported on all operating systems supported by Raindrops - class Stats < Raindrops::Struct.new(:calling, :writing) - end - - # :stopdoc: - PATH_INFO = "PATH_INFO" - require "raindrops/middleware/proxy" - # :startdoc: - - # +app+ may be any Rack application, this middleware wraps it. - # +opts+ is a hash that understands the following members: - # - # * :stats - Raindrops::Middleware::Stats struct (default: Stats.new) - # * :path - HTTP endpoint used for reading the stats (default: "/_raindrops") - # * :listeners - array of host:port or socket paths (default: from Unicorn) - def initialize(app, opts = {}) - @app = app - @stats = opts[:stats] || Stats.new - @path = opts[:path] || "/_raindrops" - tmp = opts[:listeners] - if tmp.nil? && defined?(Unicorn) && Unicorn.respond_to?(:listener_names) - tmp = Unicorn.listener_names - end - @tcp = @unix = nil - - if tmp - @tcp = tmp.grep(/\A.+:\d+\z/) - @unix = tmp.grep(%r{\A/}) - @tcp = nil if @tcp.empty? - @unix = nil if @unix.empty? - end - end - - # standard Rack endpoint - def call(env) # :nodoc: - env[PATH_INFO] == @path and return stats_response - begin - @stats.incr_calling - - status, headers, body = @app.call(env) - rv = [ status, headers, Proxy.new(body, @stats) ] - - # the Rack server will start writing headers soon after this method - @stats.incr_writing - rv - ensure - @stats.decr_calling - end - end - - def stats_response # :nodoc: - body = "calling: #{@stats.calling}\n" \ - "writing: #{@stats.writing}\n" - - if defined?(Raindrops::Linux.tcp_listener_stats) - Raindrops::Linux.tcp_listener_stats(@tcp).each do |addr,stats| - body << "#{addr} active: #{stats.active}\n" \ - "#{addr} queued: #{stats.queued}\n" - end if @tcp - Raindrops::Linux.unix_listener_stats(@unix).each do |addr,stats| - body << "#{addr} active: #{stats.active}\n" \ - "#{addr} queued: #{stats.queued}\n" - end if @unix - end - - headers = { - "Content-Type" => "text/plain", - "Content-Length" => body.size.to_s, - } - [ 200, headers, [ body ] ] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/middleware/proxy.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/middleware/proxy.rb deleted file mode 100644 index 1cf437c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/middleware/proxy.rb +++ /dev/null @@ -1,40 +0,0 @@ -# -*- encoding: binary -*- -# :stopdoc: -# This class is used by Raindrops::Middleware to proxy application -# response bodies. There should be no need to use it directly. -class Raindrops::Middleware::Proxy - def initialize(body, stats) - @body, @stats = body, stats - end - - # yield to the Rack server here for writing - def each - @body.each { |x| yield x } - end - - # the Rack server should call this after #each (usually ensure-d) - def close - @stats.decr_writing - @body.close if @body.respond_to?(:close) - end - - # Some Rack servers can optimize response processing if it responds - # to +to_path+ via the sendfile(2) system call, we proxy +to_path+ - # to the underlying body if possible. - def to_path - @body.to_path - end - - # Rack servers use +respond_to?+ to check for the presence of +close+ - # and +to_path+ methods. - def respond_to?(m) - m = m.to_sym - :close == m || @body.respond_to?(m) - end - - # Avoid breaking users of non-standard extensions (e.g. #body) - # Rack::BodyProxy does the same. - def method_missing(*args, &block) - @body.__send__(*args, &block) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/struct.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/struct.rb deleted file mode 100644 index e81a78e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/struct.rb +++ /dev/null @@ -1,62 +0,0 @@ -# -*- encoding: binary -*- - -# This is a wrapper around Raindrops objects much like the core Ruby -# \Struct can be seen as a wrapper around the core \Array class. -# It's usage is similar to the core \Struct class, except its fields -# may only be used to house unsigned long integers. -# -# class Foo < Raindrops::Struct.new(:readers, :writers) -# end -# -# foo = Foo.new 0, 0 -# -# foo.incr_writers -> 1 -# foo.incr_readers -> 1 -# -class Raindrops::Struct - - # returns a new class derived from Raindrops::Struct and supporting - # the given +members+ as fields, just like \Struct.new in core Ruby. - def self.new(*members) - members = members.map { |x| x.to_sym }.freeze - str = <= values.size) or raise ArgumentError, "too many arguments" - @raindrops = Raindrops.new(MEMBERS.size) - values.each_with_index { |val,i| @raindrops[i] = values[i] } -end - -def initialize_copy(src) - @raindrops = src.instance_variable_get(:@raindrops).dup -end - -def []=(index, value) - @raindrops[index] = value -end - -def [](index) - @raindrops[index] -end - -def to_hash - ary = @raindrops.to_ary - rv = {} - MEMBERS.each_with_index { |member, i| rv[member] = ary[i] } - rv -end -EOS - - members.each_with_index do |member, i| - str << "def incr_#{member}; @raindrops.incr(#{i}); end; " \ - "def decr_#{member}; @raindrops.decr(#{i}); end; " \ - "def #{member}; @raindrops[#{i}]; end; " \ - "def #{member}=(val); @raindrops[#{i}] = val; end; " - end - - klass = Class.new - klass.const_set(:MEMBERS, members) - klass.class_eval(str) - klass - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/watcher.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/watcher.rb deleted file mode 100644 index fb2df5b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops/watcher.rb +++ /dev/null @@ -1,428 +0,0 @@ -# -*- encoding: binary -*- -require "thread" -require "time" -require "socket" -require "rack" -require "aggregate" - -# Raindrops::Watcher is a stand-alone Rack application for watching -# any number of TCP and UNIX listeners (all of them by default). -# -# It depends on the {Aggregate RubyGem}[http://rubygems.org/gems/aggregate] -# -# In your Rack config.ru: -# -# run Raindrops::Watcher(options = {}) -# -# It takes the following options hash: -# -# - :listeners - an array of listener names, (e.g. %w(0.0.0.0:80 /tmp/sock)) -# - :delay - interval between stats updates in seconds (default: 1) -# -# Raindrops::Watcher is compatible any thread-safe/thread-aware Rack -# middleware. It does not work well with multi-process web servers -# but can be used to monitor them. It consumes minimal resources -# with the default :delay. -# -# == HTTP endpoints -# -# === GET / -# -# Returns an HTML summary listing of all listen interfaces watched on -# -# === GET /active/$LISTENER.txt -# -# Returns a plain text summary + histogram with X-* HTTP headers for -# active connections. -# -# e.g.: curl http://raindrops-demo.bogomips.org/active/0.0.0.0%3A80.txt -# -# === GET /active/$LISTENER.html -# -# Returns an HTML summary + histogram with X-* HTTP headers for -# active connections. -# -# e.g.: curl http://raindrops-demo.bogomips.org/active/0.0.0.0%3A80.html -# -# === GET /queued/$LISTENER.txt -# -# Returns a plain text summary + histogram with X-* HTTP headers for -# queued connections. -# -# e.g.: curl http://raindrops-demo.bogomips.org/queued/0.0.0.0%3A80.txt -# -# === GET /queued/$LISTENER.html -# -# Returns an HTML summary + histogram with X-* HTTP headers for -# queued connections. -# -# e.g.: curl http://raindrops-demo.bogomips.org/queued/0.0.0.0%3A80.html -# -# === POST /reset/$LISTENER -# -# Resets the active and queued statistics for the given listener. -# -# === GET /tail/$LISTENER.txt?active_min=1&queued_min=1 -# -# Streams chunked a response to the client. -# Interval is the preconfigured +:delay+ of the application (default 1 second) -# -# The response is plain text in the following format: -# -# ISO8601_TIMESTAMP LISTENER_NAME ACTIVE_COUNT QUEUED_COUNT LINEFEED -# -# Query parameters: -# -# - active_min - do not stream a line until this active count is reached -# - queued_min - do not stream a line until this queued count is reached -# -# == Response headers (mostly the same names as Raindrops::LastDataRecv) -# -# - X-Count - number of samples polled -# - X-Last-Reset - date since the last reset -# -# The following headers are only present if X-Count is greater than one. -# -# - X-Min - lowest number of connections recorded -# - X-Max - highest number of connections recorded -# - X-Mean - mean number of connections recorded -# - X-Std-Dev - standard deviation of connection count -# - X-Outliers-Low - number of low outliers (hopefully many for queued) -# - X-Outliers-High - number of high outliers (hopefully zero for queued) -# - X-Current - current number of connections -# - X-First-Peak-At - date of when X-Max was first reached -# - X-Last-Peak-At - date of when X-Max was last reached -# -# = Demo Server -# -# There is a server running this app at http://raindrops-demo.bogomips.org/ -# The Raindrops::Middleware demo is also accessible at -# http://raindrops-demo.bogomips.org/_raindrops -# -# The demo server is only limited to 30 users, so be sure not to abuse it -# by using the /tail/ endpoint too much. -class Raindrops::Watcher - # :stopdoc: - attr_reader :snapshot - include Rack::Utils - include Raindrops::Linux - DOC_URL = "http://raindrops.bogomips.org/Raindrops/Watcher.html" - Peak = Struct.new(:first, :last) - - def initialize(opts = {}) - @tcp_listeners = @unix_listeners = nil - if l = opts[:listeners] - tcp, unix = [], [] - Array(l).each { |addr| (addr =~ %r{\A/} ? unix : tcp) << addr } - unless tcp.empty? && unix.empty? - @tcp_listeners = tcp - @unix_listeners = unix - end - end - - @agg_class = opts[:agg_class] || Aggregate - @start_time = Time.now.utc - @active = Hash.new { |h,k| h[k] = @agg_class.new } - @queued = Hash.new { |h,k| h[k] = @agg_class.new } - @resets = Hash.new { |h,k| h[k] = @start_time } - @peak_active = Hash.new { |h,k| h[k] = Peak.new(@start_time, @start_time) } - @peak_queued = Hash.new { |h,k| h[k] = Peak.new(@start_time, @start_time) } - @snapshot = [ @start_time, {} ] - @delay = opts[:delay] || 1 - @lock = Mutex.new - @start = Mutex.new - @cond = ConditionVariable.new - @thr = nil - end - - def hostname - Socket.gethostname - end - - # rack endpoint - def call(env) - @start.synchronize { @thr ||= aggregator_thread(env["rack.logger"]) } - case env["REQUEST_METHOD"] - when "GET" - get env - when "HEAD" - r = get(env) - r[2] = [] - r - when "POST" - post env - else - Rack::Response.new(["Method Not Allowed"], 405).finish - end - end - - def aggregate!(agg_hash, peak_hash, addr, number, now) - agg = agg_hash[addr] - if (max = agg.max) && number > 0 && number >= max - peak = peak_hash[addr] - peak.first = now if number > max - peak.last = now - end - agg << number - end - - def aggregator_thread(logger) # :nodoc: - @socket = sock = Raindrops::InetDiagSocket.new - thr = Thread.new do - begin - combined = tcp_listener_stats(@tcp_listeners, sock) - combined.merge!(unix_listener_stats(@unix_listeners)) - @lock.synchronize do - now = Time.now.utc - combined.each do |addr,stats| - aggregate!(@active, @peak_active, addr, stats.active, now) - aggregate!(@queued, @peak_queued, addr, stats.queued, now) - end - @snapshot = [ now, combined ] - @cond.broadcast - end - rescue => e - logger.error "#{e.class} #{e.inspect}" - end while sleep(@delay) && @socket - sock.close - end - wait_snapshot - thr - end - - def non_existent_stats(time) - [ time, @start_time, @agg_class.new, 0, Peak.new(@start_time, @start_time) ] - end - - def active_stats(addr) # :nodoc: - @lock.synchronize do - time, combined = @snapshot - stats = combined[addr] or return non_existent_stats(time) - tmp, peak = @active[addr], @peak_active[addr] - [ time, @resets[addr], tmp.dup, stats.active, peak ] - end - end - - def queued_stats(addr) # :nodoc: - @lock.synchronize do - time, combined = @snapshot - stats = combined[addr] or return non_existent_stats(time) - tmp, peak = @queued[addr], @peak_queued[addr] - [ time, @resets[addr], tmp.dup, stats.queued, peak ] - end - end - - def wait_snapshot - @lock.synchronize do - @cond.wait @lock - @snapshot - end - end - - def std_dev(agg) - agg.std_dev.to_s - rescue Errno::EDOM - "NaN" - end - - def agg_to_hash(reset_at, agg, current, peak) - { - "X-Count" => agg.count.to_s, - "X-Min" => agg.min.to_s, - "X-Max" => agg.max.to_s, - "X-Mean" => agg.mean.to_s, - "X-Std-Dev" => std_dev(agg), - "X-Outliers-Low" => agg.outliers_low.to_s, - "X-Outliers-High" => agg.outliers_high.to_s, - "X-Last-Reset" => reset_at.httpdate, - "X-Current" => current.to_s, - "X-First-Peak-At" => peak.first.httpdate, - "X-Last-Peak-At" => peak.last.httpdate, - } - end - - def histogram_txt(agg) - updated_at, reset_at, agg, current, peak = *agg - headers = agg_to_hash(reset_at, agg, current, peak) - body = agg.to_s - headers["Content-Type"] = "text/plain" - headers["Expires"] = (updated_at + @delay).httpdate - headers["Content-Length"] = bytesize(body).to_s - [ 200, headers, [ body ] ] - end - - def histogram_html(agg, addr) - updated_at, reset_at, agg, current, peak = *agg - headers = agg_to_hash(reset_at, agg, current, peak) - body = "" \ - "#{hostname} - #{escape_html addr}" \ - "" << - headers.map { |k,v| - "" - }.join << "
#{k.gsub(/^X-/, '')}#{v}
#{escape_html agg}
" \ - "
" \ - "
" \ - "" - headers["Content-Type"] = "text/html" - headers["Expires"] = (updated_at + @delay).httpdate - headers["Content-Length"] = bytesize(body).to_s - [ 200, headers, [ body ] ] - end - - def get(env) - retried = false - begin - case env["PATH_INFO"] - when "/" - index - when %r{\A/active/(.+)\.txt\z} - histogram_txt(active_stats(unescape($1))) - when %r{\A/active/(.+)\.html\z} - addr = unescape $1 - histogram_html(active_stats(addr), addr) - when %r{\A/queued/(.+)\.txt\z} - histogram_txt(queued_stats(unescape($1))) - when %r{\A/queued/(.+)\.html\z} - addr = unescape $1 - histogram_html(queued_stats(addr), addr) - when %r{\A/tail/(.+)\.txt\z} - tail(unescape($1), env) - else - not_found - end - rescue Errno::EDOM - raise if retried - retried = true - wait_snapshot - retry - end - end - - def not_found - Rack::Response.new(["Not Found"], 404).finish - end - - def post(env) - case env["PATH_INFO"] - when %r{\A/reset/(.+)\z} - reset!(env, unescape($1)) - else - not_found - end - end - - def reset!(env, addr) - @lock.synchronize do - @active.include?(addr) or return not_found - @active.delete addr - @queued.delete addr - @resets[addr] = Time.now.utc - @cond.wait @lock - end - req = Rack::Request.new(env) - res = Rack::Response.new - url = req.referer || "#{req.host_with_port}/" - res.redirect(url) - res["Content-Type"] = "text/plain" - res.write "Redirecting to #{url}" - res.finish - end - - def index - updated_at, all = snapshot - headers = { - "Content-Type" => "text/html", - "Last-Modified" => updated_at.httpdate, - "Expires" => (updated_at + @delay).httpdate, - } - body = "" \ - "#{hostname} - all interfaces" \ - "

Updated at #{updated_at.iso8601}

" \ - "" \ - "" \ - "" << - all.sort do |a,b| - a[0] <=> b[0] # sort by addr - end.map do |addr,stats| - e_addr = escape addr - "" \ - "" \ - "" \ - "" \ - "" \ - "" \ - end.join << "
addressactivequeuedreset
#{escape_html addr}#{stats.active}#{stats.queued}
" \ - "
" \ - "

" \ - "This is running the #{self.class} service, see " \ - "#{DOC_URL} " \ - "for more information and options." \ - "

" \ - "" - headers["Content-Length"] = bytesize(body).to_s - [ 200, headers, [ body ] ] - end - - def tail(addr, env) - Tailer.new(self, addr, env).finish - end - - # This is the response body returned for "/tail/$ADDRESS.txt". This - # must use a multi-threaded Rack server with streaming response support. - # It is an internal class and not expected to be used directly - class Tailer - def initialize(rdmon, addr, env) # :nodoc: - @rdmon = rdmon - @addr = addr - q = Rack::Utils.parse_query env["QUERY_STRING"] - @active_min = q["active_min"].to_i - @queued_min = q["queued_min"].to_i - len = Rack::Utils.bytesize(addr) - len = 35 if len > 35 - @fmt = "%20s % #{len}s % 10u % 10u\n" - case env["HTTP_VERSION"] - when "HTTP/1.0", nil - @chunk = false - else - @chunk = true - end - end - - def finish - headers = { - "Content-Type" => "text/plain", - "Cache-Control" => "no-transform", - "Expires" => Time.at(0).httpdate, - } - headers["Transfer-Encoding"] = "chunked" if @chunk - [ 200, headers, self ] - end - - # called by the Rack server - def each # :nodoc: - begin - time, all = @rdmon.wait_snapshot - stats = all[@addr] or next - stats.queued >= @queued_min or next - stats.active >= @active_min or next - body = sprintf(@fmt, time.iso8601, @addr, stats.active, stats.queued) - body = "#{body.size.to_s(16)}\r\n#{body}\r\n" if @chunk - yield body - end while true - yield "0\r\n\r\n" if @chunk - end - end - - # shuts down the background thread, only for tests - def shutdown - @socket = nil - @thr.join if @thr - @thr = nil - end - # :startdoc: -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops_ext.bundle b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops_ext.bundle deleted file mode 100755 index 014de41..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/lib/raindrops_ext.bundle and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/pkg.mk b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/pkg.mk deleted file mode 100644 index 4cd5bef..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/pkg.mk +++ /dev/null @@ -1,175 +0,0 @@ -RUBY = ruby -RAKE = rake -RSYNC = rsync -WRONGDOC = wrongdoc - -GIT-VERSION-FILE: .FORCE-GIT-VERSION-FILE - @./GIT-VERSION-GEN --include GIT-VERSION-FILE --include local.mk -DLEXT := $(shell $(RUBY) -rrbconfig -e 'puts RbConfig::CONFIG["DLEXT"]') -RUBY_VERSION := $(shell $(RUBY) -e 'puts RUBY_VERSION') -RUBY_ENGINE := $(shell $(RUBY) -e 'puts((RUBY_ENGINE rescue "ruby"))') -lib := lib - -ifeq ($(shell test -f script/isolate_for_tests && echo t),t) -isolate_libs := tmp/isolate/$(RUBY_ENGINE)-$(RUBY_VERSION)/isolate.mk -$(isolate_libs): script/isolate_for_tests - @$(RUBY) script/isolate_for_tests --include $(isolate_libs) -lib := $(lib):$(ISOLATE_LIBS) -endif - -ext := $(firstword $(wildcard ext/*)) -ifneq ($(ext),) -ext_pfx := tmp/ext/$(RUBY_ENGINE)-$(RUBY_VERSION) -ext_h := $(wildcard $(ext)/*/*.h $(ext)/*.h) -ext_src := $(wildcard $(ext)/*.c $(ext_h)) -ext_pfx_src := $(addprefix $(ext_pfx)/,$(ext_src)) -ext_d := $(ext_pfx)/$(ext)/.d -$(ext)/extconf.rb: $(wildcard $(ext)/*.h) - @>> $@ -$(ext_d): - @mkdir -p $(@D) - @> $@ -$(ext_pfx)/$(ext)/%: $(ext)/% $(ext_d) - install -m 644 $< $@ -$(ext_pfx)/$(ext)/Makefile: $(ext)/extconf.rb $(ext_d) $(ext_h) - $(RM) -f $(@D)/*.o - cd $(@D) && $(RUBY) $(CURDIR)/$(ext)/extconf.rb -ext_sfx := _ext.$(DLEXT) -ext_dl := $(ext_pfx)/$(ext)/$(notdir $(ext)_ext.$(DLEXT)) -$(ext_dl): $(ext_src) $(ext_pfx_src) $(ext_pfx)/$(ext)/Makefile - @echo $^ == $@ - $(MAKE) -C $(@D) -lib := $(lib):$(ext_pfx)/$(ext) -build: $(ext_dl) -else -build: -endif - -pkg_extra += GIT-VERSION-FILE NEWS ChangeLog LATEST -ChangeLog: GIT-VERSION-FILE .wrongdoc.yml - $(WRONGDOC) prepare -NEWS LATEST: ChangeLog - -manifest: - $(RM) .manifest - $(MAKE) .manifest - -.manifest: $(pkg_extra) - (git ls-files && for i in $@ $(pkg_extra); do echo $$i; done) | \ - LC_ALL=C sort > $@+ - cmp $@+ $@ || mv $@+ $@ - $(RM) $@+ - -doc:: .document .wrongdoc.yml $(pkg_extra) - -find lib -type f -name '*.rbc' -exec rm -f '{}' ';' - -find ext -type f -name '*.rbc' -exec rm -f '{}' ';' - $(RM) -r doc - $(WRONGDOC) all - install -m644 COPYING doc/COPYING - install -m644 $(shell LC_ALL=C grep '^[A-Z]' .document) doc/ - -ifneq ($(VERSION),) -pkggem := pkg/$(rfpackage)-$(VERSION).gem -pkgtgz := pkg/$(rfpackage)-$(VERSION).tgz -release_notes := release_notes-$(VERSION) -release_changes := release_changes-$(VERSION) - -release-notes: $(release_notes) -release-changes: $(release_changes) -$(release_changes): - $(WRONGDOC) release_changes > $@+ - $(VISUAL) $@+ && test -s $@+ && mv $@+ $@ -$(release_notes): - $(WRONGDOC) release_notes > $@+ - $(VISUAL) $@+ && test -s $@+ && mv $@+ $@ - -# ensures we're actually on the tagged $(VERSION), only used for release -verify: - test x"$(shell umask)" = x0022 - git rev-parse --verify refs/tags/v$(VERSION)^{} - git diff-index --quiet HEAD^0 - test $$(git rev-parse --verify HEAD^0) = \ - $$(git rev-parse --verify refs/tags/v$(VERSION)^{}) - -fix-perms: - -git ls-tree -r HEAD | awk '/^100644 / {print $$NF}' | xargs chmod 644 - -git ls-tree -r HEAD | awk '/^100755 / {print $$NF}' | xargs chmod 755 - -gem: $(pkggem) - -install-gem: $(pkggem) - gem install $(CURDIR)/$< - -$(pkggem): manifest fix-perms - gem build $(rfpackage).gemspec - mkdir -p pkg - mv $(@F) $@ - -$(pkgtgz): distdir = $(basename $@) -$(pkgtgz): HEAD = v$(VERSION) -$(pkgtgz): manifest fix-perms - @test -n "$(distdir)" - $(RM) -r $(distdir) - mkdir -p $(distdir) - tar cf - $$(cat .manifest) | (cd $(distdir) && tar xf -) - cd pkg && tar cf - $(basename $(@F)) | gzip -9 > $(@F)+ - mv $@+ $@ - -package: $(pkgtgz) $(pkggem) - -test-release:: verify package $(release_notes) $(release_changes) - # make tgz release on RubyForge - @echo rubyforge add_release -f \ - -n $(release_notes) -a $(release_changes) \ - $(rfproject) $(rfpackage) $(VERSION) $(pkgtgz) - @echo gem push $(pkggem) - @echo rubyforge add_file \ - $(rfproject) $(rfpackage) $(VERSION) $(pkggem) -release:: verify package $(release_notes) $(release_changes) - # make tgz release on RubyForge - rubyforge add_release -f -n $(release_notes) -a $(release_changes) \ - $(rfproject) $(rfpackage) $(VERSION) $(pkgtgz) - # push gem to RubyGems.org - gem push $(pkggem) - # in case of gem downloads from RubyForge releases page - rubyforge add_file \ - $(rfproject) $(rfpackage) $(VERSION) $(pkggem) -else -gem install-gem: GIT-VERSION-FILE - $(MAKE) $@ VERSION=$(GIT_VERSION) -endif - -all:: test -test_units := $(wildcard test/test_*.rb) -test: test-unit -test-unit: $(test_units) -$(test_units): build - $(RUBY) -I $(lib) $@ $(RUBY_TEST_OPTS) - -# this requires GNU coreutils variants -ifneq ($(RSYNC_DEST),) -publish_doc: - -git set-file-times - $(MAKE) doc - find doc/images -type f | \ - TZ=UTC xargs touch -d '1970-01-01 00:00:06' doc/rdoc.css - $(MAKE) doc_gz - $(RSYNC) -av doc/ $(RSYNC_DEST)/ - git ls-files | xargs touch -endif - -# Create gzip variants of the same timestamp as the original so nginx -# "gzip_static on" can serve the gzipped versions directly. -doc_gz: docs = $(shell find doc -type f ! -regex '^.*\.\(gif\|jpg\|png\|gz\)$$') -doc_gz: - for i in $(docs); do \ - gzip --rsyncable -9 < $$i > $$i.gz; touch -r $$i $$i.gz; done -check-warnings: - @(for i in $$(git ls-files '*.rb'| grep -v '^setup\.rb$$'); \ - do $(RUBY) -d -W2 -c $$i; done) | grep -v '^Syntax OK$$' || : - -.PHONY: all .FORCE-GIT-VERSION-FILE doc test $(test_units) manifest -.PHONY: check-warnings diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/raindrops.gemspec b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/raindrops.gemspec deleted file mode 100644 index c5d6e87..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/raindrops.gemspec +++ /dev/null @@ -1,33 +0,0 @@ -# -*- encoding: binary -*- -ENV["VERSION"] or abort "VERSION= must be specified" -manifest = File.readlines('.manifest').map! { |x| x.chomp! } -test_files = manifest.grep(%r{\Atest/test_.*\.rb\z}) -require 'wrongdoc' -extend Wrongdoc::Gemspec -name, summary, title = readme_metadata - -Gem::Specification.new do |s| - s.name = %q{raindrops} - s.version = ENV["VERSION"].dup - - s.authors = ["raindrops hackers"] - s.date = Time.now.utc.strftime('%Y-%m-%d') - s.description = readme_description - s.email = %q{raindrops@librelist.org} - s.extensions = %w(ext/raindrops/extconf.rb) - s.extra_rdoc_files = extra_rdoc_files(manifest) - s.files = manifest - s.homepage = Wrongdoc.config[:rdoc_url] - s.summary = summary - s.rdoc_options = rdoc_options - s.rubyforge_project = %q{rainbows} - s.test_files = test_files - s.add_development_dependency('aggregate', '~> 0.2') - s.add_development_dependency('io-extra', [ '~> 1.2', '>= 1.2.3']) - s.add_development_dependency('posix_mq', '~> 2.0') - s.add_development_dependency('rack', '~> 1.2') - s.add_development_dependency('unicorn', '>= 0.98') - s.add_development_dependency('wrongdoc', ['~> 1.6.2', '>= 1.6.2']) - - s.licenses = %w(LGPLv2.1+) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/setup.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/setup.rb deleted file mode 100644 index 5eb5006..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/setup.rb +++ /dev/null @@ -1,1586 +0,0 @@ -# -*- encoding: binary -*- -# -# setup.rb -# -# Copyright (c) 2000-2005 Minero Aoki -# -# This program is free software. -# You can distribute/modify this program under the terms of -# the GNU LGPL, Lesser General Public License version 2.1. -# - -unless Enumerable.method_defined?(:map) # Ruby 1.4.6 - module Enumerable - alias map collect - end -end - -unless File.respond_to?(:read) # Ruby 1.6 - def File.read(fname) - open(fname) {|f| - return f.read - } - end -end - -unless Errno.const_defined?(:ENOTEMPTY) # Windows? - module Errno - class ENOTEMPTY - # We do not raise this exception, implementation is not needed. - end - end -end - -def File.binread(fname) - open(fname, 'rb') {|f| - return f.read - } -end - -# for corrupted Windows' stat(2) -def File.dir?(path) - File.directory?((path[-1,1] == '/') ? path : path + '/') -end - - -class ConfigTable - - include Enumerable - - def initialize(rbconfig) - @rbconfig = rbconfig - @items = [] - @table = {} - # options - @install_prefix = nil - @config_opt = nil - @verbose = true - @no_harm = false - end - - attr_accessor :install_prefix - attr_accessor :config_opt - - attr_writer :verbose - - def verbose? - @verbose - end - - attr_writer :no_harm - - def no_harm? - @no_harm - end - - def [](key) - lookup(key).resolve(self) - end - - def []=(key, val) - lookup(key).set val - end - - def names - @items.map {|i| i.name } - end - - def each(&block) - @items.each(&block) - end - - def key?(name) - @table.key?(name) - end - - def lookup(name) - @table[name] or setup_rb_error "no such config item: #{name}" - end - - def add(item) - @items.push item - @table[item.name] = item - end - - def remove(name) - item = lookup(name) - @items.delete_if {|i| i.name == name } - @table.delete_if {|name, i| i.name == name } - item - end - - def load_script(path, inst = nil) - if File.file?(path) - MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path - end - end - - def savefile - '.config' - end - - def load_savefile - begin - File.foreach(savefile()) do |line| - k, v = *line.split(/=/, 2) - self[k] = v.strip - end - rescue Errno::ENOENT - setup_rb_error $!.message + "\n#{File.basename($0)} config first" - end - end - - def save - @items.each {|i| i.value } - File.open(savefile(), 'w') {|f| - @items.each do |i| - f.printf "%s=%s\n", i.name, i.value if i.value? and i.value - end - } - end - - def load_standard_entries - standard_entries(@rbconfig).each do |ent| - add ent - end - end - - def standard_entries(rbconfig) - c = rbconfig - - rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) - - major = c['MAJOR'].to_i - minor = c['MINOR'].to_i - teeny = c['TEENY'].to_i - version = "#{major}.#{minor}" - - # ruby ver. >= 1.4.4? - newpath_p = ((major >= 2) or - ((major == 1) and - ((minor >= 5) or - ((minor == 4) and (teeny >= 4))))) - - if c['rubylibdir'] - # V > 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = c['rubylibdir'] - librubyverarch = c['archdir'] - siteruby = c['sitedir'] - siterubyver = c['sitelibdir'] - siterubyverarch = c['sitearchdir'] - elsif newpath_p - # 1.4.4 <= V <= 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = c['sitedir'] - siterubyver = "$siteruby/#{version}" - siterubyverarch = "$siterubyver/#{c['arch']}" - else - # V < 1.4.4 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" - siterubyver = siteruby - siterubyverarch = "$siterubyver/#{c['arch']}" - end - parameterize = lambda {|path| - path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') - } - - if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } - makeprog = arg.sub(/'/, '').split(/=/, 2)[1] - else - makeprog = 'make' - end - - [ - ExecItem.new('installdirs', 'std/site/home', - 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ - {|val, table| - case val - when 'std' - table['rbdir'] = '$librubyver' - table['sodir'] = '$librubyverarch' - when 'site' - table['rbdir'] = '$siterubyver' - table['sodir'] = '$siterubyverarch' - when 'home' - setup_rb_error '$HOME was not set' unless ENV['HOME'] - table['prefix'] = ENV['HOME'] - table['rbdir'] = '$libdir/ruby' - table['sodir'] = '$libdir/ruby' - end - }, - PathItem.new('prefix', 'path', c['prefix'], - 'path prefix of target environment'), - PathItem.new('bindir', 'path', parameterize.call(c['bindir']), - 'the directory for commands'), - PathItem.new('libdir', 'path', parameterize.call(c['libdir']), - 'the directory for libraries'), - PathItem.new('datadir', 'path', parameterize.call(c['datadir']), - 'the directory for shared data'), - PathItem.new('mandir', 'path', parameterize.call(c['mandir']), - 'the directory for man pages'), - PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), - 'the directory for system configuration files'), - PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), - 'the directory for local state data'), - PathItem.new('libruby', 'path', libruby, - 'the directory for ruby libraries'), - PathItem.new('librubyver', 'path', librubyver, - 'the directory for standard ruby libraries'), - PathItem.new('librubyverarch', 'path', librubyverarch, - 'the directory for standard ruby extensions'), - PathItem.new('siteruby', 'path', siteruby, - 'the directory for version-independent aux ruby libraries'), - PathItem.new('siterubyver', 'path', siterubyver, - 'the directory for aux ruby libraries'), - PathItem.new('siterubyverarch', 'path', siterubyverarch, - 'the directory for aux ruby binaries'), - PathItem.new('rbdir', 'path', '$siterubyver', - 'the directory for ruby scripts'), - PathItem.new('sodir', 'path', '$siterubyverarch', - 'the directory for ruby extentions'), - PathItem.new('rubypath', 'path', rubypath, - 'the path to set to #! line'), - ProgramItem.new('rubyprog', 'name', rubypath, - 'the ruby program using for installation'), - ProgramItem.new('makeprog', 'name', makeprog, - 'the make program to compile ruby extentions'), - SelectItem.new('shebang', 'all/ruby/never', 'ruby', - 'shebang line (#!) editing mode'), - BoolItem.new('without-ext', 'yes/no', 'no', - 'does not compile/install ruby extentions') - ] - end - private :standard_entries - - def load_multipackage_entries - multipackage_entries().each do |ent| - add ent - end - end - - def multipackage_entries - [ - PackageSelectionItem.new('with', 'name,name...', '', 'ALL', - 'package names that you want to install'), - PackageSelectionItem.new('without', 'name,name...', '', 'NONE', - 'package names that you do not want to install') - ] - end - private :multipackage_entries - - ALIASES = { - 'std-ruby' => 'librubyver', - 'stdruby' => 'librubyver', - 'rubylibdir' => 'librubyver', - 'archdir' => 'librubyverarch', - 'site-ruby-common' => 'siteruby', # For backward compatibility - 'site-ruby' => 'siterubyver', # For backward compatibility - 'bin-dir' => 'bindir', - 'bin-dir' => 'bindir', - 'rb-dir' => 'rbdir', - 'so-dir' => 'sodir', - 'data-dir' => 'datadir', - 'ruby-path' => 'rubypath', - 'ruby-prog' => 'rubyprog', - 'ruby' => 'rubyprog', - 'make-prog' => 'makeprog', - 'make' => 'makeprog' - } - - def fixup - ALIASES.each do |ali, name| - @table[ali] = @table[name] - end - @items.freeze - @table.freeze - @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ - end - - def parse_opt(opt) - m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" - m.to_a[1,2] - end - - def dllext - @rbconfig['DLEXT'] - end - - def value_config?(name) - lookup(name).value? - end - - class Item - def initialize(name, template, default, desc) - @name = name.freeze - @template = template - @value = default - @default = default - @description = desc - end - - attr_reader :name - attr_reader :description - - attr_accessor :default - alias help_default default - - def help_opt - "--#{@name}=#{@template}" - end - - def value? - true - end - - def value - @value - end - - def resolve(table) - @value.gsub(%r<\$([^/]+)>) { table[$1] } - end - - def set(val) - @value = check(val) - end - - private - - def check(val) - setup_rb_error "config: --#{name} requires argument" unless val - val - end - end - - class BoolItem < Item - def config_type - 'bool' - end - - def help_opt - "--#{@name}" - end - - private - - def check(val) - return 'yes' unless val - case val - when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' - when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' - else - setup_rb_error "config: --#{@name} accepts only yes/no for argument" - end - end - end - - class PathItem < Item - def config_type - 'path' - end - - private - - def check(path) - setup_rb_error "config: --#{@name} requires argument" unless path - path[0,1] == '$' ? path : File.expand_path(path) - end - end - - class ProgramItem < Item - def config_type - 'program' - end - end - - class SelectItem < Item - def initialize(name, selection, default, desc) - super - @ok = selection.split('/') - end - - def config_type - 'select' - end - - private - - def check(val) - unless @ok.include?(val.strip) - setup_rb_error "config: use --#{@name}=#{@template} (#{val})" - end - val.strip - end - end - - class ExecItem < Item - def initialize(name, selection, desc, &block) - super name, selection, nil, desc - @ok = selection.split('/') - @action = block - end - - def config_type - 'exec' - end - - def value? - false - end - - def resolve(table) - setup_rb_error "$#{name()} wrongly used as option value" - end - - undef set - - def evaluate(val, table) - v = val.strip.downcase - unless @ok.include?(v) - setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" - end - @action.call v, table - end - end - - class PackageSelectionItem < Item - def initialize(name, template, default, help_default, desc) - super name, template, default, desc - @help_default = help_default - end - - attr_reader :help_default - - def config_type - 'package' - end - - private - - def check(val) - unless File.dir?("packages/#{val}") - setup_rb_error "config: no such package: #{val}" - end - val - end - end - - class MetaConfigEnvironment - def initialize(config, installer) - @config = config - @installer = installer - end - - def config_names - @config.names - end - - def config?(name) - @config.key?(name) - end - - def bool_config?(name) - @config.lookup(name).config_type == 'bool' - end - - def path_config?(name) - @config.lookup(name).config_type == 'path' - end - - def value_config?(name) - @config.lookup(name).config_type != 'exec' - end - - def add_config(item) - @config.add item - end - - def add_bool_config(name, default, desc) - @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) - end - - def add_path_config(name, default, desc) - @config.add PathItem.new(name, 'path', default, desc) - end - - def set_config_default(name, default) - @config.lookup(name).default = default - end - - def remove_config(name) - @config.remove(name) - end - - # For only multipackage - def packages - raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer - @installer.packages - end - - # For only multipackage - def declare_packages(list) - raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer - @installer.packages = list - end - end - -end # class ConfigTable - - -# This module requires: #verbose?, #no_harm? -module FileOperations - - def mkdir_p(dirname, prefix = nil) - dirname = prefix + File.expand_path(dirname) if prefix - $stderr.puts "mkdir -p #{dirname}" if verbose? - return if no_harm? - - # Does not check '/', it's too abnormal. - dirs = File.expand_path(dirname).split(%r<(?=/)>) - if /\A[a-z]:\z/i =~ dirs[0] - disk = dirs.shift - dirs[0] = disk + dirs[0] - end - dirs.each_index do |idx| - path = dirs[0..idx].join('') - Dir.mkdir path unless File.dir?(path) - end - end - - def rm_f(path) - $stderr.puts "rm -f #{path}" if verbose? - return if no_harm? - force_remove_file path - end - - def rm_rf(path) - $stderr.puts "rm -rf #{path}" if verbose? - return if no_harm? - remove_tree path - end - - def remove_tree(path) - if File.symlink?(path) - remove_file path - elsif File.dir?(path) - remove_tree0 path - else - force_remove_file path - end - end - - def remove_tree0(path) - Dir.foreach(path) do |ent| - next if ent == '.' - next if ent == '..' - entpath = "#{path}/#{ent}" - if File.symlink?(entpath) - remove_file entpath - elsif File.dir?(entpath) - remove_tree0 entpath - else - force_remove_file entpath - end - end - begin - Dir.rmdir path - rescue Errno::ENOTEMPTY - # directory may not be empty - end - end - - def move_file(src, dest) - force_remove_file dest - begin - File.rename src, dest - rescue - File.open(dest, 'wb') {|f| - f.write File.binread(src) - } - File.chmod File.stat(src).mode, dest - File.unlink src - end - end - - def force_remove_file(path) - begin - remove_file path - rescue - end - end - - def remove_file(path) - File.chmod 0777, path - File.unlink path - end - - def install(from, dest, mode, prefix = nil) - $stderr.puts "install #{from} #{dest}" if verbose? - return if no_harm? - - realdest = prefix ? prefix + File.expand_path(dest) : dest - realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) - str = File.binread(from) - if diff?(str, realdest) - verbose_off { - rm_f realdest if File.exist?(realdest) - } - File.open(realdest, 'wb') {|f| - f.write str - } - File.chmod mode, realdest - - File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| - if prefix - f.puts realdest.sub(prefix, '') - else - f.puts realdest - end - } - end - end - - def diff?(new_content, path) - return true unless File.exist?(path) - new_content != File.binread(path) - end - - def command(*args) - $stderr.puts args.join(' ') if verbose? - system(*args) or raise RuntimeError, - "system(#{args.map{|a| a.inspect }.join(' ')}) failed" - end - - def ruby(*args) - command config('rubyprog'), *args - end - - def make(task = nil) - command(*[config('makeprog'), task].compact) - end - - def extdir?(dir) - File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") - end - - def files_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.file?("#{dir}/#{ent}") } - } - end - - DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) - - def directories_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT - } - end - -end - - -# This module requires: #srcdir_root, #objdir_root, #relpath -module HookScriptAPI - - def get_config(key) - @config[key] - end - - alias config get_config - - # obsolete: use metaconfig to change configuration - def set_config(key, val) - @config[key] = val - end - - # - # srcdir/objdir (works only in the package directory) - # - - def curr_srcdir - "#{srcdir_root()}/#{relpath()}" - end - - def curr_objdir - "#{objdir_root()}/#{relpath()}" - end - - def srcfile(path) - "#{curr_srcdir()}/#{path}" - end - - def srcexist?(path) - File.exist?(srcfile(path)) - end - - def srcdirectory?(path) - File.dir?(srcfile(path)) - end - - def srcfile?(path) - File.file?(srcfile(path)) - end - - def srcentries(path = '.') - Dir.open("#{curr_srcdir()}/#{path}") {|d| - return d.to_a - %w(. ..) - } - end - - def srcfiles(path = '.') - srcentries(path).select {|fname| - File.file?(File.join(curr_srcdir(), path, fname)) - } - end - - def srcdirectories(path = '.') - srcentries(path).select {|fname| - File.dir?(File.join(curr_srcdir(), path, fname)) - } - end - -end - - -class ToplevelInstaller - - Version = '3.4.1' - Copyright = 'Copyright (c) 2000-2005 Minero Aoki' - - TASKS = [ - [ 'all', 'do config, setup, then install' ], - [ 'config', 'saves your configurations' ], - [ 'show', 'shows current configuration' ], - [ 'setup', 'compiles ruby extentions and others' ], - [ 'install', 'installs files' ], - [ 'test', 'run all tests in test/' ], - [ 'clean', "does `make clean' for each extention" ], - [ 'distclean',"does `make distclean' for each extention" ] - ] - - def ToplevelInstaller.invoke - config = ConfigTable.new(load_rbconfig()) - config.load_standard_entries - config.load_multipackage_entries if multipackage? - config.fixup - klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) - klass.new(File.dirname($0), config).invoke - end - - def ToplevelInstaller.multipackage? - File.dir?(File.dirname($0) + '/packages') - end - - def ToplevelInstaller.load_rbconfig - if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } - ARGV.delete(arg) - load File.expand_path(arg.split(/=/, 2)[1]) - $".push 'rbconfig.rb' - else - require 'rbconfig' - end - ::Config::CONFIG - end - - def initialize(ardir_root, config) - @ardir = File.expand_path(ardir_root) - @config = config - # cache - @valid_task_re = nil - end - - def config(key) - @config[key] - end - - def inspect - "#<#{self.class} #{__id__()}>" - end - - def invoke - run_metaconfigs - case task = parsearg_global() - when nil, 'all' - parsearg_config - init_installers - exec_config - exec_setup - exec_install - else - case task - when 'config', 'test' - ; - when 'clean', 'distclean' - @config.load_savefile if File.exist?(@config.savefile) - else - @config.load_savefile - end - __send__ "parsearg_#{task}" - init_installers - __send__ "exec_#{task}" - end - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig" - end - - def init_installers - @installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - # - # Hook Script API bases - # - - def srcdir_root - @ardir - end - - def objdir_root - '.' - end - - def relpath - '.' - end - - # - # Option Parsing - # - - def parsearg_global - while arg = ARGV.shift - case arg - when /\A\w+\z/ - setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) - return arg - when '-q', '--quiet' - @config.verbose = false - when '--verbose' - @config.verbose = true - when '--help' - print_usage $stdout - exit 0 - when '--version' - puts "#{File.basename($0)} version #{Version}" - exit 0 - when '--copyright' - puts Copyright - exit 0 - else - setup_rb_error "unknown global option '#{arg}'" - end - end - nil - end - - def valid_task?(t) - valid_task_re() =~ t - end - - def valid_task_re - @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ - end - - def parsearg_no_options - unless ARGV.empty? - task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) - setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" - end - end - - alias parsearg_show parsearg_no_options - alias parsearg_setup parsearg_no_options - alias parsearg_test parsearg_no_options - alias parsearg_clean parsearg_no_options - alias parsearg_distclean parsearg_no_options - - def parsearg_config - evalopt = [] - set = [] - @config.config_opt = [] - while i = ARGV.shift - if /\A--?\z/ =~ i - @config.config_opt = ARGV.dup - break - end - name, value = *@config.parse_opt(i) - if @config.value_config?(name) - @config[name] = value - else - evalopt.push [name, value] - end - set.push name - end - evalopt.each do |name, value| - @config.lookup(name).evaluate value, @config - end - # Check if configuration is valid - set.each do |n| - @config[n] if @config.value_config?(n) - end - end - - def parsearg_install - @config.no_harm = false - @config.install_prefix = '' - while a = ARGV.shift - case a - when '--no-harm' - @config.no_harm = true - when /\A--prefix=/ - path = a.split(/=/, 2)[1] - path = File.expand_path(path) unless path[0,1] == '/' - @config.install_prefix = path - else - setup_rb_error "install: unknown option #{a}" - end - end - end - - def print_usage(out) - out.puts 'Typical Installation Procedure:' - out.puts " $ ruby #{File.basename $0} config" - out.puts " $ ruby #{File.basename $0} setup" - out.puts " # ruby #{File.basename $0} install (may require root privilege)" - out.puts - out.puts 'Detailed Usage:' - out.puts " ruby #{File.basename $0} " - out.puts " ruby #{File.basename $0} [] []" - - fmt = " %-24s %s\n" - out.puts - out.puts 'Global options:' - out.printf fmt, '-q,--quiet', 'suppress message outputs' - out.printf fmt, ' --verbose', 'output messages verbosely' - out.printf fmt, ' --help', 'print this message' - out.printf fmt, ' --version', 'print version and quit' - out.printf fmt, ' --copyright', 'print copyright and quit' - out.puts - out.puts 'Tasks:' - TASKS.each do |name, desc| - out.printf fmt, name, desc - end - - fmt = " %-24s %s [%s]\n" - out.puts - out.puts 'Options for CONFIG or ALL:' - @config.each do |item| - out.printf fmt, item.help_opt, item.description, item.help_default - end - out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" - out.puts - out.puts 'Options for INSTALL:' - out.printf fmt, '--no-harm', 'only display what to do if given', 'off' - out.printf fmt, '--prefix=path', 'install path prefix', '' - out.puts - end - - # - # Task Handlers - # - - def exec_config - @installer.exec_config - @config.save # must be final - end - - def exec_setup - @installer.exec_setup - end - - def exec_install - @installer.exec_install - end - - def exec_test - @installer.exec_test - end - - def exec_show - @config.each do |i| - printf "%-20s %s\n", i.name, i.value if i.value? - end - end - - def exec_clean - @installer.exec_clean - end - - def exec_distclean - @installer.exec_distclean - end - -end # class ToplevelInstaller - - -class ToplevelInstallerMulti < ToplevelInstaller - - include FileOperations - - def initialize(ardir_root, config) - super - @packages = directories_of("#{@ardir}/packages") - raise 'no package exists' if @packages.empty? - @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig", self - @packages.each do |name| - @config.load_script "#{@ardir}/packages/#{name}/metaconfig" - end - end - - attr_reader :packages - - def packages=(list) - raise 'package list is empty' if list.empty? - list.each do |name| - raise "directory packages/#{name} does not exist"\ - unless File.dir?("#{@ardir}/packages/#{name}") - end - @packages = list - end - - def init_installers - @installers = {} - @packages.each do |pack| - @installers[pack] = Installer.new(@config, - "#{@ardir}/packages/#{pack}", - "packages/#{pack}") - end - with = extract_selection(config('with')) - without = extract_selection(config('without')) - @selected = @installers.keys.select {|name| - (with.empty? or with.include?(name)) \ - and not without.include?(name) - } - end - - def extract_selection(list) - a = list.split(/,/) - a.each do |name| - setup_rb_error "no such package: #{name}" unless @installers.key?(name) - end - a - end - - def print_usage(f) - super - f.puts 'Inluded packages:' - f.puts ' ' + @packages.sort.join(' ') - f.puts - end - - # - # Task Handlers - # - - def exec_config - run_hook 'pre-config' - each_selected_installers {|inst| inst.exec_config } - run_hook 'post-config' - @config.save # must be final - end - - def exec_setup - run_hook 'pre-setup' - each_selected_installers {|inst| inst.exec_setup } - run_hook 'post-setup' - end - - def exec_install - run_hook 'pre-install' - each_selected_installers {|inst| inst.exec_install } - run_hook 'post-install' - end - - def exec_test - run_hook 'pre-test' - each_selected_installers {|inst| inst.exec_test } - run_hook 'post-test' - end - - def exec_clean - rm_f @config.savefile - run_hook 'pre-clean' - each_selected_installers {|inst| inst.exec_clean } - run_hook 'post-clean' - end - - def exec_distclean - rm_f @config.savefile - run_hook 'pre-distclean' - each_selected_installers {|inst| inst.exec_distclean } - run_hook 'post-distclean' - end - - # - # lib - # - - def each_selected_installers - Dir.mkdir 'packages' unless File.dir?('packages') - @selected.each do |pack| - $stderr.puts "Processing the package `#{pack}' ..." if verbose? - Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") - Dir.chdir "packages/#{pack}" - yield @installers[pack] - Dir.chdir '../..' - end - end - - def run_hook(id) - @root_installer.run_hook id - end - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - -end # class ToplevelInstallerMulti - - -class Installer - - FILETYPES = %w( bin lib ext data conf man ) - - include FileOperations - include HookScriptAPI - - def initialize(config, srcroot, objroot) - @config = config - @srcdir = File.expand_path(srcroot) - @objdir = File.expand_path(objroot) - @currdir = '.' - end - - def inspect - "#<#{self.class} #{File.basename(@srcdir)}>" - end - - def noop(rel) - end - - # - # Hook Script API base methods - # - - def srcdir_root - @srcdir - end - - def objdir_root - @objdir - end - - def relpath - @currdir - end - - # - # Config Access - # - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - - def verbose_off - begin - save, @config.verbose = @config.verbose?, false - yield - ensure - @config.verbose = save - end - end - - # - # TASK config - # - - def exec_config - exec_task_traverse 'config' - end - - alias config_dir_bin noop - alias config_dir_lib noop - - def config_dir_ext(rel) - extconf if extdir?(curr_srcdir()) - end - - alias config_dir_data noop - alias config_dir_conf noop - alias config_dir_man noop - - def extconf - ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt - end - - # - # TASK setup - # - - def exec_setup - exec_task_traverse 'setup' - end - - def setup_dir_bin(rel) - files_of(curr_srcdir()).each do |fname| - update_shebang_line "#{curr_srcdir()}/#{fname}" - end - end - - alias setup_dir_lib noop - - def setup_dir_ext(rel) - make if extdir?(curr_srcdir()) - end - - alias setup_dir_data noop - alias setup_dir_conf noop - alias setup_dir_man noop - - def update_shebang_line(path) - return if no_harm? - return if config('shebang') == 'never' - old = Shebang.load(path) - if old - $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 - new = new_shebang(old) - return if new.to_s == old.to_s - else - return unless config('shebang') == 'all' - new = Shebang.new(config('rubypath')) - end - $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? - open_atomic_writer(path) {|output| - File.open(path, 'rb') {|f| - f.gets if old # discard - output.puts new.to_s - output.print f.read - } - } - end - - def new_shebang(old) - if /\Aruby/ =~ File.basename(old.cmd) - Shebang.new(config('rubypath'), old.args) - elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' - Shebang.new(config('rubypath'), old.args[1..-1]) - else - return old unless config('shebang') == 'all' - Shebang.new(config('rubypath')) - end - end - - def open_atomic_writer(path, &block) - tmpfile = File.basename(path) + '.tmp' - begin - File.open(tmpfile, 'wb', &block) - File.rename tmpfile, File.basename(path) - ensure - File.unlink tmpfile if File.exist?(tmpfile) - end - end - - class Shebang - def Shebang.load(path) - line = nil - File.open(path) {|f| - line = f.gets - } - return nil unless /\A#!/ =~ line - parse(line) - end - - def Shebang.parse(line) - cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') - new(cmd, args) - end - - def initialize(cmd, args = []) - @cmd = cmd - @args = args - end - - attr_reader :cmd - attr_reader :args - - def to_s - "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") - end - end - - # - # TASK install - # - - def exec_install - rm_f 'InstalledFiles' - exec_task_traverse 'install' - end - - def install_dir_bin(rel) - install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 - end - - def install_dir_lib(rel) - install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 - end - - def install_dir_ext(rel) - return unless extdir?(curr_srcdir()) - install_files rubyextentions('.'), - "#{config('sodir')}/#{File.dirname(rel)}", - 0555 - end - - def install_dir_data(rel) - install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 - end - - def install_dir_conf(rel) - # FIXME: should not remove current config files - # (rename previous file to .old/.org) - install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 - end - - def install_dir_man(rel) - install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 - end - - def install_files(list, dest, mode) - mkdir_p dest, @config.install_prefix - list.each do |fname| - install fname, dest, mode, @config.install_prefix - end - end - - def libfiles - glob_reject(%w(*.y *.output), targetfiles()) - end - - def rubyextentions(dir) - ents = glob_select("*.#{@config.dllext}", targetfiles()) - if ents.empty? - setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" - end - ents - end - - def targetfiles - mapdir(existfiles() - hookfiles()) - end - - def mapdir(ents) - ents.map {|ent| - if File.exist?(ent) - then ent # objdir - else "#{curr_srcdir()}/#{ent}" # srcdir - end - } - end - - # picked up many entries from cvs-1.11.1/src/ignore.c - JUNK_FILES = %w( - core RCSLOG tags TAGS .make.state - .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb - *~ *.old *.bak *.BAK *.orig *.rej _$* *$ - - *.org *.in .* - ) - - def existfiles - glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) - end - - def hookfiles - %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| - %w( config setup install clean ).map {|t| sprintf(fmt, t) } - }.flatten - end - - def glob_select(pat, ents) - re = globs2re([pat]) - ents.select {|ent| re =~ ent } - end - - def glob_reject(pats, ents) - re = globs2re(pats) - ents.reject {|ent| re =~ ent } - end - - GLOB2REGEX = { - '.' => '\.', - '$' => '\$', - '#' => '\#', - '*' => '.*' - } - - def globs2re(pats) - /\A(?:#{ - pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') - })\z/ - end - - # - # TASK test - # - - TESTDIR = 'test' - - def exec_test - unless File.directory?('test') - $stderr.puts 'no test in this package' if verbose? - return - end - $stderr.puts 'Running tests...' if verbose? - begin - require 'test/unit' - rescue LoadError - setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' - end - runner = Test::Unit::AutoRunner.new(true) - runner.to_run << TESTDIR - runner.run - end - - # - # TASK clean - # - - def exec_clean - exec_task_traverse 'clean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias clean_dir_bin noop - alias clean_dir_lib noop - alias clean_dir_data noop - alias clean_dir_conf noop - alias clean_dir_man noop - - def clean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'clean' if File.file?('Makefile') - end - - # - # TASK distclean - # - - def exec_distclean - exec_task_traverse 'distclean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias distclean_dir_bin noop - alias distclean_dir_lib noop - - def distclean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'distclean' if File.file?('Makefile') - end - - alias distclean_dir_data noop - alias distclean_dir_conf noop - alias distclean_dir_man noop - - # - # Traversing - # - - def exec_task_traverse(task) - run_hook "pre-#{task}" - FILETYPES.each do |type| - if type == 'ext' and config('without-ext') == 'yes' - $stderr.puts 'skipping ext/* by user option' if verbose? - next - end - traverse task, type, "#{task}_dir_#{type}" - end - run_hook "post-#{task}" - end - - def traverse(task, rel, mid) - dive_into(rel) { - run_hook "pre-#{task}" - __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') - directories_of(curr_srcdir()).each do |d| - traverse task, "#{rel}/#{d}", mid - end - run_hook "post-#{task}" - } - end - - def dive_into(rel) - return unless File.dir?("#{@srcdir}/#{rel}") - - dir = File.basename(rel) - Dir.mkdir dir unless File.dir?(dir) - prevdir = Dir.pwd - Dir.chdir dir - $stderr.puts '---> ' + rel if verbose? - @currdir = rel - yield - Dir.chdir prevdir - $stderr.puts '<--- ' + rel if verbose? - @currdir = File.dirname(rel) - end - - def run_hook(id) - path = [ "#{curr_srcdir()}/#{id}", - "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } - return unless path - begin - instance_eval File.read(path), path, 1 - rescue - raise if $DEBUG - setup_rb_error "hook #{path} failed:\n" + $!.message - end - end - -end # class Installer - - -class SetupError < StandardError; end - -def setup_rb_error(msg) - raise SetupError, msg -end - -if $0 == __FILE__ - begin - ToplevelInstaller.invoke - rescue SetupError - raise if $DEBUG - $stderr.puts $!.message - $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." - exit 1 - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/ipv6_enabled.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/ipv6_enabled.rb deleted file mode 100644 index f02b48f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/ipv6_enabled.rb +++ /dev/null @@ -1,9 +0,0 @@ -def ipv6_enabled? - tmp = TCPServer.new(ENV["TEST_HOST6"] || '::1', 0) - tmp.close - true - rescue => e - warn "skipping IPv6 tests, host does not seem to be IPv6 enabled:" - warn " #{e.class}: #{e}" - false -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/rack_unicorn.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/rack_unicorn.rb deleted file mode 100644 index 779e8bf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/rack_unicorn.rb +++ /dev/null @@ -1,12 +0,0 @@ -# -*- encoding: binary -*- -require "test/unit" -require "raindrops" -require "rack" -require "rack/lobster" -require "open-uri" -begin - require "unicorn" - require "rack/lobster" -rescue LoadError => e - warn "W: #{e} skipping test since Rack or Unicorn was not found" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_aggregate_pmq.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_aggregate_pmq.rb deleted file mode 100644 index 7748b4f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_aggregate_pmq.rb +++ /dev/null @@ -1,65 +0,0 @@ -require "test/unit" -require "raindrops" -pmq = begin - Raindrops::Aggregate::PMQ -rescue LoadError => e - warn "W: #{e} skipping test" - false -end -if RUBY_VERSION.to_f < 1.9 - pmq = false - warn "W: skipping #{__FILE__}, only Ruby 1.9 supported for now" -end - -Thread.abort_on_exception = true - -class TestAggregatePMQ < Test::Unit::TestCase - - def setup - @queue = "/test.#{rand}" - end - - def teardown - POSIX_MQ.unlink @queue - end - - def test_run - pmq = Raindrops::Aggregate::PMQ.new :queue => @queue - thr = Thread.new { pmq.master_loop } - agg = Aggregate.new - (1..10).each { |i| pmq << i; agg << i } - pmq.stop_master_loop - assert thr.join - assert_equal agg.count, pmq.count - assert_equal agg.mean, pmq.mean - assert_equal agg.std_dev, pmq.std_dev - assert_equal agg.min, pmq.min - assert_equal agg.max, pmq.max - assert_equal agg.to_s, pmq.to_s - end - - def test_multi_process - nr_workers = 4 - nr = 100 - pmq = Raindrops::Aggregate::PMQ.new :queue => @queue - pid = fork { pmq.master_loop } - workers = (1..nr_workers).map { - fork { - (1..nr).each { |i| pmq << i } - pmq.flush - } - } - workers.each { |wpid| assert Process.waitpid2(wpid).last.success? } - pmq.stop_master_loop - assert Process.waitpid2(pid).last.success? - assert_equal 400, pmq.count - agg = Aggregate.new - (1..nr_workers).map { (1..nr).each { |i| agg << i } } - assert_equal agg.to_s, pmq.to_s - assert_equal agg.mean, pmq.mean - assert_equal agg.std_dev, pmq.std_dev - assert_equal agg.min, pmq.min - assert_equal agg.max, pmq.max - assert_equal agg.to_s, pmq.to_s - end -end if pmq diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_inet_diag_socket.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_inet_diag_socket.rb deleted file mode 100644 index 047dff3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_inet_diag_socket.rb +++ /dev/null @@ -1,16 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'raindrops' -require 'fcntl' -$stderr.sync = $stdout.sync = true - -class TestInetDiagSocket < Test::Unit::TestCase - def test_new - sock = Raindrops::InetDiagSocket.new - assert_kind_of Socket, sock - assert_kind_of Fixnum, sock.fileno - flags = sock.fcntl(Fcntl::F_GETFD) - assert_equal Fcntl::FD_CLOEXEC, flags & Fcntl::FD_CLOEXEC - assert_nil sock.close - end -end if RUBY_PLATFORM =~ /linux/ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_last_data_recv_unicorn.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_last_data_recv_unicorn.rb deleted file mode 100644 index ca48715..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_last_data_recv_unicorn.rb +++ /dev/null @@ -1,69 +0,0 @@ -# -*- encoding: binary -*- -require "./test/rack_unicorn" -require "tempfile" -require "net/http" - -$stderr.sync = $stdout.sync = true -pmq = begin - Raindrops::Aggregate::PMQ -rescue LoadError => e - warn "W: #{e} skipping test" - false -end -if RUBY_VERSION.to_f < 1.9 - pmq = false - warn "W: skipping test=#{__FILE__}, only Ruby 1.9 supported for now" -end - -class TestLastDataRecvUnicorn < Test::Unit::TestCase - def setup - @queue = "/test.#{rand}" - @host = ENV["UNICORN_TEST_ADDR"] || "127.0.0.1" - @sock = TCPServer.new @host, 0 - @port = @sock.addr[1] - ENV["UNICORN_FD"] = @sock.fileno.to_s - @host_with_port = "#@host:#@port" - @cfg = Tempfile.new 'unicorn_config_file' - @cfg.puts "require 'raindrops'" - @cfg.puts "preload_app true" - ENV['RAINDROPS_MQUEUE'] = @queue - # @cfg.puts "worker_processes 4" - @opts = { :listeners => [ @host_with_port ], :config_file => @cfg.path } - end - - def test_auto_listener - @srv = fork { - Thread.abort_on_exception = true - app = %q!Rack::Builder.new do - map("/ldr") { run Raindrops::LastDataRecv.new } - map("/") { run Rack::Lobster.new } - end.to_app! - def app.arity; 0; end - def app.call; eval self; end - Unicorn::HttpServer.new(app, @opts).start.join - } - 400.times { assert_kind_of Net::HTTPSuccess, get("/") } - resp = get("/ldr") - # # p(resp.methods - Object.methods) - # resp.each_header { |k,v| p [k, "=" , v] } - assert resp.header["x-count"] - assert resp.header["x-min"] - assert resp.header["x-max"] - assert resp.header["x-mean"] - assert resp.header["x-std-dev"] - assert resp.header["x-outliers-low"] - assert resp.header["x-outliers-high"] - assert resp.body.size > 0 - end - - def get(path) - Net::HTTP.start(@host, @port) { |http| http.get path } - end - - def teardown - Process.kill :QUIT, @srv - _, status = Process.waitpid2 @srv - assert status.success? - POSIX_MQ.unlink @queue - end -end if defined?(Unicorn) && RUBY_PLATFORM =~ /linux/ && pmq diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux.rb deleted file mode 100644 index 0e79a86..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux.rb +++ /dev/null @@ -1,273 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'tempfile' -require 'raindrops' -require 'socket' -require 'pp' -$stderr.sync = $stdout.sync = true - -class TestLinux < Test::Unit::TestCase - include Raindrops::Linux - - TEST_ADDR = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - - def setup - @to_close = [] - end - - def teardown - @to_close.each { |io| io.close unless io.closed? } - end - - def test_unix - tmp = Tempfile.new("\xde\xad\xbe\xef") # valid path, really :) - File.unlink(tmp.path) - us = UNIXServer.new(tmp.path) - stats = unix_listener_stats([tmp.path]) - assert_equal 1, stats.size - assert_equal 0, stats[tmp.path].active - assert_equal 0, stats[tmp.path].queued - - @to_close << UNIXSocket.new(tmp.path) - stats = unix_listener_stats([tmp.path]) - assert_equal 1, stats.size - assert_equal 0, stats[tmp.path].active - assert_equal 1, stats[tmp.path].queued - - @to_close << UNIXSocket.new(tmp.path) - stats = unix_listener_stats([tmp.path]) - assert_equal 1, stats.size - assert_equal 0, stats[tmp.path].active - assert_equal 2, stats[tmp.path].queued - - @to_close << us.accept - stats = unix_listener_stats([tmp.path]) - assert_equal 1, stats.size - assert_equal 1, stats[tmp.path].active - assert_equal 1, stats[tmp.path].queued - end - - def test_unix_all - tmp = Tempfile.new("\xde\xad\xbe\xef") # valid path, really :) - File.unlink(tmp.path) - us = UNIXServer.new(tmp.path) - @to_close << UNIXSocket.new(tmp.path) - stats = unix_listener_stats - assert_equal 0, stats[tmp.path].active - assert_equal 1, stats[tmp.path].queued - - @to_close << UNIXSocket.new(tmp.path) - stats = unix_listener_stats - assert_equal 0, stats[tmp.path].active - assert_equal 2, stats[tmp.path].queued - - @to_close << us.accept - stats = unix_listener_stats - assert_equal 1, stats[tmp.path].active - assert_equal 1, stats[tmp.path].queued - end - - def test_unix_all_unused - tmp = Tempfile.new("\xde\xad\xbe\xef") # valid path, really :) - File.unlink(tmp.path) - us = UNIXServer.new(tmp.path) - stats = unix_listener_stats - assert stats.keys.include?(tmp.path), stats.inspect - - assert_equal 0, stats[tmp.path].active - assert_equal 0, stats[tmp.path].queued - end - - def test_unix_resolves_symlinks - tmp = Tempfile.new("\xde\xad\xbe\xef") # valid path, really :) - File.unlink(tmp.path) - us = UNIXServer.new(tmp.path) - - # Create a symlink - link = Tempfile.new("somethingelse") - File.unlink(link.path) # We need an available name, not an actual file - File.symlink(tmp.path, link.path) - - @to_close << UNIXSocket.new(tmp.path) - stats = unix_listener_stats - assert_equal 0, stats[tmp.path].active - assert_equal 1, stats[tmp.path].queued - - @to_close << UNIXSocket.new(link.path) - stats = unix_listener_stats([link.path]) - assert_equal 0, stats[link.path].active - assert_equal 2, stats[link.path].queued - - assert_equal stats[link.path].object_id, stats[tmp.path].object_id - - @to_close << us.accept - stats = unix_listener_stats - assert_equal 1, stats[tmp.path].active - assert_equal 1, stats[tmp.path].queued - end - - def test_tcp - s = TCPServer.new(TEST_ADDR, 0) - port = s.addr[1] - addr = "#{TEST_ADDR}:#{port}" - addrs = [ addr ] - stats = tcp_listener_stats(addrs) - assert_equal 1, stats.size - assert_equal 0, stats[addr].queued - assert_equal 0, stats[addr].active - - @to_close << TCPSocket.new(TEST_ADDR, port) - stats = tcp_listener_stats(addrs) - assert_equal 1, stats.size - assert_equal 1, stats[addr].queued - assert_equal 0, stats[addr].active - - @to_close << s.accept - stats = tcp_listener_stats(addrs) - assert_equal 1, stats.size - assert_equal 0, stats[addr].queued - assert_equal 1, stats[addr].active - end - - def test_tcp_reuse_sock - nlsock = Raindrops::InetDiagSocket.new - s = TCPServer.new(TEST_ADDR, 0) - port = s.addr[1] - addr = "#{TEST_ADDR}:#{port}" - addrs = [ addr ] - stats = tcp_listener_stats(addrs, nlsock) - assert_equal 1, stats.size - assert_equal 0, stats[addr].queued - assert_equal 0, stats[addr].active - - @to_close << TCPSocket.new(TEST_ADDR, port) - stats = tcp_listener_stats(addrs, nlsock) - assert_equal 1, stats.size - assert_equal 1, stats[addr].queued - assert_equal 0, stats[addr].active - - @to_close << s.accept - stats = tcp_listener_stats(addrs, nlsock) - assert_equal 1, stats.size - assert_equal 0, stats[addr].queued - assert_equal 1, stats[addr].active - ensure - nlsock.close - end - - def test_tcp_multi - s1 = TCPServer.new(TEST_ADDR, 0) - s2 = TCPServer.new(TEST_ADDR, 0) - port1, port2 = s1.addr[1], s2.addr[1] - addr1, addr2 = "#{TEST_ADDR}:#{port1}", "#{TEST_ADDR}:#{port2}" - addrs = [ addr1, addr2 ] - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 0, stats[addr1].active - assert_equal 0, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << TCPSocket.new(TEST_ADDR, port1) - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 1, stats[addr1].queued - assert_equal 0, stats[addr1].active - assert_equal 0, stats[addr2].queued - assert_equal 0, stats[addr2].active - - sc1 = s1.accept - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 0, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << TCPSocket.new(TEST_ADDR, port2) - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 1, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << TCPSocket.new(TEST_ADDR, port2) - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 2, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << s2.accept - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 1, stats[addr2].queued - assert_equal 1, stats[addr2].active - - sc1.close - stats = tcp_listener_stats(addrs) - assert_equal 0, stats[addr1].queued - assert_equal 0, stats[addr1].active - assert_equal 1, stats[addr2].queued - assert_equal 1, stats[addr2].active - end - - # tries to overflow buffers - def test_tcp_stress_test - nr_proc = 32 - nr_sock = 500 - s = TCPServer.new(TEST_ADDR, 0) - port = s.addr[1] - addr = "#{TEST_ADDR}:#{port}" - addrs = [ addr ] - rda, wra = IO.pipe - rdb, wrb = IO.pipe - - nr_proc.times do - fork do - rda.close - wrb.close - @to_close.concat((1..nr_sock).map { s.accept }) - wra.syswrite('.') - wra.close - rdb.sysread(1) # wait for parent to nuke us - end - end - - nr_proc.times do - fork do - rda.close - wrb.close - @to_close.concat((1..nr_sock).map { TCPSocket.new(TEST_ADDR, port) }) - wra.syswrite('.') - wra.close - rdb.sysread(1) # wait for parent to nuke us - end - end - - assert_equal('.' * (nr_proc * 2), rda.read(nr_proc * 2)) - - rda.close - stats = tcp_listener_stats(addrs) - expect = { addr => Raindrops::ListenStats[nr_sock * nr_proc, 0] } - assert_equal expect, stats - - @to_close << TCPSocket.new(TEST_ADDR, port) - stats = tcp_listener_stats(addrs) - expect = { addr => Raindrops::ListenStats[nr_sock * nr_proc, 1] } - assert_equal expect, stats - - if ENV["BENCHMARK"].to_i != 0 - require 'benchmark' - puts(Benchmark.measure{1000.times { tcp_listener_stats(addrs) }}) - end - - wrb.syswrite('.' * (nr_proc * 2)) # broadcast a wakeup - statuses = Process.waitall - statuses.each { |(_,status)| assert status.success?, status.inspect } - end if ENV["STRESS"].to_i != 0 -end if RUBY_PLATFORM =~ /linux/ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_all_tcp_listen_stats.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_all_tcp_listen_stats.rb deleted file mode 100644 index ef1f943..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_all_tcp_listen_stats.rb +++ /dev/null @@ -1,66 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'socket' -require 'raindrops' -require 'pp' -$stderr.sync = $stdout.sync = true - -class TestLinuxAllTcpListenStats < Test::Unit::TestCase - include Raindrops::Linux - TEST_ADDR = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - - def test_print_all - puts "EVERYTHING" - pp Raindrops::Linux.tcp_listener_stats - puts("-" * 72) - end if $stdout.tty? - - def setup - @socks = [] - end - - def teardown - @socks.each { |io| io.closed? or io.close } - end - - def new_server - s = TCPServer.new TEST_ADDR, 0 - @socks << s - [ s, s.addr[1] ] - end - - def new_client(port) - s = TCPSocket.new("127.0.0.1", port) - @socks << s - s - end - - def new_accept(srv) - c = srv.accept - @socks << c - c - end - - def test_all_ports - srv, port = new_server - addr = "#{TEST_ADDR}:#{port}" - all = Raindrops::Linux.tcp_listener_stats - assert_equal [0,0], all[addr].to_a - - new_client(port) - all = Raindrops::Linux.tcp_listener_stats - assert_equal [0,1], all[addr].to_a - - new_client(port) - all = Raindrops::Linux.tcp_listener_stats - assert_equal [0,2], all[addr].to_a - - new_accept(srv) - all = Raindrops::Linux.tcp_listener_stats - assert_equal [1,1], all[addr].to_a - - new_accept(srv) - all = Raindrops::Linux.tcp_listener_stats - assert_equal [2,0], all[addr].to_a - end -end if RUBY_PLATFORM =~ /linux/ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_all_tcp_listen_stats_leak.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_all_tcp_listen_stats_leak.rb deleted file mode 100644 index 7368220..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_all_tcp_listen_stats_leak.rb +++ /dev/null @@ -1,43 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'raindrops' -require 'socket' -require 'benchmark' -$stderr.sync = $stdout.sync = true - -class TestLinuxAllTcpListenStatsLeak < Test::Unit::TestCase - - TEST_ADDR = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - - - def rss_kb - File.readlines("/proc/#$$/status").grep(/VmRSS:/)[0].split(/\s+/)[1].to_i - end - def test_leak - s = TCPServer.new(TEST_ADDR, 0) - start_kb = rss_kb - p [ :start_kb, start_kb ] - assert_nothing_raised do - p(Benchmark.measure { - 1000.times { Raindrops::Linux.all_tcp_listener_stats } - }) - end - cur_kb = rss_kb - p [ :cur_kb, cur_kb ] - now = Time.now.to_i - fin = now + 60 - assert_nothing_raised do - 1000000000.times { |i| - if (i % 1024) == 0 - now = Time.now.to_i - break if now > fin - end - Raindrops::Linux.all_tcp_listener_stats - } - end - cur_kb = rss_kb - p [ :cur_kb, cur_kb ] - ensure - s.close - end -end if ENV["STRESS"].to_i != 0 diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_ipv6.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_ipv6.rb deleted file mode 100644 index ec08f28..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_ipv6.rb +++ /dev/null @@ -1,158 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'tempfile' -require 'raindrops' -require 'socket' -require 'pp' -require "./test/ipv6_enabled" -$stderr.sync = $stdout.sync = true - -class TestLinuxIPv6 < Test::Unit::TestCase - include Raindrops::Linux - - TEST_ADDR = ENV["TEST_HOST6"] || "::1" - - def test_tcp - s = TCPServer.new(TEST_ADDR, 0) - port = s.addr[1] - addr = "[#{TEST_ADDR}]:#{port}" - addrs = [ addr ] - stats = tcp_listener_stats(addrs) - assert_equal 1, stats.size - assert_equal 0, stats[addr].queued - assert_equal 0, stats[addr].active - - @to_close << TCPSocket.new(TEST_ADDR, port) - stats = tcp_listener_stats(addrs) - assert_equal 1, stats.size - assert_equal 1, stats[addr].queued - assert_equal 0, stats[addr].active - - @to_close << s.accept - stats = tcp_listener_stats(addrs) - assert_equal 1, stats.size - assert_equal 0, stats[addr].queued - assert_equal 1, stats[addr].active - end - - def test_tcp_multi - s1 = TCPServer.new(TEST_ADDR, 0) - s2 = TCPServer.new(TEST_ADDR, 0) - port1, port2 = s1.addr[1], s2.addr[1] - addr1, addr2 = "[#{TEST_ADDR}]:#{port1}", "[#{TEST_ADDR}]:#{port2}" - addrs = [ addr1, addr2 ] - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 0, stats[addr1].active - assert_equal 0, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << TCPSocket.new(TEST_ADDR, port1) - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 1, stats[addr1].queued - assert_equal 0, stats[addr1].active - assert_equal 0, stats[addr2].queued - assert_equal 0, stats[addr2].active - - sc1 = s1.accept - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 0, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << TCPSocket.new(TEST_ADDR, port2) - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 1, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << TCPSocket.new(TEST_ADDR, port2) - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 2, stats[addr2].queued - assert_equal 0, stats[addr2].active - - @to_close << s2.accept - stats = tcp_listener_stats(addrs) - assert_equal 2, stats.size - assert_equal 0, stats[addr1].queued - assert_equal 1, stats[addr1].active - assert_equal 1, stats[addr2].queued - assert_equal 1, stats[addr2].active - - sc1.close - stats = tcp_listener_stats(addrs) - assert_equal 0, stats[addr1].queued - assert_equal 0, stats[addr1].active - assert_equal 1, stats[addr2].queued - assert_equal 1, stats[addr2].active - end - - def test_invalid_addresses - assert_raises(ArgumentError) { tcp_listener_stats(%w([1:::5)) } - assert_raises(ArgumentError) { tcp_listener_stats(%w([1:::]5)) } - end - - # tries to overflow buffers - def test_tcp_stress_test - nr_proc = 32 - nr_sock = 500 - s = TCPServer.new(TEST_ADDR, 0) - port = s.addr[1] - addr = "[#{TEST_ADDR}]:#{port}" - addrs = [ addr ] - rda, wra = IO.pipe - rdb, wrb = IO.pipe - - nr_proc.times do - fork do - rda.close - wrb.close - @to_close.concat((1..nr_sock).map { s.accept }) - wra.syswrite('.') - wra.close - rdb.sysread(1) # wait for parent to nuke us - end - end - - nr_proc.times do - fork do - rda.close - wrb.close - @to_close.concat((1..nr_sock).map { TCPSocket.new(TEST_ADDR, port) }) - wra.syswrite('.') - wra.close - rdb.sysread(1) # wait for parent to nuke us - end - end - - assert_equal('.' * (nr_proc * 2), rda.read(nr_proc * 2)) - - rda.close - stats = tcp_listener_stats(addrs) - expect = { addr => Raindrops::ListenStats[nr_sock * nr_proc, 0] } - assert_equal expect, stats - - @to_close << TCPSocket.new(TEST_ADDR, port) - stats = tcp_listener_stats(addrs) - expect = { addr => Raindrops::ListenStats[nr_sock * nr_proc, 1] } - assert_equal expect, stats - - if ENV["BENCHMARK"].to_i != 0 - require 'benchmark' - puts(Benchmark.measure{1000.times { tcp_listener_stats(addrs) }}) - end - - wrb.syswrite('.' * (nr_proc * 2)) # broadcast a wakeup - statuses = Process.waitall - statuses.each { |(_,status)| assert status.success?, status.inspect } - end if ENV["STRESS"].to_i != 0 -end if RUBY_PLATFORM =~ /linux/ && ipv6_enabled? diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_middleware.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_middleware.rb deleted file mode 100644 index f573225..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_middleware.rb +++ /dev/null @@ -1,64 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'tempfile' -require 'raindrops' -require 'socket' -$stderr.sync = $stdout.sync = true - -class TestLinuxMiddleware < Test::Unit::TestCase - - def setup - @resp_headers = { 'Content-Type' => 'text/plain', 'Content-Length' => '0' } - @response = [ 200, @resp_headers, [] ] - @app = lambda { |env| @response } - @to_close = [] - end - - def teardown - @to_close.each { |io| io.close unless io.closed? } - end - - def test_unix_listener - tmp = Tempfile.new("") - File.unlink(tmp.path) - @to_close << UNIXServer.new(tmp.path) - app = Raindrops::Middleware.new(@app, :listeners => [tmp.path]) - linux_extra = "#{tmp.path} active: 0\n#{tmp.path} queued: 0\n" - response = app.call("PATH_INFO" => "/_raindrops") - - expect = [ - 200, - { - "Content-Type" => "text/plain", - "Content-Length" => (22 + linux_extra.size).to_s - }, - [ - "calling: 0\nwriting: 0\n#{linux_extra}" \ - ] - ] - assert_equal expect, response - end - - def test_unix_listener_queued - tmp = Tempfile.new("") - File.unlink(tmp.path) - @to_close << UNIXServer.new(tmp.path) - @to_close << UNIXSocket.new(tmp.path) - app = Raindrops::Middleware.new(@app, :listeners => [tmp.path]) - linux_extra = "#{tmp.path} active: 0\n#{tmp.path} queued: 1\n" - response = app.call("PATH_INFO" => "/_raindrops") - - expect = [ - 200, - { - "Content-Type" => "text/plain", - "Content-Length" => (22 + linux_extra.size).to_s - }, - [ - "calling: 0\nwriting: 0\n#{linux_extra}" \ - ] - ] - assert_equal expect, response - end - -end if RUBY_PLATFORM =~ /linux/ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_tcp_info.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_tcp_info.rb deleted file mode 100644 index c947211..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_linux_tcp_info.rb +++ /dev/null @@ -1,68 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'tempfile' -require 'raindrops' -require 'socket' -require 'pp' -$stderr.sync = $stdout.sync = true -class TestLinuxTCP_Info < Test::Unit::TestCase - - TEST_ADDR = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - - # Linux kernel commit 5ee3afba88f5a79d0bff07ddd87af45919259f91 - TCP_INFO_useful_listenq = `uname -r`.strip >= '2.6.24' - - - def test_tcp_server - s = TCPServer.new(TEST_ADDR, 0) - rv = Raindrops::TCP_Info.new s - c = TCPSocket.new TEST_ADDR, s.addr[1] - tmp = Raindrops::TCP_Info.new s - TCP_INFO_useful_listenq and assert_equal 1, tmp.unacked - - assert_equal 0, rv.unacked - a = s.accept - tmp = Raindrops::TCP_Info.new s - assert_equal 0, tmp.unacked - before = tmp.object_id - - tmp.get!(s) - assert_equal before, tmp.object_id - - ensure - c.close if c - a.close if a - s.close - end - - def test_accessors - s = TCPServer.new TEST_ADDR, 0 - tmp = Raindrops::TCP_Info.new s - tcp_info_methods = tmp.methods - Object.new.methods - assert tcp_info_methods.size >= 32 - tcp_info_methods.each do |m| - next if m.to_sym == :get! - val = tmp.__send__ m - assert_kind_of Integer, val - assert val >= 0 - end - ensure - s.close - end - - def test_tcp_server_delayed - delay = 0.010 - delay_ms = (delay * 1000).to_i - s = TCPServer.new(TEST_ADDR, 0) - c = TCPSocket.new TEST_ADDR, s.addr[1] - c.syswrite "." - sleep(delay * 1.2) - a = s.accept - i = Raindrops::TCP_Info.new(a) - assert i.last_data_recv >= delay_ms, "#{i.last_data_recv} < #{delay_ms}" - ensure - c.close if c - a.close if a - s.close - end -end if RUBY_PLATFORM =~ /linux/ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware.rb deleted file mode 100644 index 56ce346..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware.rb +++ /dev/null @@ -1,128 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'raindrops' - -class TestMiddleware < Test::Unit::TestCase - - def setup - @resp_headers = { 'Content-Type' => 'text/plain', 'Content-Length' => '0' } - @response = [ 200, @resp_headers, [] ] - @app = lambda { |env| @response } - end - - def test_setup - app = Raindrops::Middleware.new(@app) - response = app.call({}) - assert_equal @response[0,2], response[0,2] - assert response.last.kind_of?(Raindrops::Middleware::Proxy) - assert response.last.object_id != app.object_id - tmp = [] - response.last.each { |y| tmp << y } - assert tmp.empty? - end - - def test_alt_stats - stats = Raindrops::Middleware::Stats.new - app = lambda { |env| - if (stats.writing == 0 && stats.calling == 1) - @app.call(env) - else - [ 500, @resp_headers, [] ] - end - } - app = Raindrops::Middleware.new(app, :stats => stats) - response = app.call({}) - assert_equal 0, stats.calling - assert_equal 1, stats.writing - assert_equal 200, response[0] - assert response.last.kind_of?(Raindrops::Middleware::Proxy) - tmp = [] - response.last.each do |y| - assert_equal 1, stats.writing - tmp << y - end - assert tmp.empty? - end - - def test_default_endpoint - app = Raindrops::Middleware.new(@app) - response = app.call("PATH_INFO" => "/_raindrops") - expect = [ - 200, - { "Content-Type" => "text/plain", "Content-Length" => "22" }, - [ "calling: 0\nwriting: 0\n" ] - ] - assert_equal expect, response - end - - def test_alt_endpoint - app = Raindrops::Middleware.new(@app, :path => "/foo") - response = app.call("PATH_INFO" => "/foo") - expect = [ - 200, - { "Content-Type" => "text/plain", "Content-Length" => "22" }, - [ "calling: 0\nwriting: 0\n" ] - ] - assert_equal expect, response - end - - def test_concurrent - rda, wra = IO.pipe - rdb, wrb = IO.pipe - app = lambda do |env| - wrb.close - wra.syswrite('.') - wra.close - - # wait until parent has run app.call for stats endpoint - rdb.read - @app.call(env) - end - app = Raindrops::Middleware.new(app) - - pid = fork { app.call({}) } - rdb.close - - # wait til child is running in app.call - assert_equal '.', rda.sysread(1) - rda.close - - response = app.call("PATH_INFO" => "/_raindrops") - expect = [ - 200, - { "Content-Type" => "text/plain", "Content-Length" => "22" }, - [ "calling: 1\nwriting: 0\n" ] - ] - assert_equal expect, response - wrb.close # unblock child process - assert Process.waitpid2(pid).last.success? - - # we didn't call close the body in the forked child, so it'll always be - # marked as writing, a real server would close the body - response = app.call("PATH_INFO" => "/_raindrops") - expect = [ - 200, - { "Content-Type" => "text/plain", "Content-Length" => "22" }, - [ "calling: 0\nwriting: 1\n" ] - ] - assert_equal expect, response - end - - def test_middleware_proxy_to_path_missing - app = Raindrops::Middleware.new(@app) - response = app.call({}) - body = response[2] - assert_kind_of Raindrops::Middleware::Proxy, body - assert ! body.respond_to?(:to_path) - assert body.respond_to?(:close) - orig_body = @response[2] - - def orig_body.to_path; "/dev/null"; end - assert body.respond_to?(:to_path) - assert_equal "/dev/null", body.to_path - - def orig_body.body; "this is a body"; end - assert body.respond_to?(:body) - assert_equal "this is a body", body.body - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware_unicorn.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware_unicorn.rb deleted file mode 100644 index 6730d4b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware_unicorn.rb +++ /dev/null @@ -1,37 +0,0 @@ -# -*- encoding: binary -*- -require "./test/rack_unicorn" -$stderr.sync = $stdout.sync = true - -class TestMiddlewareUnicorn < Test::Unit::TestCase - - def setup - @host = ENV["UNICORN_TEST_ADDR"] || "127.0.0.1" - @sock = TCPServer.new @host, 0 - @port = @sock.addr[1] - ENV["UNICORN_FD"] = @sock.fileno.to_s - @host_with_port = "#@host:#@port" - @opts = { :listeners => [ @host_with_port ] } - @addr_regexp = Regexp.escape @host_with_port - end - - def test_auto_listener - @app = Rack::Builder.new do - use Raindrops::Middleware - run Rack::Lobster.new - end - @srv = fork { Unicorn::HttpServer.new(@app, @opts).start.join } - - s = TCPSocket.new @host, @port - s.write "GET /_raindrops HTTP/1.0\r\n\r\n" - resp = s.read - _, body = resp.split(/\r\n\r\n/, 2) - assert_match %r{^#@addr_regexp active: 1$}, body - assert_match %r{^#@addr_regexp queued: 0$}, body - end - - def teardown - Process.kill :QUIT, @srv - _, status = Process.waitpid2 @srv - assert status.success? - end -end if defined?(Unicorn) && RUBY_PLATFORM =~ /linux/ diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware_unicorn_ipv6.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware_unicorn_ipv6.rb deleted file mode 100644 index 3d6862c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_middleware_unicorn_ipv6.rb +++ /dev/null @@ -1,37 +0,0 @@ -# -*- encoding: binary -*- -require "./test/rack_unicorn" -require "./test/ipv6_enabled" -$stderr.sync = $stdout.sync = true - -class TestMiddlewareUnicornIPv6 < Test::Unit::TestCase - - def setup - @host = ENV["TEST_HOST6"] || "::1" - sock = TCPServer.new @host, 0 - @port = sock.addr[1] - ENV["UNICORN_FD"] = sock.fileno.to_s - @host_with_port = "[#@host]:#@port" - @opts = { :listeners => [ @host_with_port ] } - @addr_regexp = Regexp.escape @host_with_port - end - - def test_auto_listener - @app = Rack::Builder.new do - use Raindrops::Middleware - run Rack::Lobster.new - end - @srv = fork { Unicorn::HttpServer.new(@app, @opts).start.join } - s = TCPSocket.new @host, @port - s.write "GET /_raindrops HTTP/1.0\r\n\r\n" - resp = s.read - _, body = resp.split(/\r\n\r\n/, 2) - assert_match %r{^#@addr_regexp active: 1$}, body - assert_match %r{^#@addr_regexp queued: 0$}, body - end - - def teardown - Process.kill :QUIT, @srv - _, status = Process.waitpid2 @srv - assert status.success? - end -end if defined?(Unicorn) && RUBY_PLATFORM =~ /linux/ && ipv6_enabled? diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_raindrops.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_raindrops.rb deleted file mode 100644 index 67089b7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_raindrops.rb +++ /dev/null @@ -1,165 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'raindrops' - -class TestRaindrops < Test::Unit::TestCase - - def test_raindrop_counter_max - assert_kind_of Integer, Raindrops::MAX - assert Raindrops::MAX > 0 - printf "Raindrops::MAX = 0x%x\n", Raindrops::MAX - end - - def test_raindrop_size - assert_kind_of Integer, Raindrops::SIZE - assert Raindrops::SIZE > 0 - puts "Raindrops::SIZE = #{Raindrops::SIZE}" - end - - def test_page_size - assert_kind_of Integer, Raindrops::PAGE_SIZE - assert Raindrops::PAGE_SIZE > Raindrops::SIZE - end - - def test_size_and_capa - rd = Raindrops.new(4) - assert_equal 4, rd.size - assert rd.capa >= rd.size - end - - def test_ary - rd = Raindrops.new(4) - assert_equal [0, 0, 0, 0] , rd.to_ary - end - - def test_incr_no_args - rd = Raindrops.new(4) - assert_equal 1, rd.incr(0) - assert_equal [1, 0, 0, 0], rd.to_ary - end - - def test_incr_args - rd = Raindrops.new(4) - assert_equal 6, rd.incr(3, 6) - assert_equal [0, 0, 0, 6], rd.to_ary - end - - def test_decr_args - rd = Raindrops.new(4) - rd[3] = 6 - assert_equal 5, rd.decr(3, 1) - assert_equal [0, 0, 0, 5], rd.to_ary - end - - def test_incr_shared - rd = Raindrops.new(2) - 5.times do - pid = fork { rd.incr(1) } - _, status = Process.waitpid2(pid) - assert status.success? - end - assert_equal [0, 5], rd.to_ary - end - - def test_incr_decr - rd = Raindrops.new(1) - fork { 1000000.times { rd.incr(0) } } - 1000.times { rd.decr(0) } - statuses = Process.waitall - statuses.each { |pid, status| assert status.success? } - assert_equal [999000], rd.to_ary - end - - def test_bad_incr - rd = Raindrops.new(1) - assert_raises(ArgumentError) { rd.incr(-1) } - assert_raises(ArgumentError) { rd.incr(2) } - assert_raises(ArgumentError) { rd.incr(0xffffffff) } - end - - def test_dup - @rd = Raindrops.new(1) - rd = @rd.dup - assert_equal 1, @rd.incr(0) - assert_equal 1, rd.incr(0) - assert_equal 2, rd.incr(0) - assert_equal 2, rd[0] - assert_equal 1, @rd[0] - end - - def test_clone - @rd = Raindrops.new(1) - rd = @rd.clone - assert_equal 1, @rd.incr(0) - assert_equal 1, rd.incr(0) - assert_equal 2, rd.incr(0) - assert_equal 2, rd[0] - assert_equal 1, @rd[0] - end - - def test_big - expect = (1..256).map { 0 } - rd = Raindrops.new(256) - assert_equal expect, rd.to_ary - assert_nothing_raised { rd[255] = 5 } - assert_equal 5, rd[255] - assert_nothing_raised { rd[2] = 2 } - - expect[255] = 5 - expect[2] = 2 - assert_equal expect, rd.to_ary - end - - def test_resize - rd = Raindrops.new(4) - assert_equal 4, rd.size - assert_equal rd.capa, rd.size = rd.capa - assert_equal rd.capa, rd.to_ary.size - assert_equal 0, rd[rd.capa - 1] - assert_equal 1, rd.incr(rd.capa - 1) - assert_raises(ArgumentError) { rd[rd.capa] } - end - - def test_resize_mremap - rd = Raindrops.new(4) - assert_equal 4, rd.size - old_capa = rd.capa - rd.size = rd.capa + 1 - assert_equal old_capa * 2, rd.capa - - # mremap() is currently broken with MAP_SHARED - # https://bugzilla.kernel.org/show_bug.cgi?id=8691 - assert_equal 0, rd[old_capa] - assert_equal rd.capa, rd.to_ary.size - assert_equal 0, rd[rd.capa - 1] - assert_equal 1, rd.incr(rd.capa - 1) - assert_raises(ArgumentError) { rd[rd.capa] } - rescue RangeError - end # if RUBY_PLATFORM =~ /linux/ - - def test_evaporate - rd = Raindrops.new 1 - assert_nil rd.evaporate! - assert_raises(StandardError) { rd.evaporate! } - end - - def test_evaporate_with_fork - tmp = Raindrops.new 2 - pid = fork do - tmp.incr 0 - exit(tmp.evaporate! == nil) - end - _, status = Process.waitpid2(pid) - assert status.success? - assert_equal [ 1, 0 ], tmp.to_ary - tmp.incr 1 - assert_equal [ 1, 1 ], tmp.to_ary - pid = fork do - tmp.incr 1 - exit([ 1, 2 ] == tmp.to_ary) - end - _, status = Process.waitpid2(pid) - assert status.success? - assert_equal [ 1, 2 ], tmp.to_ary - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_raindrops_gc.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_raindrops_gc.rb deleted file mode 100644 index 2098129..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_raindrops_gc.rb +++ /dev/null @@ -1,38 +0,0 @@ -# -*- encoding: binary -*- -require 'test/unit' -require 'raindrops' - -class TestRaindropsGc < Test::Unit::TestCase - - # we may need to create more garbage as GC may be less aggressive - # about expiring things. This is completely unrealistic code, - # though... - def test_gc - assert_nothing_raised do - 1000000.times { |i| Raindrops.new(24); [] } - end - end - - def test_gc_postfork - tmp = Raindrops.new 2 - pid = fork do - 1000000.times do - tmp = Raindrops.new 2 - tmp.to_ary - end - end - _, status = Process.waitpid2(pid) - assert status.success? - assert_equal [ 0, 0 ], tmp.to_ary - tmp.incr 1 - assert_equal [ 0, 1 ], tmp.to_ary - pid = fork do - tmp.incr 1 - exit([ 0, 2 ] == tmp.to_ary) - end - _, status = Process.waitpid2(pid) - assert status.success? - assert_equal [ 0, 2 ], tmp.to_ary - end -end if !defined?(RUBY_ENGINE) || RUBY_ENGINE == "ruby" && - ENV["STRESS"].to_i != 0 diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_struct.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_struct.rb deleted file mode 100644 index 9792d5b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_struct.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'test/unit' -require 'raindrops' - -class TestRaindrops < Test::Unit::TestCase - - def test_struct_new - @rw = Raindrops::Struct.new(:r, :w) - assert @rw.kind_of?(Class) - end - - TMP = Raindrops::Struct.new(:r, :w) - - def test_init_basic - tmp = TMP.new - assert_equal 0, tmp.r - assert_equal 1, tmp.incr_r - assert_equal 1, tmp.r - assert_equal({ :r => 1, :w => 0 }, tmp.to_hash) - - assert_equal 1, tmp[0] - assert_equal 0, tmp[1] - assert_equal [ :r, :w ], TMP::MEMBERS - end - - def test_init - tmp = TMP.new(5, 6) - assert_equal({ :r => 5, :w => 6 }, tmp.to_hash) - end - - def test_dup - a = TMP.new(5, 6) - b = a.dup - assert_equal({ :r => 5, :w => 6 }, b.to_hash) - assert_nothing_raised { 4.times { b.decr_r } } - assert_equal({ :r => 1, :w => 6 }, b.to_hash) - assert_equal({ :r => 5, :w => 6 }, a.to_hash) - end - - class Foo < Raindrops::Struct.new(:a, :b, :c, :d) - def to_ary - @raindrops.to_ary - end - - def hello - "world" - end - end - - def test_subclass - assert_equal [0, 0, 0, 0], Foo.new.to_ary - assert_equal "world", Foo.new.hello - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_watcher.rb b/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_watcher.rb deleted file mode 100644 index 70e8e75..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/raindrops-0.13.0/test/test_watcher.rb +++ /dev/null @@ -1,181 +0,0 @@ -# -*- encoding: binary -*- -require "test/unit" -require "rack" -require "raindrops" - -class TestWatcher < Test::Unit::TestCase - TEST_ADDR = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - def check_headers(headers) - %w(X-Count X-Std-Dev X-Min X-Max X-Mean - X-Outliers-Low X-Outliers-Low X-Last-Reset).each { |x| - assert_kind_of String, headers[x], "#{x} missing" - } - end - - def teardown - @app.shutdown - @ios.each { |io| io.close unless io.closed? } - end - - def setup - @ios = [] - @srv = TCPServer.new TEST_ADDR, 0 - @ios << @srv - @port = @srv.addr[1] - @client = TCPSocket.new TEST_ADDR, @port - @addr = "#{TEST_ADDR}:#{@port}" - @ios << @client - @app = Raindrops::Watcher.new :delay => 0.001 - @req = Rack::MockRequest.new @app - end - - def test_index - resp = @req.get "/" - assert_equal 200, resp.status.to_i - t = Time.parse resp.headers["Last-Modified"] - assert_in_delta Time.now.to_f, t.to_f, 2.0 - end - - def test_active_txt - resp = @req.get "/active/#@addr.txt" - assert_equal 200, resp.status.to_i - assert_equal "text/plain", resp.headers["Content-Type"] - check_headers(resp.headers) - end - - def test_invalid - assert_nothing_raised do - @req.get("/active/666.666.666.666%3A666.txt") - @req.get("/queued/666.666.666.666%3A666.txt") - @req.get("/active/666.666.666.666%3A666.html") - @req.get("/queued/666.666.666.666%3A666.html") - end - addr = @app.instance_eval do - @peak_active.keys + @peak_queued.keys + - @resets.keys + @active.keys + @queued.keys - end - assert addr.grep(/666\.666\.666\.666/).empty?, addr.inspect - end - - def test_active_html - resp = @req.get "/active/#@addr.html" - assert_equal 200, resp.status.to_i - assert_equal "text/html", resp.headers["Content-Type"] - check_headers(resp.headers) - end - - def test_queued_txt - resp = @req.get "/queued/#@addr.txt" - assert_equal 200, resp.status.to_i - assert_equal "text/plain", resp.headers["Content-Type"] - check_headers(resp.headers) - end - - def test_queued_html - resp = @req.get "/queued/#@addr.html" - assert_equal 200, resp.status.to_i - assert_equal "text/html", resp.headers["Content-Type"] - check_headers(resp.headers) - end - - def test_reset - resp = @req.post "/reset/#@addr" - assert_equal 302, resp.status.to_i - end - - def test_tail - env = @req.class.env_for "/tail/#@addr.txt" - status, headers, body = @app.call env - assert_equal "text/plain", headers["Content-Type"] - assert_equal 200, status.to_i - tmp = [] - body.each do |x| - assert_kind_of String, x - tmp << x - break if tmp.size > 1 - end - end - - def test_tail_queued_min - env = @req.class.env_for "/tail/#@addr.txt?queued_min=1" - status, headers, body = @app.call env - assert_equal "text/plain", headers["Content-Type"] - assert_equal 200, status.to_i - tmp = [] - body.each do |x| - tmp = TCPSocket.new TEST_ADDR, @port - @ios << tmp - assert_kind_of String, x - assert_equal 1, x.strip.split(/\s+/).last.to_i - break - end - end - - def test_x_current_header - env = @req.class.env_for "/active/#@addr.txt" - status, headers, body = @app.call(env) - assert_equal "0", headers["X-Current"], headers.inspect - - env = @req.class.env_for "/queued/#@addr.txt" - status, headers, body = @app.call(env) - assert_equal "1", headers["X-Current"], headers.inspect - - @ios << @srv.accept - sleep 0.1 - - env = @req.class.env_for "/queued/#@addr.txt" - status, headers, body = @app.call(env) - assert_equal "0", headers["X-Current"], headers.inspect - - env = @req.class.env_for "/active/#@addr.txt" - status, headers, body = @app.call(env) - assert_equal "1", headers["X-Current"], headers.inspect - end - - def test_peaks - env = @req.class.env_for "/active/#@addr.txt" - status, headers, body = @app.call(env.dup) - start = headers["X-First-Peak-At"] - assert headers["X-First-Peak-At"], headers.inspect - assert headers["X-Last-Peak-At"], headers.inspect - assert_nothing_raised { Time.parse(headers["X-First-Peak-At"]) } - assert_nothing_raised { Time.parse(headers["X-Last-Peak-At"]) } - before = headers["X-Last-Peak-At"] - - env = @req.class.env_for "/queued/#@addr.txt" - status, headers, body = @app.call(env) - assert_nothing_raised { Time.parse(headers["X-First-Peak-At"]) } - assert_nothing_raised { Time.parse(headers["X-Last-Peak-At"]) } - assert_equal before, headers["X-Last-Peak-At"], "should not change" - - sleep 2 - env = @req.class.env_for "/active/#@addr.txt" - status, headers, body = @app.call(env.dup) - assert_equal before, headers["X-Last-Peak-At"], headers.inspect - - @ios << @srv.accept - begin - @srv.accept_nonblock - assert false, "we should not get here" - rescue => e - assert_kind_of Errno::EAGAIN, e - end - sleep 0.1 - env = @req.class.env_for "/queued/#@addr.txt" - status, headers, body = @app.call(env.dup) - assert headers["X-Last-Peak-At"], headers.inspect - assert_nothing_raised { Time.parse(headers["X-Last-Peak-At"]) } - assert before != headers["X-Last-Peak-At"] - - queued_before = headers["X-Last-Peak-At"] - - sleep 2 - - env = @req.class.env_for "/queued/#@addr.txt" - status, headers, body = @app.call(env) - assert_equal "0", headers["X-Current"] - assert_nothing_raised { Time.parse(headers["X-Last-Peak-At"]) } - assert_equal queued_before, headers["X-Last-Peak-At"], "should not change" - assert_equal start, headers["X-First-Peak-At"] - end -end if RUBY_PLATFORM =~ /linux/ diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/License.txt b/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/License.txt deleted file mode 100644 index 02bc06c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/License.txt +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2009 Chad Humphries, David Chelimsky -Copyright (c) 2006 David Chelimsky, The RSpec Development Team -Copyright (c) 2005 Steven Baker - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/README.md b/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/README.md deleted file mode 100644 index a0d6fc1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# RSpec - -Behaviour Driven Development for Ruby - -# Description - -rspec is a meta-gem, which depends on the rspec-core, rspec-expectations -and rspec-mocks gems. Each of these can be installed separately and actived in -isolation with the `gem` command. Among other benefits, this allows you to use -rspec-expectations, for example, in Test::Unit::TestCase if you happen to -prefer that style. - -Conversely, if you like RSpec's approach to declaring example groups and -examples (`describe` and `it`) but prefer Test::Unit assertions and mocha, rr -or flexmock for mocking, you'll be able to do that without having to load the -components of rspec that you're not using. - -## Documentation - -### rspec-core - -* [Cucumber features](http://relishapp.com/rspec/rspec-core) -* [RDoc](http://rubydoc.info/gems/rspec-core/frames) - -### rspec-expectations - -* [Cucumber features](http://relishapp.com/rspec/rspec-expectations) -* [RDoc](http://rubydoc.info/gems/rspec-expectations/frames) - -### rspec-mocks - -* [Cucumber features](http://relishapp.com/rspec/rspec-mocks) -* [RDoc](http://rubydoc.info/gems/rspec-mocks/frames) - -## Install - - gem install rspec - -## Contribute - -* [http://github.com/rspec/rspec-dev](http://github.com/rspec/rspec-dev) - -## Also see - -* [http://github.com/rspec/rspec-core](http://github.com/rspec/rspec-core) -* [http://github.com/rspec/rspec-expectations](http://github.com/rspec/rspec-expectations) -* [http://github.com/rspec/rspec-mocks](http://github.com/rspec/rspec-mocks) diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/lib/rspec.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/lib/rspec.rb deleted file mode 100644 index 36149e0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/lib/rspec.rb +++ /dev/null @@ -1,3 +0,0 @@ -require 'rspec/core' -require 'rspec/version' - diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/lib/rspec/version.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/lib/rspec/version.rb deleted file mode 100644 index a94bea2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-3.0.0/lib/rspec/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module RSpec # :nodoc: - module Version # :nodoc: - STRING = '3.0.0' - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/.document b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/.document deleted file mode 100644 index 050e204..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/.document +++ /dev/null @@ -1,5 +0,0 @@ -lib/**/*.rb -- -README.md -License.txt -Changelog.md diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/.yardopts b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/.yardopts deleted file mode 100644 index 0feceb4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/.yardopts +++ /dev/null @@ -1,7 +0,0 @@ ---exclude features ---no-private ---markup markdown ---default-return void -- -Changelog.md -License.txt diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/Changelog.md b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/Changelog.md deleted file mode 100644 index 9fa6513..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/Changelog.md +++ /dev/null @@ -1,1478 +0,0 @@ -### 3.0.3 / 2014-07-21 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.2...v3.0.3) - -Bug Fixes: - -* Properly convert both parts of a description into strings before - concatenation. (@nicklink483, #1636) -* Exclude the working directory when figuring out folders to ignore. - (Jon Rowe, Myron Marston, #1616) -* Allow `::RSpec::Core::Notifications::FailedExampleNotification#message_lines` - to be accessed without a colouriser. (@tomykaira, #1637) - -### 3.0.2 / 2014-06-19 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.1...v3.0.2) - -Bug Fixes: - -* Fix regression in CLI option handling that prevented `--tag slow` - passed at the command line from overriding `--tag ~slow` in `.rspec`. - (Colin Jones, #1602) -* Fix metadata `:example_group` deprecation warning so that it gets - issued at the call site of the configuration that specified it as - a filter rather than later when an example group is defined. - (Myron Marston, #1562) -* Make the line that is printed when a shared example group fails indicating - where the concrete example group is white, separating it from the stack trace - that is produced for the failure. (Sam Phippen, Jon Rowe, #1606) - -### 3.0.1 / 2014-06-12 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.0...v3.0.1) - -Bug Fixes: - -* Fix a couple ruby warnings caused by rspec-core when loaded. - (Prem Sichanugrist, #1584) -* Example groups named `Config` will no longer cause a Ruby warning to be - issued. (Jimmy Cuadra, #1580) - -### 3.0.0 / 2014-06-01 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.0.rc1...v3.0.0) - -Bug Fixes: - -* Fix `BaseTextFormatter` so that it does not re-close a closed output - stream. (Myron Marston) -* Fix regression in metadata that caused the metadata hash of a top-level - example group to have a `:parent_example_group` key even though it has - no parent example group. (Myron Marston) - -Enhancements: - -* Alter the default `spec_helper.rb` to no longer recommend - `config.full_backtrace = true` see #1536 for discussion. (Jon Rowe) - -### 3.0.0.rc1 / 2014-05-18 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.0.beta2...v3.0.0.rc1) - -Breaking Changes for 3.0.0: - -* Change `described_class` so that in a nested group like `describe - MyClass`, it returns `MyClass` rather than the outer group's described - class. (Myron Marston) -* Refactor filter manager so that it no longer subclasses Hash and has a - tighter, more domain-specific interface. (Sergey Pchelincev) -* Remove legacy colours definitions from `BaseTextFormatter`. (Jon Rowe) -* Remove console color definitions from `BaseTextFormatter`. (Jon Rowe) -* Restructure example group metadata so that the computed keys are - exposed directly off of the metadata hash rather than being on - a nested `:example_group` subhash. In addition, the parent example - group metadata is now available as `[:parent_example_group]` rather - than `[:example_group][:example_group]`. Deprecated access via the - old key structure is still provided. (Myron Marston) -* Remove `:describes` metadata key. It duplicates `:described_class` - for no good reason. Deprecated access via `:describes` is still - provided. (Myron Marston) -* Rename `:example_group_block` metadata key to `:block`. - (Myron Marston) -* Remove deprecated `RSpec::Core::Example#options`. (Myron Marston) -* Move `BaseTextFormatter#colorize_summary` to `SummaryNotification#colorize_with` - (Jon Rowe). -* `describe some_hash` treated `some_hash` as metadata in RSpec 2.x but - will treat it as the described object in RSpec 3.0. Metadata must - always come after the description args. (Myron Marston) -* Remove deprecated `display_name` alias of `ExampleGroup.description`. - (Myron Marston) -* Remove deprecated `describes` alias of `ExampleGroup.described_class`. - (Myron Marston) -* Remove deprecated `RSpec::Core::ExampleGroup.alias_it_behaves_like_to`. - Use `RSpec::Core::Configuration#alias_it_behaves_like_to` instead. - (Myron Marston) -* Remove deprecated `RSpec::Core::ExampleGroup.alias_example_to`. - Use `RSpec::Core::Configuration#alias_example_to` instead. - (Myron Marston) -* Removed `focused` example alias and change example/group aliases - `fit`, `focus`, `fcontext` and `fdescribe` to no longer include - `:focused => true` metadata. They only contain `:focus => true` - metadata now. This means that you will need to filter them with - `filter_run :focus`, not `filter_run :focused`. (Myron Marston) -* Remove `--line-number` filtering. It's semantically dubious since it's - a global filter (potentially applied to multiple files) but there's no - meaningful connection between the same line number in multiple files. - Instead use the `rspec path/to/spec.rb:23:46` form, which is terser - and makes more sense as it is scoped to a file. (Myron Marston) -* Remove `--default_path` as an alias for `--default-path`. (Jon Rowe) -* Remove deprecated `share_examples_for`. There's still - `shared_examples` and `shared_examples_for`. (Myron Marston) -* Rename `RSpec::Core::Configuration#warnings` to - `RSpec::Core::Configuration#warnings?` since it's a boolean flag. - (Myron Marston) -* RSpec's global state is no longer reset after a spec run. This gives - more flexibility to alternate runners to decide when and if they - want the state reset. Alternate runners are now responsible for - calling this (or doing a similar reset) if they are going to run - the spec suite multiple times in the same process. (Sam Phippen) -* Merge `RSpec::Core::CommandLine` (never formally declared public) - into `RSpec::Core::Runner`. (Myron Marston) -* Remove `color_enabled` as an alias of `color`. (Jon Rowe) -* Remove `backtrace_cleaner` as an alias of `backtrace_formatter`. (Jon Rowe) -* Remove `filename_pattern` as an alias of `pattern`. (Jon Rowe) -* Extract support for legacy formatters to `rspec-legacy_formatters`. (Jon Rowe) -* `RSpec::Configuration#formatters` now returns a dup to prevent mutation. (Jon Rowe) -* Replace `stdlib` as an available expectation framework with `test_unit` and - `minitest`. (Aaron Kromer) -* Remove backtrace formatting helpers from `BaseTextFormatter`. (Jon Rowe) -* Extract profiler support to `ProfileFormatter` and `ProfileNotification`. - Formatters should implement `dump_profile` if they wish to respond to `--profile`. - (Jon Rowe) -* Extract remaining formatter state to reporter and notifications. Introduce - `ExamplesNotification` to share information about examples that was previously - held in `BaseFormatter`. (Jon Rowe) - -Enhancements: - -* Add `config.default_formatter` attribute, which can be used to set a - formatter which will only be used if no other formatter is set - (e.g. via `--formatter`). (Myron Marston) -* Support legacy colour definitions in `LegacyFormatterAdaptor`. (Jon Rowe) -* Migrate `execution_result` (exposed by metadata) from a hash to a - first-class object with appropriate attributes. `status` is now - stored and returned as a symbol rather than a string. It retains - deprecated hash behavior for backwards compatibility. (Myron Marston) -* Provide console code helper for formatters. (Jon Rowe) -* Use raw ruby hashes for the metadata hashes rather than a subclass of - a hash. Computed metadata entries are now computed in advance rather - than being done lazily on first access. (Myron Marston) -* Add `:block` metadata entry to the example metadata, bringing - parity with `:block` in the example group metadata. (Myron Marston) -* Add `fspecify` and `fexample` as aliases of `specify` and `example` - with `:focus => true` metadata for parity with `fit`. (Myron Marston) -* Add legacy support for `colorize_summary`. (Jon Rowe) -* Restructure runner so it can be more easily customized in a subclass - for an alternate runner. (Ben Hoskings) -* Document `RSpec::Core::ConfigurationOptions` as an officially - supported public API. (Myron Marston) -* Add `--deprecation-out` CLI option which directs deprecation warnings - to the named file. (Myron Marston) -* Minitest 5 compatability for `expect_with :stdlib` (now available as - `expect_with :minitest`). (Xavier Shay) -* Reporter now notifies formatters of the load time of RSpec and your - specs via `StartNotification` and `SummaryNotification`. (Jon Rowe) -* Add `disable_monkey_patching!` config option that disables all monkey - patching from whatever pieces of RSpec you use. (Alexey Fedorov) -* Add `Pathname` support for setting all output streams. (Aaron Kromer) -* Add `config.define_derived_metadata`, which can be used to apply - additional metadata to all groups or examples that match a given - filter. (Myron Marston) -* Provide formatted and colorized backtraces via `FailedExampleNotification` - and send `PendingExampleFixedNotifications` when the error is due to a - passing spec you expect to fail. (Jon Rowe) -* Add `dump_profile` to formatter API to allow formatters to implement - support for `--profile`. (Jon Rowe) -* Allow colourising text via `ConsoleCodes` with RSpec 'states' - (e.g. `:success`, `:failure`) rather than direct colour codes. (Jon Rowe) -* Expose `fully_formatted` methods off the formatter notification objects - that make it easy for a custom formatter to produce formatted output - like rspec-core's. (Myron Marston) - -Bug Fixes: - -* Fix `spec_helper.rb` file generated by `rspec --init` so that the - recommended settings correctly use the documentation formatter - when running one file. (Myron Marston) -* Fix ordering problem where descriptions were generated after - tearing down mocks, which resulted in unexpected exceptions. - (Bradley Schaefer, Aaron Kromer, Andrey Savchenko) -* Allow a symbol to be used as an implicit subject (e.g. `describe - :foo`). (Myron Marston) -* Prevent creating an isolated context (i.e. using `RSpec.describe`) when - already inside a context. There is no reason to do this, and it could - potentially cause unexpected bugs. (Xavier Shay) -* Fix shared example group scoping so that when two shared example - groups share the same name at different levels of nested contexts, - the one in the nearest context is used. (Myron Marston) -* Fix `--warnings` option so that it enables warnings immediately so - that it applies to files loaded by `--require`. (Myron Marston) -* Issue a warning when you set `config.deprecation_stream` too late for - it to take effect because the reporter has already been setup. (Myron Marston) -* Add the full `RSpec::Core::Example` interface to the argument yielded - to `around` hooks. (Myron Marston) -* Line number always takes precendence when running specs with filters. - (Xavier Shay) -* Ensure :if and :unless metadata filters are treated as a special case - and are always in-effect. (Bradley Schaefer) -* Ensure the currently running installation of RSpec is used when - the rake task shells out to `rspec`, even if a newer version is also - installed. (Postmodern) -* Using a legacy formatter as default no longer causes an infinite loop. - (Xavier Shay) - -### 3.0.0.beta2 / 2014-02-17 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v3.0.0.beta1...v3.0.0.beta2) - -Breaking Changes for 3.0.0: - -* Make `mock_with` option more strict. Strings are no longer supported - (e.g. `mock_with "mocha"`) -- use a symbol instead. Also, unrecognized - values will now result in an error rather than falling back to the - null mocking adapter. If you want to use the null mocking adapter, - use `mock_with :nothing` (as has been documented for a long time). - (Myron Marston) -* Remove support for overriding RSpec's built-in `:if` and `:unless` - filters. (Ashish Dixit) -* Custom formatters are now required to call - `RSpec::Core::Formatters.register(formatter_class, *notifications)` - where `notifications` is the list of events the formatter wishes to - be notified about. Notifications are handled by methods matching the - names on formatters. This allows us to add or remove notifications - without breaking existing formatters. (Jon Rowe) -* Change arguments passed to formatters. Rather than passing multiple - arguments (which limits are ability to add additional arguments as - doing so would break existing formatters), we now pass a notification - value object that exposes the same data via attributes. This will - allow us to add new bits of data to a notification event without - breaking existing formatters. (Jon Rowe) -* Remove support for deprecated `:alias` option for - `RSpec.configuration.add_setting`. (Myron Marston) -* Remove support for deprecated `RSpec.configuration.requires = [...]`. - (Myron Marston) -* Remove support for deprecated `--formatter` CLI option. (Myron Marston) -* Remove support for deprecated `--configure` CLI option. (Myron Marston) -* Remove support for deprecated `RSpec::Core::RakeTask#spec_opts=`. - (Myron Marston) -* An example group level `pending` block or `:pending` metadata now executes - the example and cause a failure if it passes, otherwise it will be pending if - it fails. The old "never run" behaviour is still used for `xexample`, `xit`, - and `xspecify`, or via a new `skip` method or `:skip` metadata option. - (Xavier Shay) -* After calling `pending` inside an example, the remainder of the example will - now be run. If it passes a failure is raised, otherwise the example is marked - pending. The old "never run" behaviour is provided a by a new `skip` method. - (Xavier Shay) -* Pending blocks inside an example have been removed as a feature with no - direct replacement. Use `skip` or `pending` without a block. (Xavier Shay) -* Pending statement is no longer allowed in `before(:all)` hooks. Use `skip` - instead. (Xavier Shay) -* Remove `show_failures_in_pending_blocks` configuration option. (Xavier Shay) -* Remove support for specifying the documentation formatter using - 's', 'n', 'spec' or 'nested'. (Jon Rowe) - -Enhancements: - -* Add example run time to JSON formatter output. (Karthik Kastury) -* Add more suggested settings to the files generated by - `rspec --init`. (Myron Marston) -* Add `config.alias_example_group_to`, which can be used to define a - new method that defines an example group with the provided metadata. - (Michi Huber) -* Add `xdescribe` and `xcontext` as shortcuts to skip an example group. - (Myron Marston) -* Add `fdescribe` and `fcontext` as shortcuts to focus an example group. - (Myron Marston) -* Don't autorun specs via `#at_exit` by default. `require 'rspec/autorun'` - is only needed when running specs via `ruby`, as it always has been. - Running specs via `rake` or `rspec` are both unaffected. (Ben Hoskings) -* Add `expose_dsl_globally` config option, defaulting to true. When disabled - it will remove the monkey patches rspec-core adds to `main` and `Module` - (e.g. `describe`, `shared_examples_for`, etc). (Jon Rowe) -* Expose RSpec DSL entry point methods (`describe`, - `shared_examples_for`, etc) on the `RSpec` constant. Intended for use - when `expose_dsl_globally` is set to `false`. (Jon Rowe) -* For consistency, expose all example group aliases (including - `context`) on the `RSpec` constant. If `expose_dsl_globally` is set to - `true`, also expose them on `main` and `Module`. Historically, only `describe` - was exposed. (Jon Rowe, Michi Huber) -* Add hook scope `:example` as an alias for `:each`, and `:context` as an alias - for `:all`. (John Feminella) - -Bug Fixes: - -* Fix failure (undefined method `path`) in end-of-run summary - when `raise_errors_for_deprecations!` is configured. (Myron Marston) -* Issue error when attempting to use `-i` or `--I` on command line, - too close to `-I` to be considered short hand for `--init`. (Jon Rowe) -* Prevent adding formatters to an output target if the same - formatter has already been added to that output. (Alex Peattie) -* Allow a matcher-generated example description to be used when - the example is pending. (Myron Marston) -* Ensure the configured `failure_exit_code` is used by the rake - task when there is a failure. (Jon Rowe) -* Restore behaviour whereby system exclusion filters take priority over working - directory (was broken in beta1). (Jon Rowe) -* Prevent RSpec mangling file names that have substrings containing `line_number` - or `default_path`. (Matijs van Zuijlen) - -### 3.0.0.beta1 / 2013-11-07 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.1...v3.0.0.beta1) - -Breaking Changes for 3.0.0: - -* Remove explicit support for 1.8.6. (Jon Rowe) -* Remove `RSpec::Core::ExampleGroup#example` and - `RSpec::Core::ExampleGroup#running_example` methods. If you need - access to the example (e.g. to get its metadata), use a block arg - instead. (David Chelimsky) -* Remove `TextMateFormatter`, it has been moved to `rspec-tmbundle`. - (Aaron Kromer) -* Remove RCov integration. (Jon Rowe) -* Remove deprecated support for RSpec 1 constructs (Myron Marston): - * The `Spec` and `Rspec` constants (rather than `RSpec`). - * `Spec::Runner.configure` rather than `RSpec.configure`. - * `Rake::SpecTask` rather than `RSpec::Core::RakeTask`. -* Remove deprecated support for `share_as`. (Myron Marston) -* Remove `--debug` option (and corresponding option on - `RSpec::Core::Configuration`). Instead, use `-r` to - load whichever debugger gem you wish to use (e.g. `ruby-debug`, - `debugger`, or `pry`). (Myron Marston) -* Extract Autotest support to a seperate gem. (Jon Rowe) -* Raise an error when a `let` or `subject` declaration is - accessed in a `before(:all)` or `after(:all)` hook. (Myron Marston) -* Extract `its` support to a separate gem. (Peter Alfvin) -* Disallow use of a shared example group from sibling contexts, making them - fully isolated. 2.14 and 2.99 allowed this but printed a deprecation warning. - (Jon Rowe) -* Remove `RSpec::Core::Configuration#output` and - `RSpec::Core::Configuration#out` aliases of - `RSpec::Core::Configuration#output_stream`. (Myron Marston) -* Remove legacy ordering APIs deprecated in 2.99.0.beta1. (Myron - Marston) - -Enhancements: - -* Replace unmaintained syntax gem with coderay gem. (Xavier Shay) -* Times in profile output are now bold instead of `failure_color`. - (Matthew Boedicker) -* Add `--no-fail-fast` command line option. (Gonzalo Rodríguez-Baltanás Díaz) -* Runner now considers the local system ip address when running under Drb. - (Adrian CB) -* JsonFormatter now includes `--profile` information. (Alex / @MasterLambaster) -* Always treat symbols passed as metadata args as hash - keys with true values. RSpec 2 supported this with the - `treat_symbols_as_metadata_keys_with_true_values` but - now this behavior is always enabled. (Myron Marston) -* Add `--dry-run` option, which prints the formatter output - of your suite without running any examples or hooks. - (Thomas Stratmann, Myron Marston) -* Document the configuration options and default values in the `spec_helper.rb` - file that is generated by RSpec. (Parker Selbert) -* Give generated example group classes a friendly name derived - from the docstring, rather than something like "Nested_2". - (Myron Marston) -* Avoid affecting randomization of user code when shuffling - examples so that users can count on their own seeds - working. (Travis Herrick) -* Ordering is no longer a single global property of the test suite. - Each group can pick an ordering using `:order` metadata. (Andy - Lindeman, Sam Phippen, Myron Marston) -* Allow named custom ordering strategies to be registered, which can - then be used on individual example groups. (Andy Lindeman, Sam - Phippen, Myron Marston) - -Deprecations: - -* `treat_symbols_as_metadata_keys_with_true_values` is deprecated and no - longer has an affect now that the behavior it enabled is always - enabled. (Myron Marston) - -### 2.99.1 / 2014-06-19 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0...v2.99.1) - -Bug Fixes: - -* Add missing deprecation warning for when `RSpec::Core::Runner` is used - multiple times in the same process. In 2.x RSpec's global state was - automatically cleared between runs but in 3.0 you need to call `RSpec.reset` - manually in these situations. (Sam Phippen, #1587) -* Prevent deprecation being accidentally issues when doubles used with `be_` - matchers due to automatically generated descriptions. (Jon Rowe, #1573) -* Load `rspec/core` when loading `rspec/core/rake_task` to ensure we can - issue deprecations correctly. (Jon Rowe, #1612) - -### 2.99.0 / 2014-06-01 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0.rc1...v2.99.0) - -Bug Fixes: - -* Fix `BaseTextFormatter` so that it does not re-close a closed output - stream. (Myron Marston) -* Use `RSpec::Configuration#backtrace_exclusion_patterns` rather than the - deprecated `RSpec::Configuration#backtrace_clean_patterns` when mocking - with rr. (David Dollar) - -### 2.99.0.rc1 / 2014-05-18 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0.beta2...v2.99.0.rc1) - -Enhancements: - -* Add `--deprecation-out` CLI option which directs deprecation warnings - to the named file. (Myron Marston) -* Backport support for `skip` in metadata to skip execution of an example. - (Xavier Shay, #1472) -* Add `Pathname` support for setting all output streams. (Aaron Kromer) -* Add `test_unit` and `minitest` expectation frameworks. (Aaron Kromer) - -Deprecations: - -* Deprecate `RSpec::Core::Pending::PendingDeclaredInExample`, use - `SkipDeclaredInExample` instead. (Xavier Shay) -* Issue a deprecation when `described_class` is accessed from within - a nested `describe ` example group, since `described_class` - will return the innermost described class in RSpec 3 rather than the - outermost described class, as it behaved in RSpec 2. (Myron Marston) -* Deprecate `RSpec::Core::FilterManager::DEFAULT_EXCLUSIONS`, - `RSpec::Core::FilterManager::STANDALONE_FILTERS` and use of - `#empty_without_conditional_filters?` on those filters. (Sergey Pchelincev) -* Deprecate `RSpec::Core::Example#options` in favor of - `RSpec::Core::Example#metadata`. (Myron Marston) -* Issue warning when passing a symbol or hash to `describe` or `context` - as the first argument. In RSpec 2.x this would be treated as metadata - but in RSpec 3 it'll be treated as the described object. To continue - having it treated as metadata, pass a description before the symbol or - hash. (Myron Marston) -* Deprecate `RSpec::Core::BaseTextFormatter::VT100_COLORS` and - `RSpec::Core::BaseTextFormatter::VT100_COLOR_CODES` in favour - of `RSpec::Core::BaseTextFormatter::ConsoleCodes::VT100_CODES` and - `RSpec::Core::BaseTextFormatter::ConsoleCodes::VT100_CODE_VALUES`. - (Jon Rowe) -* Deprecate `RSpec::Core::ExampleGroup.display_name` in favor of - `RSpec::Core::ExampleGroup.description`. (Myron Marston) -* Deprecate `RSpec::Core::ExampleGroup.describes` in favor of - `RSpec::Core::ExampleGroup.described_class`. (Myron Marston) -* Deprecate `RSpec::Core::ExampleGroup.alias_example_to` in favor of - `RSpec::Core::Configuration#alias_example_to`. (Myron Marston) -* Deprecate `RSpec::Core::ExampleGroup.alias_it_behaves_like_to` in favor - of `RSpec::Core::Configuration#alias_it_behaves_like_to`. (Myron Marston) -* Deprecate `RSpec::Core::ExampleGroup.focused` in favor of - `RSpec::Core::ExampleGroup.focus`. (Myron Marston) -* Add deprecation warning for `config.filter_run :focused` since - example aliases `fit` and `focus` will no longer include - `:focused` metadata but will continue to include `:focus`. (Myron Marston) -* Deprecate filtering by `:line_number` (e.g. `--line-number` from the - CLI). Use location filtering instead. (Myron Marston) -* Deprecate `--default_path` as an alternative to `--default-path`. (Jon Rowe) -* Deprecate `RSpec::Core::Configuration#warnings` in favor of - `RSpec::Core::Configuration#warnings?`. (Myron Marston) -* Deprecate `share_examples_for` in favor of `shared_examples_for` or - just `shared_examples`. (Myron Marston) -* Deprecate `RSpec::Core::CommandLine` in favor of - `RSpec::Core::Runner`. (Myron Marston) -* Deprecate `#color_enabled`, `#color_enabled=` and `#color?` in favour of - `#color`, `#color=` and `#color_enabled? output`. (Jon Rowe) -* Deprecate `#filename_pattern` in favour of `#pattern`. (Jon Rowe) -* Deprecate `#backtrace_cleaner` in favour of `#backtrace_formatter`. (Jon Rowe) -* Deprecate mutating `RSpec::Configuration#formatters`. (Jon Rowe) -* Deprecate `stdlib` as an available expectation framework in favour of - `test_unit` and `minitest`. (Aaron Kromer) - -Bug Fixes: - -* Issue a warning when you set `config.deprecation_stream` too late for - it to take effect because the reporter has already been setup. (Myron Marston) -* `skip` with a block should not execute the block. (Xavier Shay) - -### 2.99.0.beta2 / 2014-02-17 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.99.0.beta1...v2.99.0.beta2) - -Enhancements: - -* Add `is_expected` for one-liners that read well with the - `expect`-based syntax. `is_expected` is simply defined as - `expect(subject)` and can be used in an expression like: - `it { is_expected.to read_well }`. (Myron Marston) -* Backport `skip` from RSpec 3, which acts like `pending` did in RSpec 2 - when not given a block, since the behavior of `pending` is changing in - RSpec 3. (Xavier Shay) - -Deprecations: - -* Deprecate inexact `mock_with` config options. RSpec 3 will only support - the exact symbols `:rspec`, `:mocha`, `:flexmock`, `:rr` or `:nothing` - (or any module that implements the adapter interface). RSpec 2 did - fuzzy matching but this will not be supported going forward. - (Myron Marston) -* Deprecate `show_failures_in_pending_blocks` config option. To achieve - the same behavior as the option enabled, you can use a custom - formatter instead. (Xavier Shay) -* Add a deprecation warning for the fact that the behavior of `pending` - is changing in RSpec 3 -- rather than skipping the example (as it did - in 2.x when no block was provided), it will run the example and mark - it as failed if no exception is raised. Use `skip` instead to preserve - the old behavior. (Xavier Shay) -* Deprecate 's', 'n', 'spec' and 'nested' as aliases for documentation - formatter. (Jon Rowe) -* Deprecate `RSpec::Core::Reporter#abort` in favor of - `RSpec::Core::Reporter#finish`. (Jon Rowe) - -Bug Fixes: - -* Fix failure (undefined method `path`) in end-of-run summary - when `raise_errors_for_deprecations!` is configured. (Myron Marston) -* Fix issue were overridding spec ordering from the command line wasn't - fully recognised interally. (Jon Rowe) - -### 2.99.0.beta1 / 2013-11-07 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.7...v2.99.0.beta1) - -Enhancements - -* Block-based DSL methods that run in the context of an example - (`it`, `before(:each)`, `after(:each)`, `let` and `subject`) - now yield the example as a block argument. (David Chelimsky) -* Warn when the name of more than one example group is submitted to - `include_examples` and it's aliases. (David Chelimsky) -* Add `expose_current_running_example_as` config option for - use during the upgrade process when external gems use the - deprecated `RSpec::Core::ExampleGroup#example` and - `RSpec::Core::ExampleGroup#running_example` methods. (Myron Marston) -* Limit spamminess of deprecation messages. (Bradley Schaefer, Loren Segal) -* Add `config.raise_errors_for_deprecations!` option, which turns - deprecations warnings into errors to surface the full backtrace - of the call site. (Myron Marston) - -Deprecations - -* Deprecate `RSpec::Core::ExampleGroup#example` and - `RSpec::Core::ExampleGroup#running_example` methods. If you need - access to the example (e.g. to get its metadata), use a block argument - instead. (David Chelimsky) -* Deprecate use of `autotest/rspec2` in favour of `rspec-autotest`. (Jon Rowe) -* Deprecate RSpec's built-in debugger support. Use a CLI option like - `-rruby-debug` (for the ruby-debug gem) or `-rdebugger` (for the - debugger gem) instead. (Myron Marston) -* Deprecate `RSpec.configuration.treat_symbols_as_metadata_keys_with_true_values = false`. - RSpec 3 will not support having this option set to `false`. (Myron Marston) -* Deprecate accessing a `let` or `subject` declaration in - a `after(:all)` hook. (Myron Marston, Jon Rowe) -* Deprecate built-in `its` usage in favor of `rspec-its` gem due to planned - removal in RSpec 3. (Peter Alfvin) -* Deprecate `RSpec::Core::PendingExampleFixedError` in favor of - `RSpec::Core::Pending::PendingExampleFixedError`. (Myron Marston) -* Deprecate `RSpec::Core::Configuration#out` and - `RSpec::Core::Configuration#output` in favor of - `RSpec::Core::Configuration#output_stream`. (Myron Marston) -* Deprecate legacy ordering APIs. - * You should use `register_ordering(:global)` instead of these: - * `RSpec::Core::Configuration#order_examples` - * `RSpec::Core::Configuration#order_groups` - * `RSpec::Core::Configuration#order_groups_and_examples` - * These are deprecated with no replacement because in RSpec 3 - ordering is a property of individual example groups rather than - just a global property of the entire test suite: - * `RSpec::Core::Configuration#order` - * `RSpec::Core::Configuration#randomize?` - * `--order default` is deprecated in favor of `--order defined` - (Myron Marston) - -### 2.14.8 / 2014-02-27 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.7...v2.14.8) - -Bug fixes: - -* Fix regression with the `textmateformatter` that prevented backtrace links - from being clickable. (Stefan Daschek) - -### 2.14.7 / 2013-10-29 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.6...v2.14.7) - -Bug fixes: - -* Fix regression in 2.14.6 that broke the Fivemat formatter. - It depended upon either - `example.execution_result[:exception].pending_fixed?` (which - was removed in 2.14.6 to fix an issue with frozen error objects) - or `RSpec::Core::PendingExampleFixedError` (which was renamed - to `RSpec::Core::Pending::PendingExampleFixedError` in 2.8. - This fix makes a constant alias for the old error name. - (Myron Marston) - -### 2.14.6 / 2013-10-15 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.5...v2.14.6) - -Bug fixes: - -* Format stringified numbers correctly when mathn library is loaded. - (Jay Hayes) -* Fix an issue that prevented the use of frozen error objects. (Lars - Gierth) - -### 2.14.5 / 2013-08-13 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.4...v2.14.5) - -Bug fixes: - -* Fix a `NoMethodError` that was being raised when there were no shared - examples or contexts declared and `RSpec.world.reset` is invoked. - (thepoho, Jon Rowe, Myron Marston) -* Fix a deprecation warning that was being incorrectly displayed when - `shared_examples` are declared at top level in a `module` scope. - (Jon Rowe) -* Fix after(:all) hooks so consecutive (same context) scopes will run even if - one raises an error. (Jon Rowe, Trejkaz) -* JsonFormatter no longer dies if `dump_profile` isn't defined (Alex / @MasterLambaster, Jon Rowe) - -### 2.14.4 / 2013-07-21 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.3...v2.14.4) - -Bug fixes - -* Fix regression in 2.14: ensure configured requires (via `-r` option) - are loaded before spec files are loaded. This allows the spec files - to programatically change the file pattern (Jon Rowe). -* Autoload `RSpec::Mocks` and `RSpec::Expectations` when referenced if - they are not already loaded (`RSpec::Matches` has been autoloaded - for a while). In the `rspec` gem, we changed it recently to stop - loading `rspec/mocks` and `rspec/expectations` by default, as some - users reported problems where they were intending to use mocha, - not rspec-mocks, but rspec-mocks was loaded and causing a conflict. - rspec-core loads mocks and expectations at the appropriate time, so - it seemed like a safe change -- but caused a problem for some authors - of libraries that integrate with RSpec. This fixes that problem. - (Myron Marston) -* Gracefully handle a command like `rspec --profile path/to/spec.rb`: - the `path/to/spec.rb` arg was being wrongly treated as the `profile` - integer arg, which got cast `0` using `to_i`, causing no profiled - examples to be printed. (Jon Rowe) - -### 2.14.3 / 2013-07-13 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.2...v2.14.3) - -Bug fixes - -* Fix deprecation notices issued from `RSpec::Core::RakeTask` so - that they work properly when all of rspec-core is not loaded. - (This was a regression in 2.14) (Jon Rowe) - -### 2.14.2 / 2013-07-09 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.1...v2.14.2) - -Bug fixes - -* Fix regression caused by 2.14.1 release: formatters that - report that they `respond_to?` a notification, but had - no corresponding method would raise an error when registered. - The new fix is to just implement `start` on the deprecation - formatter to fix the original JRuby/ruby-debug issue. - (Jon Rowe) - -### 2.14.1 / 2013-07-08 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.0...v2.14.1) - -Bug fixes - -* Address deprecation formatter failure when using `ruby-debug` on - JRuby: fix `RSpec::Core::Reporter` to not send a notification - when the formatter's implementation of the notification method - comes from `Kernel` (Alex Portnov, Jon Rowe). - -### 2.14.0 / 2013-07-06 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.14.0.rc1...v2.14.0) - -Enhancements - -* Apply focus to examples defined with `fit` (equivalent of - `it "description", focus: true`) (Michael de Silva) - -Bug fix - -* Ensure methods defined by `let` take precedence over others - when there is a name collision (e.g. from an included module). - (Jon Rowe, Andy Lindeman and Myron Marston) - -### 2.14.0.rc1 / 2013-05-27 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.13.1...v2.14.0.rc1) - -Enhancements - -* Improved Windows detection inside Git Bash, for better `--color` handling. -* Add profiling of the slowest example groups to `--profile` option. - The output is sorted by the slowest average example groups. -* Don't show slow examples if there's a failure and both `--fail-fast` - and `--profile` options are used (Paweł Gościcki). -* Rather than always adding `spec` to the load path, add the configured - `--default-path` to the load path (which defaults to `spec`). This - better supports folks who choose to put their specs in a different - directory (John Feminella). -* Add some logic to test time duration precision. Make it a - function of time, dropping precision as the time increases. (Aaron Kromer) -* Add new `backtrace_inclusion_patterns` config option. Backtrace lines - that match one of these patterns will _always_ be included in the - backtrace, even if they match an exclusion pattern, too (Sam Phippen). -* Support ERB trim mode using the `-` when parsing `.rspec` as ERB - (Gabor Garami). -* Give a better error message when let and subject are called without a block. - (Sam Phippen). -* List the precedence of `.rspec-local` in the configuration documentation - (Sam Phippen) -* Support `{a,b}` shell expansion syntax in `--pattern` option - (Konstantin Haase). -* Add cucumber documentation for --require command line option - (Bradley Schaefer) -* Expose configuration options via config: - * `config.libs` returns the libs configured to be added onto the load path - * `full_backtrace?` returns the state of the backtrace cleaner - * `debug?` returns true when the debugger is loaded - * `line_numbers` returns the line numbers we are filtering by (if any) - * `full_description` returns the RegExp used to filter descriptions - (Jon Rowe) -* Add setters for RSpec.world and RSpec.configuration (Alex Soulim) -* Configure ruby's warning behaviour with `--warnings` (Jon Rowe) -* Fix an obscure issue on old versions of `1.8.7` where `Time.dup` wouldn't - allow access to `Time.now` (Jon Rowe) -* Make `shared_examples_for` context aware, so that keys may be safely reused - in multiple contexts without colliding. (Jon Rowe) -* Add a configurable `deprecation_stream` (Jon Rowe) -* Publish deprecations through a formatter (David Chelimsky) - -Bug fixes - -* Make JSON formatter behave the same when it comes to `--profile` as - the text formatter (Paweł Gościcki). -* Fix named subjects so that if an inner group defines a method that - overrides the named method, `subject` still retains the originally - declared value (Myron Marston). -* Fix random ordering so that it does not cause `rand` in examples in - nested sibling contexts to return the same value (Max Shytikov). -* Use the new `backtrace_inclusion_patterns` config option to ensure - that folks who develop code in a directory matching one of the default - exclusion patterns (e.g. `gems`) still get the normal backtrace - filtering (Sam Phippen). -* Fix ordering of `before` hooks so that `before` hooks declared in - `RSpec.configure` run before `before` hooks declared in a shared - context (Michi Huber and Tejas Dinkar). -* Fix `Example#full_description` so that it gets filled in by the last - matcher description (as `Example#description` already did) when no - doc string has been provided (David Chelimsky). -* Fix the memoized methods (`let` and `subject`) leaking `define_method` - as a `public` method. (Thomas Holmes and Jon Rowe) (#873) -* Fix warnings coming from the test suite. (Pete Higgins) - -Deprecations - -* Deprecate `Configuration#backtrace_clean_patterns` in favor of - `Configuration#backtrace_exclusion_patterns` for greater consistency - and symmetry with new `backtrace_inclusion_patterns` config option - (Sam Phippen). -* Deprecate `Configuration#requires=` in favor of using ruby's - `require`. Requires specified by the command line can still be - accessed by the `Configuration#require` reader. (Bradley Schaefer) -* Deprecate calling `SharedExampleGroups` defined across sibling contexts - (Jon Rowe) - -### 2.13.1 / 2013-03-12 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.13.0...v2.13.1) - -Bug fixes - -* Use hook classes as proxies rather than extending hook blocks to support - lambdas for before/after/around hooks. (David Chelimsky) -* Fix regression in 2.13.0 that caused confusing behavior when overriding - a named subject with an unnamed subject in an inner group and then - referencing the outer group subject's name. The fix for this required - us to disallow using `super` in a named subject (which is confusing, - anyway -- named subjects create 2 methods, so which method on the - parent example group are you `super`ing to?) but `super` in an unnamed - subject continues to work (Myron Marston). -* Do not allow a referenced `let` or `subject` in `before(:all)` to cause - other `let` declarations to leak across examples (Myron Marston). -* Work around odd ruby 1.9 bug with `String#match` that was triggered - by passing it a regex from a `let` declaration. For more info, see - http://bugs.ruby-lang.org/issues/8059 (Aaron Kromer). -* Add missing `require 'set'` to `base_text_formatter.rb` (Tom - Anderson). - -Deprecations - -* Deprecate accessing `let` or `subject` declarations in `before(:all)`. - These were not intended to be called in a `before(:all)` hook, as - they exist to define state that is reset between each example, while - `before(:all)` exists to define state that is shared across examples - in an example group (Myron Marston). - -### 2.13.0 / 2013-02-23 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.12.2...v2.13.0) - -Enhancements - -* Allow `--profile` option to take a count argument that - determines the number of slow examples to dump - (Greggory Rothmeier). -* Add `subject!` that is the analog to `let!`. It defines an - explicit subject and sets a `before` hook that will invoke - the subject (Zubin Henner). -* Fix `let` and `subject` declaration so that `super` - and `return` can be used in them, just like in a normal - method. (Myron Marston) -* Allow output colors to be configured individually. - (Charlie Maffitt) -* Always dump slow examples when `--profile` option is given, - even when an example failed (Myron Marston). - -Bug fixes - -* Don't blow up when dumping error output for instances - of anonymous error classes (Myron Marston). -* Fix default backtrace filters so lines from projects - containing "gems" in the name are not filtered, but - lines from installed gems still are (Myron Marston). -* Fix autotest command so that is uses double quotes - rather than single quotes for windows compatibility - (Jonas Tingeborn). -* Fix `its` so that uses of `subject` in a `before` or `let` - declaration in the parent group continue to reference the - parent group's subject. (Olek Janiszewski) - -### 2.12.2 / 2012-12-13 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.12.1...v2.12.2) - -Bug fixes - -* Fix `RSpec::Core::RakeTask` so that it is compatible with rake 0.8.7 - on ruby 1.8.7. We had accidentally broke it in the 2.12 release - (Myron Marston). -* Fix `RSpec::Core::RakeTask` so it is tolerant of the `Rspec` constant - for backwards compatibility (Patrick Van Stee) - -### 2.12.1 / 2012-12-01 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.12.0...v2.12.1) - -Bug fixes - -* Specs are run even if another at\_exit hook calls `exit`. This allows - Test::Unit and RSpec to run together. (Suraj N. Kurapati) -* Fix full doc string concatenation so that it handles the case of a - method string (e.g. "#foo") being nested under a context string - (e.g. "when it is tuesday"), so that we get "when it is tuesday #foo" - rather than "when it is tuesday#foo". (Myron Marston) -* Restore public API I unintentionally broke in 2.12.0: - `RSpec::Core::Formatters::BaseFormatter#format_backtrce(backtrace, example)` - (Myron Marston). - -### 2.12.0 / 2012-11-12 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.11.1...v2.12.0) - -Enhancements - -* Add support for custom ordering strategies for groups and examples. - (Myron Marston) -* JSON Formatter (Alex Chaffee) -* Refactor rake task internals (Sam Phippen) -* Refactor HtmlFormatter (Pete Hodgson) -* Autotest supports a path to Ruby that contains spaces (dsisnero) -* Provide a helpful warning when a shared example group is redefined. - (Mark Burns). -* `--default_path` can be specified as `--default-line`. `--line_number` can be - specified as `--line-number`. Hyphens are more idiomatic command line argument - separators (Sam Phippen). -* A more useful error message is shown when an invalid command line option is - used (Jordi Polo). -* Add `format_docstrings { |str| }` config option. It can be used to - apply formatting rules to example group and example docstrings. - (Alex Tan) -* Add support for an `.rspec-local` options file. This is intended to - allow individual developers to set options in a git-ignored file that - override the common project options in `.rspec`. (Sam Phippen) -* Support for mocha 0.13.0. (Andy Lindeman) - -Bug fixes - -* Remove override of `ExampleGroup#ancestors`. This is a core ruby method that - RSpec shouldn't override. Instead, define `ExampleGroup#parent_groups`. (Myron - Marston) -* Limit monkey patching of shared example/context declaration methods - (`shared_examples_for`, etc.) to just the objects that need it rather than - every object in the system (Myron Marston). -* Fix Metadata#fetch to support computed values (Sam Goldman). -* Named subject can now be referred to from within subject block in a nested - group (tomykaira). -* Fix `fail_fast` so that it properly exits when an error occurs in a - `before(:all) hook` (Bradley Schaefer). -* Make the order spec files are loaded consistent, regardless of the - order of the files returned by the OS or the order passed at - the command line (Jo Liss and Sam Phippen). -* Ensure instance variables from `before(:all)` are always exposed - from `after(:all)`, even if an error occurs in `before(:all)` - (Sam Phippen). -* `rspec --init` no longer generates an incorrect warning about `--configure` - being deprecated (Sam Phippen). -* Fix pluralization of `1 seconds` (Odin Dutton) -* Fix ANSICON url (Jarmo Pertman) -* Use dup of Time so reporting isn't clobbered by examples that modify Time - without properly restoring it. (David Chelimsky) - -Deprecations - -* `share_as` is no longer needed. `shared_context` and/or - `RSpec::SharedContext` provide better mechanisms (Sam Phippen). -* Deprecate `RSpec.configuration` with a block (use `RSpec.configure`). - - -### 2.11.1 / 2012-07-18 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.11.0...v2.11.1) - -Bug fixes - -* Fix the way we autoload RSpec::Matchers so that custom matchers can be - defined before rspec-core has been configured to definitely use - rspec-expectations. (Myron Marston) -* Fix typo in --help message printed for -e option. (Jo Liss) -* Fix ruby warnings. (Myron Marston) -* Ignore mock expectation failures when the example has already failed. - Mock expectation failures have always been ignored in this situation, - but due to my changes in 27059bf1 it was printing a confusing message. - (Myron Marston). - -### 2.11.0 / 2012-07-07 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.10.1...v2.11.0) - -Enhancements - -* Support multiple `--example` options. (Daniel Doubrovkine @dblock) -* Named subject e.g. `subject(:article) { Article.new }` - * see [http://blog.davidchelimsky.net/2012/05/13/spec-smell-explicit-use-of-subject/](http://blog.davidchelimsky.net/2012/05/13/spec-smell-explicit-use-of-subject/) - for background. - * thanks to Bradley Schaefer for suggesting it and Avdi Grimm for almost - suggesting it. -* `config.mock_with` and `config.expect_with` yield custom config object to a - block if given - * aids decoupling from rspec-core's configuation -* `include_context` and `include_examples` support a block, which gets eval'd - in the current context (vs the nested context generated by `it_behaves_like`). -* Add `config.order = 'random'` to the `spec_helper.rb` generated by `rspec - --init`. -* Delay the loading of DRb (Myron Marston). -* Limit monkey patching of `describe` onto just the objects that need it rather - than every object in the system (Myron Marston). - -Bug fixes - -* Support alternative path separators. For example, on Windows, you can now do - this: `rspec spec\subdir`. (Jarmo Pertman @jarmo) -* When an example raises an error and an after or around hook does as - well, print out the hook error. Previously, the error was silenced and - the user got no feedback about what happened. (Myron Marston) -* `--require` and `-I` are merged among different configuration sources (Andy - Lindeman) -* Delegate to mocha methods instead of aliasing them in mocha adapter. - -### 2.10.1 / 2012-05-19 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.10.0...v2.10.1) - -Bug fixes - -* `RSpec.reset` properly reinits configuration and world -* Call `to_s` before `split` on exception messages that might not always be - Strings (slyphon) - -### 2.10.0 / 2012-05-03 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.9.0...v2.10.0) - -Enhancements - -* Add `prepend_before` and `append_after` hooks (preethiramdev) - * intended for extension libs - * restores rspec-1 behavior -* Reporting of profiled examples (moro) - * Report the total amount of time taken for the top slowest examples. - * Report what percentage the slowest examples took from the total runtime. - -Bug fixes - -* Properly parse `SPEC_OPTS` options. -* `example.description` returns the location of the example if there is no - explicit description or matcher-generated description. -* RDoc fixes (Grzegorz Świrski) -* Do not modify example ancestry when dumping errors (Michael Grosser) - -### 2.9.0 / 2012-03-17 -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.8.0...v2.9.0) - -Enhancements - -* Support for "X minutes X seconds" spec run duration in formatter. (uzzz) -* Strip whitespace from group and example names in doc formatter. -* Removed spork-0.9 shim. If you're using spork-0.8.x, you'll need to upgrade - to 0.9.0. - -Bug fixes - -* Restore `--full_backtrace` option -* Ensure that values passed to `config.filter_run` are respected when running - over DRb (using spork). -* Ensure shared example groups are reset after a run (as example groups are). -* Remove `rescue false` from calls to filters represented as Procs -* Ensure `described_class` gets the closest constant (pyromaniac) -* In "autorun", don't run the specs in the `at_exit` hook if there was an - exception (most likely due to a SyntaxError). (sunaku) -* Don't extend groups with modules already used to extend ancestor groups. -* `its` correctly memoizes nil or false values (Yamada Masaki) - -### 2.8.0 / 2012-01-04 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.8.0.rc2...v2.8.0) - -Bug fixes - -* For metadata filtering, restore passing the entire array to the proc, rather - than each item in the array (weidenfreak) -* Ensure each spec file is loaded only once - * Fixes a bug that caused all the examples in a file to be run when - referenced twice with line numbers in a command, e.g. - * `rspec path/to/file:37 path/to/file:42` - -### 2.8.0.rc2 / 2011-12-19 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.8.0.rc1...v2.8.0.rc2) - -Enhancments - -* new `--init` command (Peter Schröder) - * generates `spec/spec_helper.rb` - * deletes obsolete files (on confirmation) - * merged with and deprecates `--configure` command, which generated - `.rspec` -* use `require_relative` when available (Ian Leitch) -* `include_context` and `include_examples` accept params (Calvin Bascom) -* print the time for every example in the html formatter (Richie Vos) -* several tasty refactoring niblets (Sasha) -* `it "does something", :x => [:foo,'bar',/baz/] (Ivan Neverov) - * supports matching n command line tag values with an example or group - -### 2.8.0.rc1 / 2011-11-06 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.7.1...v2.8.0.rc1) - -Enhancements - -* `--order` (Justin Ko) - * run examples in random order: `--order rand` - * specify the seed: `--order rand:123` -* `--seed SEED` - * equivalent of `--order rand:SEED` -* SharedContext supports `let` (David Chelimsky) -* Filter improvements (David Chelimsky) - * override opposing tags from the command line - * override RSpec.configure tags from the command line - * `--line_number 37` overrides all other filters - * `path/to/file.rb:37` overrides all other filters - * refactor: consolidate filter management in a FilterManger object -* Eliminate Ruby warnings (Matijs van Zuijlen) -* Make reporter.report an API (David Chelimsky) - * supports extension tools like interative_rspec - -Changes - -* change `config.color_enabled` (getter/setter/predicate) to `color` to align - with `--[no]-color` CLI option. - * `color_enabled` is still supported for now, but will likley be deprecated - in a 2.x release so we can remove it in 3.0. - -Bug fixes - -* Make sure the `bar` in `--tag foo:bar` makes it to DRb (Aaron Gibralter) -* Fix bug where full descriptions of groups nested 3 deep were repeated. -* Restore report of time to run to start after files are loaded. - * fixes bug where run times were cumalitive in spork - * fixes compatibility with time-series metrics -* Don't error out when `config.mock_with` or `expect_with` is re-specifying the - current config (Myron Marston) - -* Deprecations - * :alias option on `configuration.add_setting`. Use `:alias_with` on the - original setting declaration instead. - -### 2.7.1 / 2011-10-20 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.7.0...v2.7.1) - -Bug fixes - -* tell autotest the correct place to find the rspec executable - -### 2.7.0 / 2011-10-16 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.6.4...v2.7.0) - -NOTE: RSpec's release policy dictates that there should not be any backward -incompatible changes in minor releases, but we're making an exception to -release a change to how RSpec interacts with other command line tools. - -As of 2.7.0, you must explicity `require "rspec/autorun"` unless you use the -`rspec` command (which already does this for you). - -Enhancements - -* Add `example.exception` (David Chelimsky) -* `--default_path` command line option (Justin Ko) -* support multiple `--line_number` options (David J. Hamilton) - * also supports `path/to/file.rb:5:9` (runs examples on lines 5 and 9) -* Allow classes/modules to be used as shared example group identifiers (Arthur - Gunn) -* Friendly error message when shared context cannot be found (Sławosz - Sławiński) -* Clear formatters when resetting config (John Bintz) -* Add `xspecify` and xexample as temp-pending methods (David Chelimsky) -* Add `--no-drb` option (Iain Hecker) -* Provide more accurate run time by registering start time before code is - loaded (David Chelimsky) - * reverted in 2.8.0 -* Rake task default pattern finds specs in symlinked dirs (Kelly Felkins) -* Rake task no longer does anything to invoke bundler since Bundler already - handles it for us. Thanks to Andre Arko for the tip. -* Add `--failure-exit-code` option (Chris Griego) - -Bug fixes - -* Include `Rake::DSL` to remove deprecation warnings in Rake > 0.8.7 (Pivotal - Casebook) -* Only eval `let` block once even if it returns `nil` (Adam Meehan) -* Fix `--pattern` option (wasn't being recognized) (David Chelimsky) -* Only implicitly `require "rspec/autorun"` with the `rspec` command (David - Chelimsky) -* Ensure that rspec's `at_exit` defines the exit code (Daniel Doubrovkine) -* Show the correct snippet in the HTML and TextMate formatters (Brian Faherty) - -### 2.6.4 / 2011-06-06 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.6.3...v2.6.4) - -NOTE: RSpec's release policy dictates that there should not be new -functionality in patch releases, but this minor enhancement slipped in by -accident. As it doesn't add a new API, we decided to leave it in rather than -roll back this release. - -Enhancements - -* Add summary of commands to run individual failed examples. - -Bug fixes - -* Support exclusion filters in DRb. (Yann Lugrin) -* Fix --example escaping when run over DRb. (Elliot Winkler) -* Use standard ANSI codes for color formatting so colors work in a wider set of - color schemes. - -### 2.6.3 / 2011-05-24 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.6.2...v2.6.3) - -Bug fixes - -* Explicitly convert exit code to integer, avoiding TypeError when return - value of run is IO object proxied by `DRb::DRbObject` (Julian Scheid) -* Clarify behavior of `--example` command line option -* Build using a rubygems-1.6.2 to avoid downstream yaml parsing error - -### 2.6.2 / 2011-05-21 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.6.1...v2.6.2) - -Bug fixes - -* Warn rather than raise when HOME env var is not defined -* Properly merge command-line exclusions with default :if and :unless (joshcooper) - -### 2.6.1 / 2011-05-19 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.6.0...v2.6.1) - -Bug fixes - -* Don't extend nil when filters are nil -* `require 'rspec/autorun'` when running rcov. - -### 2.6.0 / 2011-05-12 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.5.1...v2.6.0) - -Enhancements - -* `shared_context` (Damian Nurzynski) - * extend groups matching specific metadata with: - * method definitions - * subject declarations - * let/let! declarations - * etc (anything you can do in a group) -* `its([:key])` works for any subject with #[]. (Peter Jaros) -* `treat_symbols_as_metadata_keys_with_true_values` (Myron Marston) -* Print a deprecation warning when you configure RSpec after defining an - example. All configuration should happen before any examples are defined. - (Myron Marston) -* Pass the exit status of a DRb run to the invoking process. This causes specs - run via DRb to not just return true or false. (Ilkka Laukkanen) -* Refactoring of `ConfigurationOptions#parse_options` (Rodrigo Rosenfeld Rosas) -* Report excluded filters in runner output (tip from andyl) -* Clean up messages for filters/tags. -* Restore --pattern/-P command line option from rspec-1 -* Support false as well as true in config.full_backtrace= (Andreas Tolf - Tolfsen) - -Bug fixes - -* Don't stumble over an exception without a message (Hans Hasselberg) -* Remove non-ascii characters from comments that were choking rcov (Geoffrey - Byers) -* Fixed backtrace so it doesn't include lines from before the autorun at_exit - hook (Myron Marston) -* Include RSpec::Matchers when first example group is defined, rather than just - before running the examples. This works around an obscure bug in ruby 1.9 - that can cause infinite recursion. (Myron Marston) -* Don't send `example_group_[started|finished]` to formatters for empty groups. -* Get specs passing on jruby (Sidu Ponnappa) -* Fix bug where mixing nested groups and outer-level examples gave - unpredictable :line_number behavior (Artur Małecki) -* Regexp.escape the argument to --example (tip from Elliot Winkler) -* Correctly pass/fail pending block with message expectations -* CommandLine returns exit status (0/1) instead of true/false -* Create path to formatter output file if it doesn't exist (marekj). - - -### 2.5.1 / 2011-02-06 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.5.0...v2.5.1) - -NOTE: this release breaks compatibility with rspec/autotest/bundler -integration, but does so in order to greatly simplify it. - -With this release, if you want the generated autotest command to include -'bundle exec', require Autotest's bundler plugin in a .autotest file in the -project's root directory or in your home directory: - - require "autotest/bundler" - -Now you can just type 'autotest' on the commmand line and it will work as you expect. - -If you don't want 'bundle exec', there is nothing you have to do. - -### 2.5.0 / 2011-02-05 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.4.0...v2.5.0) - -Enhancements - -* Autotest::Rspec2 parses command line args passed to autotest after '--' -* --skip-bundler option for autotest command -* Autotest regexp fixes (Jon Rowe) -* Add filters to html and textmate formatters (Daniel Quimper) -* Explicit passing of block (need for JRuby 1.6) (John Firebaugh) - -Bug fixes - -* fix dom IDs in HTML formatter (Brian Faherty) -* fix bug with --drb + formatters when not running in drb -* include --tag options in drb args (monocle) -* fix regression so now SPEC_OPTS take precedence over CLI options again (Roman - Chernyatchik) -* only call its(:attribute) once (failing example from Brian Dunn) -* fix bizarre bug where rspec would hang after String.alias :to_int :to_i - (Damian Nurzynski) - -Deprecations - -* implicit inclusion of 'bundle exec' when Gemfile present (use autotest's - bundler plugin instead) - -### 2.4.0 / 2011-01-02 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.3.1...v2.4.0) - -Enhancements - -* start the debugger on -d so the stack trace is visible when it stops - (Clifford Heath) -* apply hook filtering to examples as well as groups (Myron Marston) -* support multiple formatters, each with their own output -* show exception classes in failure messages unless they come from RSpec - matchers or message expectations -* before(:all) { pending } sets all examples to pending - -Bug fixes - -* fix bug due to change in behavior of reject in Ruby 1.9.3-dev (Shota - Fukumori) -* fix bug when running in jruby: be explicit about passing block to super (John - Firebaugh) -* rake task doesn't choke on paths with quotes (Janmejay Singh) -* restore --options option from rspec-1 -* require 'ostruct' to fix bug with its([key]) (Kim Burgestrand) -* --configure option generates .rspec file instead of autotest/discover.rb - -### 2.3.1 / 2010-12-16 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.3.0...v2.3.1) - -Bug fixes - -* send debugger warning message to $stdout if RSpec.configuration.error_stream - has not been defined yet. -* HTML Formatter _finally_ properly displays nested groups (Jarmo Pertman) -* eliminate some warnings when running RSpec's own suite (Jarmo Pertman) - -### 2.3.0 / 2010-12-12 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.2.1...v2.3.0) - -Enhancements - -* tell autotest to use "rspec2" if it sees a .rspec file in the project's root - directory - * replaces the need for ./autotest/discover.rb, which will not work with - all versions of ZenTest and/or autotest -* config.expect_with - * :rspec # => rspec/expectations - * :stdlib # => test/unit/assertions - * :rspec, :stdlib # => both - -Bug fixes - -* fix dev Gemfile to work on non-mac-os machines (Lake Denman) -* ensure explicit subject is only eval'd once (Laszlo Bacsi) - -### 2.2.1 / 2010-11-28 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.2.0...v2.2.1) - -Bug fixes -* alias_method instead of override Kernel#method_missing (John Wilger) -* changed --autotest to --tty in generated command (MIKAMI Yoshiyuki) -* revert change to debugger (had introduced conflict with Rails) - * also restored --debugger/-debug option - -### 2.2.0 / 2010-11-28 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.1.0...v2.2.0) - -Deprecations/changes - -* --debug/-d on command line is deprecated and now has no effect -* win32console is now ignored; Windows users must use ANSICON for color support - (Bosko Ivanisevic) - -Enhancements - -* When developing locally rspec-core now works with the rspec-dev setup or your - local gems -* Raise exception with helpful message when rspec-1 is loaded alongside rspec-2 - (Justin Ko) -* debugger statements _just work_ as long as ruby-debug is installed - * otherwise you get warned, but not fired -* Expose example.metadata in around hooks -* Performance improvments (much faster now) - -Bug fixes - -* Make sure --fail-fast makes it across drb -* Pass -Ilib:spec to rcov - -### 2.1.0 / 2010-11-07 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.0.1...v2.1.0) - -Enhancments - -* Add skip_bundler option to rake task to tell rake task to ignore the presence - of a Gemfile (jfelchner) -* Add gemfile option to rake task to tell rake task what Gemfile to look for - (defaults to 'Gemfile') -* Allow passing caller trace into Metadata to support extensions (Glenn - Vanderburg) -* Add deprecation warning for Spec::Runner.configure to aid upgrade from - RSpec-1 -* Add deprecated Spec::Rake::SpecTask to aid upgrade from RSpec-1 -* Add 'autospec' command with helpful message to aid upgrade from RSpec-1 -* Add support for filtering with tags on CLI (Lailson Bandeira) -* Add a helpful message about RUBYOPT when require fails in bin/rspec (slyphon) -* Add "-Ilib" to the default rcov options (Tianyi Cui) -* Make the expectation framework configurable (default rspec, of course) - (Justin Ko) -* Add 'pending' to be conditional (Myron Marston) -* Add explicit support for :if and :unless as metadata keys for conditional run - of examples (Myron Marston) -* Add --fail-fast command line option (Jeff Kreeftmeijer) - -Bug fixes - -* Eliminate stack overflow with "subject { self }" -* Require 'rspec/core' in the Raketask (ensures it required when running rcov) - -### 2.0.1 / 2010-10-18 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.0.0...v2.0.1) - -Bug fixes - -* Restore color when using spork + autotest -* Pending examples without docstrings render the correct message (Josep M. - Bach) -* Fixed bug where a failure in a spec file ending in anything but _spec.rb - would fail in a confusing way. -* Support backtrace lines from erb templates in html formatter (Alex Crichton) - -### 2.0.0 / 2010-10-10 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.0.0.rc...v2.0.0) - -RSpec-1 compatibility - -* Rake task uses ENV["SPEC"] as file list if present - -Bug fixes - -* Bug Fix: optparse --out foo.txt (Leonardo Bessa) -* Suppress color codes for non-tty output (except autotest) - -### 2.0.0.rc / 2010-10-05 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.0.0.beta.22...v2.0.0.rc) - -Enhancements - -* implicitly require unknown formatters so you don't have to require the file - explicitly on the commmand line (Michael Grosser) -* add --out/-o option to assign output target -* added fail_fast configuration option to abort on first failure -* support a Hash subject (its([:key]) { should == value }) (Josep M. Bach) - -Bug fixes - -* Explicitly require rspec version to fix broken rdoc task (Hans de Graaff) -* Ignore backtrace lines that come from other languages, like Java or - Javascript (Charles Lowell) -* Rake task now does what is expected when setting (or not setting) - fail_on_error and verbose -* Fix bug in which before/after(:all) hooks were running on excluded nested - groups (Myron Marston) -* Fix before(:all) error handling so that it fails examples in nested groups, - too (Myron Marston) - -### 2.0.0.beta.22 / 2010-09-12 - -[Full Changelog](http://github.com/rspec/rspec-core/compare/v2.0.0.beta.20...v2.0.0.beta.22) - -Enhancements - -* removed at_exit hook -* CTRL-C stops the run (almost) immediately - * first it cleans things up by running the appropriate after(:all) and - after(:suite) hooks - * then it reports on any examples that have already run -* cleaned up rake task - * generate correct task under variety of conditions - * options are more consistent - * deprecated redundant options -* run 'bundle exec autotest' when Gemfile is present -* support ERB in .rspec options files (Justin Ko) -* depend on bundler for development tasks (Myron Marston) -* add example_group_finished to formatters and reporter (Roman Chernyatchik) - -Bug fixes - -* support paths with spaces when using autotest (Andreas Neuhaus) -* fix module_exec with ruby 1.8.6 (Myron Marston) -* remove context method from top-level - * was conflicting with irb, for example -* errors in before(:all) are now reported correctly (Chad Humphries) - -Removals - -* removed -o --options-file command line option - * use ./.rspec and ~/.rspec diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/License.txt b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/License.txt deleted file mode 100644 index 4bd202e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/License.txt +++ /dev/null @@ -1,25 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 Chad Humphries, David Chelimsky, Myron Marston -Copyright (c) 2009 Chad Humphries, David Chelimsky -Copyright (c) 2006 David Chelimsky, The RSpec Development Team -Copyright (c) 2005 Steven Baker - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/README.md b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/README.md deleted file mode 100644 index 3cd7e72..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/README.md +++ /dev/null @@ -1,243 +0,0 @@ -# rspec-core [![Build Status](https://secure.travis-ci.org/rspec/rspec-core.png?branch=master)](http://travis-ci.org/rspec/rspec-core) [![Code Climate](https://codeclimate.com/github/rspec/rspec-core.png)](https://codeclimate.com/github/rspec/rspec-core) - -rspec-core provides the structure for writing executable examples of how your -code should behave, and an `rspec` command with tools to constrain which -examples get run and tailor the output. - -## install - - gem install rspec # for rspec-core, rspec-expectations, rspec-mocks - gem install rspec-core # for rspec-core only - rspec --help - -## basic structure - -RSpec uses the words "describe" and "it" so we can express concepts like a conversation: - - "Describe an order." - "It sums the prices of its line items." - -```ruby -RSpec.describe Order do - it "sums the prices of its line items" do - order = Order.new - order.add_entry(LineItem.new(:item => Item.new( - :price => Money.new(1.11, :USD) - ))) - order.add_entry(LineItem.new(:item => Item.new( - :price => Money.new(2.22, :USD), - :quantity => 2 - ))) - expect(order.total).to eq(Money.new(5.55, :USD)) - end -end -``` - -The `describe` method creates an [ExampleGroup](http://rubydoc.info/gems/rspec-core/RSpec/Core/ExampleGroup). Within the -block passed to `describe` you can declare examples using the `it` method. - -Under the hood, an example group is a class in which the block passed to -`describe` is evaluated. The blocks passed to `it` are evaluated in the -context of an _instance_ of that class. - -## nested groups - -You can also declare nested nested groups using the `describe` or `context` -methods: - -```ruby -RSpec.describe Order do - context "with no items" do - it "behaves one way" do - # ... - end - end - - context "with one item" do - it "behaves another way" do - # ... - end - end -end -``` - -## aliases - -You can declare example groups using either `describe` or `context`. -For a top level example group, `describe` and `context` are available -off of `RSpec`. For backwards compatibility, they are also available -off of the `main` object and `Module` unless you disable monkey -patching. - -You can declare examples within a group using any of `it`, `specify`, or -`example`. - -## shared examples and contexts - -Declare a shared example group using `shared_examples`, and then include it -in any group using `include_examples`. - -```ruby -RSpec.shared_examples "collections" do |collection_class| - it "is empty when first created" do - expect(collection_class.new).to be_empty - end -end - -RSpec.describe Array do - include_examples "collections", Array -end - -RSpec.describe Hash do - include_examples "collections", Hash -end -``` - -Nearly anything that can be declared within an example group can be declared -within a shared example group. This includes `before`, `after`, and `around` -hooks, `let` declarations, and nested groups/contexts. - -You can also use the names `shared_context` and `include_context`. These are -pretty much the same as `shared_examples` and `include_examples`, providing -more accurate naming when you share hooks, `let` declarations, helper methods, -etc, but no examples. - -## metadata - -rspec-core stores a metadata hash with every example and group, which -contains their descriptions, the locations at which they were -declared, etc, etc. This hash powers many of rspec-core's features, -including output formatters (which access descriptions and locations), -and filtering before and after hooks. - -Although you probably won't ever need this unless you are writing an -extension, you can access it from an example like this: - -```ruby -it "does something" do - expect(example.metadata[:description]).to eq("does something") -end -``` - -### `described_class` - -When a class is passed to `describe`, you can access it from an example -using the `described_class` method, which is a wrapper for -`example.metadata[:described_class]`. - -```ruby -RSpec.describe Widget do - example do - expect(described_class).to equal(Widget) - end -end -``` - -This is useful in extensions or shared example groups in which the specific -class is unknown. Taking the collections shared example group from above, we can -clean it up a bit using `described_class`: - -```ruby -RSpec.shared_examples "collections" do - it "is empty when first created" do - expect(described_class.new).to be_empty - end -end - -RSpec.describe Array do - include_examples "collections" -end - -RSpec.describe Hash do - include_examples "collections" -end -``` - -## the `rspec` command - -When you install the rspec-core gem, it installs the `rspec` executable, -which you'll use to run rspec. The `rspec` command comes with many useful -options. -Run `rspec --help` to see the complete list. - -## store command line options `.rspec` - -You can store command line options in a `.rspec` file in the project's root -directory, and the `rspec` command will read them as though you typed them on -the command line. - -## autotest integration - -rspec-core no longer ships with an Autotest extension, if you require Autotest -integration, please use the `rspec-autotest` gem and see [rspec/rspec-autotest](https://github.com/rspec/rspec-autotest) -for details - -## get started - -Start with a simple example of behavior you expect from your system. Do -this before you write any implementation code: - -```ruby -# in spec/calculator_spec.rb -RSpec.describe Calculator do - describe '#add' do - it 'returns the sum of its arguments' do - expect(Calculator.new.add(1, 2)).to eq(3) - end - end -end -``` - -Run this with the rspec command, and watch it fail: - -``` -$ rspec spec/calculator_spec.rb -./spec/calculator_spec.rb:1: uninitialized constant Calculator -``` - -Implement the simplest solution: - -```ruby -# in lib/calculator.rb -class Calculator - def add(a,b) - a + b - end -end -``` - -Be sure to require the implementation file in the spec: - -```ruby -# in spec/calculator_spec.rb -# - RSpec adds ./lib to the $LOAD_PATH -require "calculator" -``` - -Now run the spec again, and watch it pass: - -``` -$ rspec spec/calculator_spec.rb -. - -Finished in 0.000315 seconds -1 example, 0 failures -``` - -Use the `documentation` formatter to see the resulting spec: - -``` -$ rspec spec/calculator_spec.rb --format doc -Calculator - #add - returns the sum of its arguments - -Finished in 0.000379 seconds -1 example, 0 failures -``` - -## Also see - -* [http://github.com/rspec/rspec](http://github.com/rspec/rspec) -* [http://github.com/rspec/rspec-expectations](http://github.com/rspec/rspec-expectations) -* [http://github.com/rspec/rspec-mocks](http://github.com/rspec/rspec-mocks) diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/exe/rspec b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/exe/rspec deleted file mode 100755 index 7ee5fd8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/exe/rspec +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env ruby - -require 'rspec/core' -RSpec::Core::Runner.invoke diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/autorun.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/autorun.rb deleted file mode 100644 index 18cc1ed..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/autorun.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'rspec/core' -RSpec::Core::Runner.autorun diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core.rb deleted file mode 100644 index 05d261e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core.rb +++ /dev/null @@ -1,167 +0,0 @@ -$_rspec_core_load_started_at = Time.now -require 'rbconfig' - -require "rspec/support" -RSpec::Support.require_rspec_support "caller_filter" - -RSpec::Support.define_optimized_require_for_rspec(:core) { |f| require_relative f } - -%w[ - version - warnings - - flat_map - filter_manager - dsl - notifications - reporter - - hooks - memoized_helpers - metadata - metadata_filter - pending - formatters - ordering - - world - configuration - option_parser - configuration_options - runner - example - shared_example_group - example_group -].each { |name| RSpec::Support.require_rspec_core name } - -# Namespace for all core RSpec code. -module RSpec - autoload :SharedContext, 'rspec/core/shared_context' - - extend RSpec::Core::Warnings - - # Used to ensure examples get reloaded between multiple runs in - # the same process. - # - # Users must invoke this if they want to have the configuration reset when - # they use runner multiple times within the same process. - def self.reset - @world = nil - @configuration = nil - end - - # Returns the global [Configuration](RSpec/Core/Configuration) object. While you - # _can_ use this method to access the configuration, the more common - # convention is to use [RSpec.configure](RSpec#configure-class_method). - # - # @example - # RSpec.configuration.drb_port = 1234 - # @see RSpec.configure - # @see Core::Configuration - def self.configuration - @configuration ||= begin - config = RSpec::Core::Configuration.new - config.expose_dsl_globally = true - config - end - - end - - # Yields the global configuration to a block. - # @yield [Configuration] global configuration - # - # @example - # RSpec.configure do |config| - # config.add_formatter 'documentation' - # end - # @see Core::Configuration - def self.configure - yield configuration if block_given? - end - - # The example being executed. - # - # The primary audience for this method is library authors who need access - # to the example currently being executed and also want to support all - # versions of RSpec 2 and 3. - # - # @example - # - # RSpec.configure do |c| - # # context.example is deprecated, but RSpec.current_example is not - # # available until RSpec 3.0. - # fetch_current_example = RSpec.respond_to?(:current_example) ? - # proc { RSpec.current_example } : proc { |context| context.example } - # - # c.before(:example) do - # example = fetch_current_example.call(self) - # - # # ... - # end - # end - # - def self.current_example - thread_local_metadata[:current_example] - end - - # Set the current example being executed. - # @api private - def self.current_example=(example) - thread_local_metadata[:current_example] = example - end - - # @private - # A single thread local variable so we don't excessively pollute that - # namespace. - def self.thread_local_metadata - Thread.current[:_rspec] ||= {} - end - - # @private - # Internal container for global non-configuration data - def self.world - @world ||= RSpec::Core::World.new - end - - # Namespace for the rspec-core code. - module Core - # @private - # This avoids issues with reporting time caused by examples that - # change the value/meaning of Time.now without properly restoring - # it. - class Time - class << self - define_method(:now, &::Time.method(:now)) - end - end - - # @private path to executable file - def self.path_to_executable - @path_to_executable ||= File.expand_path('../../../exe/rspec', __FILE__) - end - end - - # @private - MODULES_TO_AUTOLOAD = { - :Matchers => "rspec/expectations", - :Expectations => "rspec/expectations", - :Mocks => "rspec/mocks" - } - - # @private - def self.const_missing(name) - # Load rspec-expectations when RSpec::Matchers is referenced. This allows - # people to define custom matchers (using `RSpec::Matchers.define`) before - # rspec-core has loaded rspec-expectations (since it delays the loading of - # it to allow users to configure a different assertion/expectation - # framework). `autoload` can't be used since it works with ruby's built-in - # require (e.g. for files that are available relative to a load path dir), - # but not with rubygems' extended require. - # - # As of rspec 2.14.1, we no longer require `rspec/mocks` and - # `rspec/expectations` when `rspec` is required, so we want - # to make them available as an autoload. - require MODULES_TO_AUTOLOAD.fetch(name) { return super } - ::RSpec.const_get(name) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/backport_random.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/backport_random.rb deleted file mode 100644 index 90046d5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/backport_random.rb +++ /dev/null @@ -1,336 +0,0 @@ -module RSpec - module Core - # @private - # - # Methods used internally by the backports. - # - # This code was (mostly) ported from the backports gem found at - # https://github.com/marcandre/backports which is subject to this license: - # - # ========================================================================= - # - # Copyright (c) 2009 Marc-Andre Lafortune - # - # Permission is hereby granted, free of charge, to any person obtaining - # a copy of this software and associated documentation files (the - # "Software"), to deal in the Software without restriction, including - # without limitation the rights to use, copy, modify, merge, publish, - # distribute, sublicense, and/or sell copies of the Software, and to - # permit persons to whom the Software is furnished to do so, subject to - # the following conditions: - # - # The above copyright notice and this permission notice shall be - # included in all copies or substantial portions of the Software. - # - # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - # - # ========================================================================= - # - # The goal is to provide a random number generator in Ruby versions that do - # not have one. This was added to support localization of random spec - # ordering. - # - # These were in multiple files in backports, but merged into one here. - module Backports - # Helper method to coerce a value into a specific class. - # Raises a TypeError if the coercion fails or the returned value - # is not of the right class. - # (from Rubinius) - def self.coerce_to(obj, cls, meth) - return obj if obj.kind_of?(cls) - - begin - ret = obj.__send__(meth) - rescue Exception => e - raise TypeError, "Coercion error: #{obj.inspect}.#{meth} => #{cls} failed:\n" \ - "(#{e.message})" - end - raise TypeError, "Coercion error: obj.#{meth} did NOT return a #{cls} (was #{ret.class})" unless ret.kind_of? cls - ret - end - - # @private - def self.coerce_to_int(obj) - coerce_to(obj, Integer, :to_int) - end - - # Used internally to make it easy to deal with optional arguments - # (from Rubinius) - Undefined = Object.new - - # @private - class Random - # @private - # An implementation of Mersenne Twister MT19937 in Ruby - class MT19937 - STATE_SIZE = 624 - LAST_STATE = STATE_SIZE - 1 - PAD_32_BITS = 0xffffffff - - # See seed= - def initialize(seed) - self.seed = seed - end - - LAST_31_BITS = 0x7fffffff - OFFSET = 397 - - # Generates a completely new state out of the previous one. - def next_state - STATE_SIZE.times do |i| - mix = @state[i] & 0x80000000 | @state[i+1 - STATE_SIZE] & 0x7fffffff - @state[i] = @state[i+OFFSET - STATE_SIZE] ^ (mix >> 1) - @state[i] ^= 0x9908b0df if mix.odd? - end - @last_read = -1 - end - - # Seed must be either an Integer (only the first 32 bits will be used) - # or an Array of Integers (of which only the first 32 bits will be used) - # - # No conversion or type checking is done at this level - def seed=(seed) - case seed - when Integer - @state = Array.new(STATE_SIZE) - @state[0] = seed & PAD_32_BITS - (1..LAST_STATE).each do |i| - @state[i] = (1812433253 * (@state[i-1] ^ @state[i-1]>>30) + i)& PAD_32_BITS - end - @last_read = LAST_STATE - when Array - self.seed = 19650218 - i=1 - j=0 - [STATE_SIZE, seed.size].max.times do - @state[i] = (@state[i] ^ (@state[i-1] ^ @state[i-1]>>30) * 1664525) + j + seed[j] & PAD_32_BITS - if (i+=1) >= STATE_SIZE - @state[0] = @state[-1] - i = 1 - end - j = 0 if (j+=1) >= seed.size - end - (STATE_SIZE-1).times do - @state[i] = (@state[i] ^ (@state[i-1] ^ @state[i-1]>>30) * 1566083941) - i & PAD_32_BITS - if (i+=1) >= STATE_SIZE - @state[0] = @state[-1] - i = 1 - end - end - @state[0] = 0x80000000 - else - raise ArgumentError, "Seed must be an Integer or an Array" - end - end - - # Returns a random Integer from the range 0 ... (1 << 32) - def random_32_bits - next_state if @last_read >= LAST_STATE - @last_read += 1 - y = @state[@last_read] - # Tempering - y ^= (y >> 11) - y ^= (y << 7) & 0x9d2c5680 - y ^= (y << 15) & 0xefc60000 - y ^= (y >> 18) - end - - # Supplement the MT19937 class with methods to do - # conversions the same way as MRI. - # No argument checking is done here either. - - FLOAT_FACTOR = 1.0/9007199254740992.0 - # generates a random number on [0,1) with 53-bit resolution - def random_float - ((random_32_bits >> 5) * 67108864.0 + (random_32_bits >> 6)) * FLOAT_FACTOR; - end - - # Returns an integer within 0...upto - def random_integer(upto) - n = upto - 1 - nb_full_32 = 0 - while n > PAD_32_BITS - n >>= 32 - nb_full_32 += 1 - end - mask = mask_32_bits(n) - begin - rand = random_32_bits & mask - nb_full_32.times do - rand <<= 32 - rand |= random_32_bits - end - end until rand < upto - rand - end - - def random_bytes(nb) - nb_32_bits = (nb + 3) / 4 - random = nb_32_bits.times.map { random_32_bits } - random.pack("L" * nb_32_bits)[0, nb] - end - - def state_as_bignum - b = 0 - @state.each_with_index do |val, i| - b |= val << (32 * i) - end - b - end - - def left # It's actually the number of words left + 1, as per MRI... - MT19937::STATE_SIZE - @last_read - end - - def marshal_dump - [state_as_bignum, left] - end - - def marshal_load(ary) - b, left = ary - @last_read = MT19937::STATE_SIZE - left - @state = Array.new(STATE_SIZE) - STATE_SIZE.times do |i| - @state[i] = b & PAD_32_BITS - b >>= 32 - end - end - - # Convert an Integer seed of arbitrary size to either a single 32 bit integer, or an Array of 32 bit integers - def self.convert_seed(seed) - seed = seed.abs - long_values = [] - begin - long_values << (seed & PAD_32_BITS) - seed >>= 32 - end until seed == 0 - - long_values.pop if long_values[-1] == 1 && long_values.size > 1 # Done to allow any kind of sequence of integers - - long_values.size > 1 ? long_values : long_values.first - end - - def self.[](seed) - new(convert_seed(seed)) - end - - private - - MASK_BY = [1,2,4,8,16] - def mask_32_bits(n) - MASK_BY.each do |shift| - n |= n >> shift - end - n - end - end - - # @private - # Implementation corresponding to the actual Random class of Ruby - # The actual random generator (mersenne twister) is in MT19937. - # Ruby specific conversions are handled in bits_and_bytes. - # The high level stuff (argument checking) is done here. - module Implementation - attr_reader :seed - - def initialize(seed = 0) - super() - seed_rand seed - end - - def seed_rand(new_seed = 0) - new_seed = Backports.coerce_to_int(new_seed) - @seed = nil unless defined?(@seed) - old, @seed = @seed, new_seed.nonzero? || Random.new_seed - @mt = MT19937[ @seed ] - old - end - - def rand(limit = Backports::Undefined) - case limit - when Backports::Undefined - @mt.random_float - when Float - limit * @mt.random_float unless limit <= 0 - when Range - _rand_range(limit) - else - limit = Backports.coerce_to_int(limit) - @mt.random_integer(limit) unless limit <= 0 - end || raise(ArgumentError, "invalid argument #{limit}") - end - - def bytes(nb) - nb = Backports.coerce_to_int(nb) - raise ArgumentError, "negative size" if nb < 0 - @mt.random_bytes(nb) - end - - def ==(other) - other.is_a?(Random) && - seed == other.seed && - left == other.send(:left) && - state == other.send(:state) - end - - def marshal_dump - @mt.marshal_dump << @seed - end - - def marshal_load(ary) - @seed = ary.pop - @mt = MT19937.allocate - @mt.marshal_load(ary) - end - - private - - def state - @mt.state_as_bignum - end - - def left - @mt.left - end - - def _rand_range(limit) - range = limit.end - limit.begin - if (!range.is_a?(Float)) && range.respond_to?(:to_int) && range = Backports.coerce_to_int(range) - range += 1 unless limit.exclude_end? - limit.begin + @mt.random_integer(range) unless range <= 0 - elsif range = Backports.coerce_to(range, Float, :to_f) - if range < 0 - nil - elsif limit.exclude_end? - limit.begin + @mt.random_float * range unless range <= 0 - else - # cheat a bit... this will reduce the nb of random bits - loop do - r = @mt.random_float * range * 1.0001 - break limit.begin + r unless r > range - end - end - end - end - end - - def self.new_seed - (2 ** 62) + Kernel.rand(2 ** 62) - end - end - - class Random - include Implementation - class << self - include Implementation - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/backtrace_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/backtrace_formatter.rb deleted file mode 100644 index 83a1874..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/backtrace_formatter.rb +++ /dev/null @@ -1,66 +0,0 @@ -module RSpec - module Core - # @private - class BacktraceFormatter - # @private - attr_accessor :exclusion_patterns, :inclusion_patterns - - def initialize - @full_backtrace = false - - patterns = [ - "/lib\d*/ruby/", - "org/jruby/", - "bin/", - "/gems/", - ].map { |s| Regexp.new(s.gsub("/", File::SEPARATOR)) } - - @system_exclusion_patterns = [Regexp.union(RSpec::CallerFilter::IGNORE_REGEX, *patterns)] - @exclusion_patterns = [] + @system_exclusion_patterns - @inclusion_patterns = [Regexp.new(Dir.getwd)] - end - - def full_backtrace=(full_backtrace) - @full_backtrace = full_backtrace - end - - def full_backtrace? - @full_backtrace || @exclusion_patterns.empty? - end - - def format_backtrace(backtrace, options = {}) - return backtrace if options[:full_backtrace] - - backtrace.map { |l| backtrace_line(l) }.compact. - tap do |filtered| - if filtered.empty? - filtered.concat backtrace - filtered << "" - filtered << " Showing full backtrace because every line was filtered out." - filtered << " See docs for RSpec::Configuration#backtrace_exclusion_patterns and" - filtered << " RSpec::Configuration#backtrace_inclusion_patterns for more information." - end - end - end - - def backtrace_line(line) - Metadata.relative_path(line) unless exclude?(line) - rescue SecurityError - nil - end - - def exclude?(line) - return false if @full_backtrace - relative_line = Metadata.relative_path(line) - return false unless matches?(@exclusion_patterns, relative_line) - matches?(@system_exclusion_patterns, relative_line) || !matches?(@inclusion_patterns, line) - end - - private - - def matches?(patterns, line) - patterns.any? { |p| line =~ p } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/configuration.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/configuration.rb deleted file mode 100644 index 963e9f0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/configuration.rb +++ /dev/null @@ -1,1343 +0,0 @@ -require 'fileutils' - -RSpec::Support.require_rspec_core "backtrace_formatter" -RSpec::Support.require_rspec_core "ruby_project" -RSpec::Support.require_rspec_core "formatters/deprecation_formatter" - -module RSpec - module Core - # Stores runtime configuration information. - # - # Configuration options are loaded from `~/.rspec`, `.rspec`, - # `.rspec-local`, command line switches, and the `SPEC_OPTS` environment - # variable (listed in lowest to highest precedence; for example, an option - # in `~/.rspec` can be overridden by an option in `.rspec-local`). - # - # @example Standard settings - # RSpec.configure do |c| - # c.drb = true - # c.drb_port = 1234 - # c.default_path = 'behavior' - # end - # - # @example Hooks - # RSpec.configure do |c| - # c.before(:suite) { establish_connection } - # c.before(:example) { log_in_as :authorized } - # c.around(:example) { |ex| Database.transaction(&ex) } - # end - # - # @see RSpec.configure - # @see Hooks - class Configuration - include RSpec::Core::Hooks - - # @private - class MustBeConfiguredBeforeExampleGroupsError < StandardError; end - - # @private - def self.define_reader(name) - define_method(name) do - variable = instance_variable_defined?("@#{name}") ? instance_variable_get("@#{name}") : nil - value_for(name, variable) - end - end - - # @private - def self.define_aliases(name, alias_name) - alias_method alias_name, name - alias_method "#{alias_name}=", "#{name}=" - define_predicate_for alias_name - end - - # @private - def self.define_predicate_for(*names) - names.each {|name| alias_method "#{name}?", name} - end - - # @private - # - # Invoked by the `add_setting` instance method. Use that method on a - # `Configuration` instance rather than this class method. - def self.add_setting(name, opts={}) - raise "Use the instance add_setting method if you want to set a default" if opts.has_key?(:default) - attr_writer name - add_read_only_setting name - - Array(opts[:alias_with]).each do |alias_name| - define_aliases(name, alias_name) - end - end - - # @private - # - # As `add_setting` but only add the reader - def self.add_read_only_setting(name, opts={}) - raise "Use the instance add_setting method if you want to set a default" if opts.has_key?(:default) - define_reader name - define_predicate_for name - end - - # @macro [attach] add_setting - # @!attribute [rw] $1 - # @!method $1=(value) - # - # @macro [attach] define_reader - # @!attribute [r] $1 - - # @macro add_setting - # Path to use if no path is provided to the `rspec` command (default: - # `"spec"`). Allows you to just type `rspec` instead of `rspec spec` to - # run all the examples in the `spec` directory. - add_setting :default_path - - # @macro add_setting - # Run examples over DRb (default: `false`). RSpec doesn't supply the DRb - # server, but you can use tools like spork. - add_setting :drb - - # @macro add_setting - # The drb_port (default: nil). - add_setting :drb_port - - # @macro add_setting - # Default: `$stderr`. - add_setting :error_stream - - # Indicates if the DSL has been exposed off of modules and `main`. - # Default: true - def expose_dsl_globally? - Core::DSL.exposed_globally? - end - - # Use this to expose the core RSpec DSL via `Module` and the `main` - # object. It will be set automatically but you can override it to - # remove the DSL. - # Default: true - def expose_dsl_globally=(value) - if value - Core::DSL.expose_globally! - Core::SharedExampleGroup::TopLevelDSL.expose_globally! - else - Core::DSL.remove_globally! - Core::SharedExampleGroup::TopLevelDSL.remove_globally! - end - end - - # Determines where deprecation warnings are printed. - # Defaults to `$stderr`. - # @return [IO, String] IO to write to or filename to write to - define_reader :deprecation_stream - - # Determines where deprecation warnings are printed. - # @param value [IO, String] IO to write to or filename to write to - def deprecation_stream=(value) - if @reporter && !value.equal?(@deprecation_stream) - warn "RSpec's reporter has already been initialized with " + - "#{deprecation_stream.inspect} as the deprecation stream, so your change to "+ - "`deprecation_stream` will be ignored. You should configure it earlier for " + - "it to take effect, or use the `--deprecation-out` CLI option. " + - "(Called from #{CallerFilter.first_non_rspec_line})" - else - @deprecation_stream = value - end - end - - # @macro add_setting - # Clean up and exit after the first failure (default: `false`). - add_setting :fail_fast - - # @macro add_setting - # Prints the formatter output of your suite without running any - # examples or hooks. - add_setting :dry_run - - # @macro add_setting - # The exit code to return if there are any failures (default: 1). - add_setting :failure_exit_code - - # @macro define_reader - # Indicates files configured to be required - define_reader :requires - - # @macro define_reader - # Returns dirs that have been prepended to the load path by the `-I` command line option - define_reader :libs - - # @macro add_setting - # Determines where RSpec will send its output. - # Default: `$stdout`. - define_reader :output_stream - - # Set the output stream for reporter - # @attr value [IO] value for output, defaults to $stdout - def output_stream=(value) - if @reporter && !value.equal?(@output_stream) - warn "RSpec's reporter has already been initialized with " + - "#{output_stream.inspect} as the output stream, so your change to "+ - "`output_stream` will be ignored. You should configure it earlier for " + - "it to take effect. (Called from #{CallerFilter.first_non_rspec_line})" - else - @output_stream = value - end - end - - # @macro define_reader - # Load files matching this pattern (default: `'**/*_spec.rb'`) - define_reader :pattern - - # Set pattern to match files to load - # @attr value [String] the filename pattern to filter spec files by - def pattern=(value) - if @spec_files_loaded - RSpec.warning "Configuring `pattern` to #{value} has no effect since RSpec has already loaded the spec files." - end - @pattern = value - end - - # @macro add_setting - # Report the times for the slowest examples (default: `false`). - # Use this to specify the number of examples to include in the profile. - add_setting :profile_examples - - # @macro add_setting - # Run all examples if none match the configured filters (default: `false`). - add_setting :run_all_when_everything_filtered - - # @macro add_setting - # Color to use to indicate success. - # @param color [Symbol] defaults to `:green` but can be set to one of the - # following: `[:black, :white, :red, :green, :yellow, - # :blue, :magenta, :cyan]` - add_setting :success_color - - # @macro add_setting - # Color to use to print pending examples. - # @param color [Symbol] defaults to `:yellow` but can be set to one of the - # following: `[:black, :white, :red, :green, :yellow, - # :blue, :magenta, :cyan]` - add_setting :pending_color - - # @macro add_setting - # Color to use to indicate failure. - # @param color [Symbol] defaults to `:red` but can be set to one of the - # following: `[:black, :white, :red, :green, :yellow, - # :blue, :magenta, :cyan]` - add_setting :failure_color - - # @macro add_setting - # The default output color. - # @param color [Symbol] defaults to `:white` but can be set to one of the - # following:`[:black, :white, :red, :green, :yellow, - # :blue, :magenta, :cyan]` - add_setting :default_color - - # @macro add_setting - # Color used when a pending example is fixed. - # @param color [Symbol] defaults to `:blue` but can be set to one of the - # following: `[:black, :white, :red, :green, :yellow, - # :blue, :magenta, :cyan]` - add_setting :fixed_color - - # @macro add_setting - # Color used to print details. - # @param color [Symbol] defaults to `:cyan` but can be set to one of the - # following: `[:black, :white, :red, :green, :yellow, - # :blue, :magenta, :cyan]` - add_setting :detail_color - - # Deprecated. This config option was added in RSpec 2 to pave the way - # for this being the default behavior in RSpec 3. Now this option is - # a no-op. - def treat_symbols_as_metadata_keys_with_true_values=(value) - RSpec.deprecate("RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values=", - :message => "RSpec::Core::Configuration#treat_symbols_as_metadata_keys_with_true_values= " + - "is deprecated, it is now set to true as default and setting it to false has no effect.") - end - - # Record the start time of the spec suite to measure load time - add_setting :start_time - - # @private - add_setting :tty - # @private - add_setting :include_or_extend_modules - # @private - attr_writer :files_to_run - # @private - add_setting :expecting_with_rspec - # @private - attr_accessor :filter_manager - # @private - attr_reader :backtrace_formatter, :ordering_manager - - def initialize - @start_time = $_rspec_core_load_started_at || ::RSpec::Core::Time.now - @expectation_frameworks = [] - @include_or_extend_modules = [] - @mock_framework = nil - @files_or_directories_to_run = [] - @color = false - @pattern = '**/*_spec.rb' - @failure_exit_code = 1 - @spec_files_loaded = false - - @backtrace_formatter = BacktraceFormatter.new - - @default_path = 'spec' - @deprecation_stream = $stderr - @output_stream = $stdout - @reporter = nil - @reporter_buffer = nil - @filter_manager = FilterManager.new - @ordering_manager = Ordering::ConfigurationManager.new - @preferred_options = {} - @failure_color = :red - @success_color = :green - @pending_color = :yellow - @default_color = :white - @fixed_color = :blue - @detail_color = :cyan - @profile_examples = false - @requires = [] - @libs = [] - @derived_metadata_blocks = [] - end - - # @private - # - # Used to set higher priority option values from the command line. - def force(hash) - ordering_manager.force(hash) - @preferred_options.merge!(hash) - end - - # @private - def reset - @spec_files_loaded = false - @reporter = nil - @formatter_loader = nil - end - - # @overload add_setting(name) - # @overload add_setting(name, opts) - # @option opts [Symbol] :default - # - # set a default value for the generated getter and predicate methods: - # - # add_setting(:foo, :default => "default value") - # - # @option opts [Symbol] :alias_with - # - # Use `:alias_with` to alias the setter, getter, and predicate to another - # name, or names: - # - # add_setting(:foo, :alias_with => :bar) - # add_setting(:foo, :alias_with => [:bar, :baz]) - # - # Adds a custom setting to the RSpec.configuration object. - # - # RSpec.configuration.add_setting :foo - # - # Used internally and by extension frameworks like rspec-rails, so they - # can add config settings that are domain specific. For example: - # - # RSpec.configure do |c| - # c.add_setting :use_transactional_fixtures, - # :default => true, - # :alias_with => :use_transactional_examples - # end - # - # `add_setting` creates three methods on the configuration object, a - # setter, a getter, and a predicate: - # - # RSpec.configuration.foo=(value) - # RSpec.configuration.foo - # RSpec.configuration.foo? # returns true if foo returns anything but nil or false - def add_setting(name, opts={}) - default = opts.delete(:default) - (class << self; self; end).class_exec do - add_setting(name, opts) - end - __send__("#{name}=", default) if default - end - - # Returns the configured mock framework adapter module - def mock_framework - mock_with :rspec unless @mock_framework - @mock_framework - end - - # Delegates to mock_framework=(framework) - def mock_framework=(framework) - mock_with framework - end - - # Regexps used to exclude lines from backtraces. - # - # Excludes lines from ruby (and jruby) source, installed gems, anything - # in any "bin" directory, and any of the rspec libs (outside gem - # installs) by default. - # - # You can modify the list via the getter, or replace it with the setter. - # - # To override this behaviour and display a full backtrace, use - # `--backtrace`on the command line, in a `.rspec` file, or in the - # `rspec_options` attribute of RSpec's rake task. - def backtrace_exclusion_patterns - @backtrace_formatter.exclusion_patterns - end - - # Set regular expressions used to exclude lines in backtrace - # @param patterns [Regexp] set the backtrace exlusion pattern - def backtrace_exclusion_patterns=(patterns) - @backtrace_formatter.exclusion_patterns = patterns - end - - # Regexps used to include lines in backtraces. - # - # Defaults to [Regexp.new Dir.getwd]. - # - # Lines that match an exclusion _and_ an inclusion pattern - # will be included. - # - # You can modify the list via the getter, or replace it with the setter. - def backtrace_inclusion_patterns - @backtrace_formatter.inclusion_patterns - end - - # Set regular expressions used to include lines in backtrace - # @attr patterns [Regexp] set backtrace_formatter inclusion_patterns - def backtrace_inclusion_patterns=(patterns) - @backtrace_formatter.inclusion_patterns = patterns - end - - # @private - MOCKING_ADAPTERS = { - :rspec => :RSpec, - :flexmock => :Flexmock, - :rr => :RR, - :mocha => :Mocha, - :nothing => :Null - } - - # Sets the mock framework adapter module. - # - # `framework` can be a Symbol or a Module. - # - # Given any of `:rspec`, `:mocha`, `:flexmock`, or `:rr`, configures the - # named framework. - # - # Given `:nothing`, configures no framework. Use this if you don't use - # any mocking framework to save a little bit of overhead. - # - # Given a Module, includes that module in every example group. The module - # should adhere to RSpec's mock framework adapter API: - # - # setup_mocks_for_rspec - # - called before each example - # - # verify_mocks_for_rspec - # - called after each example if the example hasn't yet failed. - # Framework should raise an exception when expectations fail - # - # teardown_mocks_for_rspec - # - called after verify_mocks_for_rspec (even if there are errors) - # - # If the module responds to `configuration` and `mock_with` receives a block, - # it will yield the configuration object to the block e.g. - # - # config.mock_with OtherMockFrameworkAdapter do |mod_config| - # mod_config.custom_setting = true - # end - def mock_with(framework) - framework_module = if framework.is_a?(Module) - framework - else - const_name = MOCKING_ADAPTERS.fetch(framework) do - raise ArgumentError, - "Unknown mocking framework: #{framework.inspect}. " + - "Pass a module or one of #{MOCKING_ADAPTERS.keys.inspect}" - end - - RSpec::Support.require_rspec_core "mocking_adapters/#{const_name.to_s.downcase}" - RSpec::Core::MockingAdapters.const_get(const_name) - end - - new_name, old_name = [framework_module, @mock_framework].map do |mod| - mod.respond_to?(:framework_name) ? mod.framework_name : :unnamed - end - - unless new_name == old_name - assert_no_example_groups_defined(:mock_framework) - end - - if block_given? - raise "#{framework_module} must respond to `configuration` so that mock_with can yield it." unless framework_module.respond_to?(:configuration) - yield framework_module.configuration - end - - @mock_framework = framework_module - end - - # Returns the configured expectation framework adapter module(s) - def expectation_frameworks - expect_with :rspec if @expectation_frameworks.empty? - @expectation_frameworks - end - - # Delegates to expect_with(framework) - def expectation_framework=(framework) - expect_with(framework) - end - - # Sets the expectation framework module(s) to be included in each example - # group. - # - # `frameworks` can be `:rspec`, `:test_unit`, `:minitest`, a custom - # module, or any combination thereof: - # - # config.expect_with :rspec - # config.expect_with :test_unit - # config.expect_with :minitest - # config.expect_with :rspec, :minitest - # config.expect_with OtherExpectationFramework - # - # RSpec will translate `:rspec`, `:minitest`, and `:test_unit` into the - # appropriate modules. - # - # ## Configuration - # - # If the module responds to `configuration`, `expect_with` will - # yield the `configuration` object if given a block: - # - # config.expect_with OtherExpectationFramework do |custom_config| - # custom_config.custom_setting = true - # end - def expect_with(*frameworks) - modules = frameworks.map do |framework| - case framework - when Module - framework - when :rspec - require 'rspec/expectations' - self.expecting_with_rspec = true - ::RSpec::Matchers - when :test_unit - require 'rspec/core/test_unit_assertions_adapter' - ::RSpec::Core::TestUnitAssertionsAdapter - when :minitest - require 'rspec/core/minitest_assertions_adapter' - ::RSpec::Core::MinitestAssertionsAdapter - else - raise ArgumentError, "#{framework.inspect} is not supported" - end - end - - if (modules - @expectation_frameworks).any? - assert_no_example_groups_defined(:expect_with) - end - - if block_given? - raise "expect_with only accepts a block with a single argument. Call expect_with #{modules.length} times, once with each argument, instead." if modules.length > 1 - raise "#{modules.first} must respond to `configuration` so that expect_with can yield it." unless modules.first.respond_to?(:configuration) - yield modules.first.configuration - end - - @expectation_frameworks.push(*modules) - end - - # Check if full backtrace is enabled - # @return [Boolean] is full backtrace enabled - def full_backtrace? - @backtrace_formatter.full_backtrace? - end - - # Toggle full backtrace - # @attr true_or_false [Boolean] toggle full backtrace display - def full_backtrace=(true_or_false) - @backtrace_formatter.full_backtrace = true_or_false - end - - # Returns the configuration option for color, but should not - # be used to check if color is supported. - # - # @see color_enabled? - # @return [Boolean] - def color - value_for(:color, @color) - end - - # Check if color is enabled for a particular output - # @param output [IO] an output stream to use, defaults to the current - # `output_stream` - # @return [Boolean] - def color_enabled?(output = output_stream) - output_to_tty?(output) && color - end - - # Toggle output color - # @attr true_or_false [Boolean] toggle color enabled - def color=(true_or_false) - if true_or_false - if RSpec.world.windows_os? and not ENV['ANSICON'] - RSpec.warning "You must use ANSICON 1.31 or later (http://adoxa.3eeweb.com/ansicon/) to use colour on Windows" - @color = false - else - @color = true - end - end - end - - # @private - def libs=(libs) - libs.map do |lib| - @libs.unshift lib - $LOAD_PATH.unshift lib - end - end - - # Run examples matching on `description` in all files to run. - # @param description [String, Regexp] the pattern to filter on - def full_description=(description) - filter_run :full_description => Regexp.union(*Array(description).map {|d| Regexp.new(d) }) - end - - # @return [Array] full description filter - def full_description - filter.fetch :full_description, nil - end - - # @overload add_formatter(formatter) - # - # Adds a formatter to the formatters collection. `formatter` can be a - # string representing any of the built-in formatters (see - # `built_in_formatter`), or a custom formatter class. - # - # ### Note - # - # For internal purposes, `add_formatter` also accepts the name of a class - # and paths to use for output streams, but you should consider that a - # private api that may change at any time without notice. - def add_formatter(formatter_to_use, *paths) - paths << output_stream if paths.empty? - formatter_loader.add formatter_to_use, *paths - end - alias_method :formatter=, :add_formatter - - # The formatter that will be used if no formatter has been set. - # Defaults to 'progress'. - def default_formatter - formatter_loader.default_formatter - end - - # Sets a fallback formatter to use if none other has been set. - # - # @example - # - # RSpec.configure do |rspec| - # rspec.default_formatter = 'doc' - # end - def default_formatter=(value) - formatter_loader.default_formatter = value - end - - # Returns a duplicate of the formatters currently loaded in - # the `FormatterLoader` for introspection. - # - # Note as this is a duplicate, any mutations will be disregarded. - # - # @return [Array] the formatters currently loaded - def formatters - formatter_loader.formatters.dup - end - - # @private - def formatter_loader - @formatter_loader ||= Formatters::Loader.new(Reporter.new(self)) - end - - # @private - # - # This buffer is used to capture all messages sent to the reporter during - # reporter initialization. It can then replay those messages after the - # formatter is correctly initialized. Otherwise, deprecation warnings - # during formatter initialization can cause an infinite loop. - class DeprecationReporterBuffer - def initialize - @calls = [] - end - - def deprecation(*args) - @calls << args - end - - def play_onto(reporter) - @calls.each do |args| - reporter.deprecation(*args) - end - end - end - - # @private - def reporter - # @reporter_buffer should only ever be set in this method to cover - # initialization of @reporter. - @reporter_buffer || @reporter ||= - begin - @reporter_buffer = DeprecationReporterBuffer.new - formatter_loader.setup_default output_stream, deprecation_stream - @reporter_buffer.play_onto(formatter_loader.reporter) - @reporter_buffer = nil - formatter_loader.reporter - end - end - - # @api private - # - # Defaults `profile_examples` to 10 examples when `@profile_examples` is `true`. - # - def profile_examples - profile = value_for(:profile_examples, @profile_examples) - if profile && !profile.is_a?(Integer) - 10 - else - profile - end - end - - # @private - def files_or_directories_to_run=(*files) - files = files.flatten - files << default_path if (command == 'rspec' || Runner.running_in_drb?) && default_path && files.empty? - @files_or_directories_to_run = files - @files_to_run = nil - end - - # The spec files RSpec will run - # @return [Array] specified files about to run - def files_to_run - @files_to_run ||= get_files_to_run(@files_or_directories_to_run) - end - - # Creates a method that delegates to `example` including the submitted - # `args`. Used internally to add variants of `example` like `pending`: - # @param name [String] example name alias - # @param args [Array, Hash] metadata for the generated example - # - # @note The specific example alias below (`pending`) is already - # defined for you. - # @note Use with caution. This extends the language used in your - # specs, but does not add any additional documentation. We use this - # in rspec to define methods like `focus` and `xit`, but we also add - # docs for those methods. - # - # @example - # RSpec.configure do |config| - # config.alias_example_to :pending, :pending => true - # end - # - # # This lets you do this: - # - # describe Thing do - # pending "does something" do - # thing = Thing.new - # end - # end - # - # # ... which is the equivalent of - # - # describe Thing do - # it "does something", :pending => true do - # thing = Thing.new - # end - # end - def alias_example_to(name, *args) - extra_options = Metadata.build_hash_from(args) - RSpec::Core::ExampleGroup.define_example_method(name, extra_options) - end - - # Creates a method that defines an example group with the provided - # metadata. Can be used to define example group/metadata shortcuts. - # - # @example - # RSpec.configure do |config| - # config.alias_example_group_to :describe_model, :type => :model - # end - # - # shared_context_for "model tests", :type => :model do - # # define common model test helper methods, `let` declarations, etc - # end - # - # # This lets you do this: - # - # RSpec.describe_model User do - # end - # - # # ... which is the equivalent of - # - # RSpec.describe User, :type => :model do - # end - # - # @note The defined aliased will also be added to the top level - # (e.g. `main` and from within modules) if - # `expose_dsl_globally` is set to true. - # @see #alias_example_to - # @see #expose_dsl_globally= - def alias_example_group_to(new_name, *args) - extra_options = Metadata.build_hash_from(args) - RSpec::Core::ExampleGroup.define_example_group_method(new_name, extra_options) - end - - # Define an alias for it_should_behave_like that allows different - # language (like "it_has_behavior" or "it_behaves_like") to be - # employed when including shared examples. - # - # @example - # RSpec.configure do |config| - # config.alias_it_behaves_like_to(:it_has_behavior, 'has behavior:') - # end - # - # # allows the user to include a shared example group like: - # - # describe Entity do - # it_has_behavior 'sortability' do - # let(:sortable) { Entity.new } - # end - # end - # - # # which is reported in the output as: - # # Entity - # # has behavior: sortability - # # ...sortability examples here - # - # @note Use with caution. This extends the language used in your - # specs, but does not add any additional documentation. We use this - # in rspec to define `it_should_behave_like` (for backward - # compatibility), but we also add docs for that method. - def alias_it_behaves_like_to(new_name, report_label = '') - RSpec::Core::ExampleGroup.define_nested_shared_group_method(new_name, report_label) - end - alias_method :alias_it_should_behave_like_to, :alias_it_behaves_like_to - - # Adds key/value pairs to the `inclusion_filter`. If `args` - # includes any symbols that are not part of the hash, each symbol - # is treated as a key in the hash with the value `true`. - # - # ### Note - # - # Filters set using this method can be overridden from the command line - # or config files (e.g. `.rspec`). - # - # @example - # # given this declaration - # describe "something", :foo => 'bar' do - # # ... - # end - # - # # any of the following will include that group - # config.filter_run_including :foo => 'bar' - # config.filter_run_including :foo => /^ba/ - # config.filter_run_including :foo => lambda {|v| v == 'bar'} - # config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'} - # - # # given a proc with an arity of 1, the lambda is passed the value related to the key, e.g. - # config.filter_run_including :foo => lambda {|v| v == 'bar'} - # - # # given a proc with an arity of 2, the lambda is passed the value related to the key, - # # and the metadata itself e.g. - # config.filter_run_including :foo => lambda {|v,m| m[:foo] == 'bar'} - # - # filter_run_including :foo # same as filter_run_including :foo => true - def filter_run_including(*args) - meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering) - filter_manager.include_with_low_priority meta - end - - alias_method :filter_run, :filter_run_including - - # Clears and reassigns the `inclusion_filter`. Set to `nil` if you don't - # want any inclusion filter at all. - # - # ### Warning - # - # This overrides any inclusion filters/tags set on the command line or in - # configuration files. - def inclusion_filter=(filter) - meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering) - filter_manager.include_only meta - end - - alias_method :filter=, :inclusion_filter= - - # Returns the `inclusion_filter`. If none has been set, returns an empty - # hash. - def inclusion_filter - filter_manager.inclusions - end - - alias_method :filter, :inclusion_filter - - # Adds key/value pairs to the `exclusion_filter`. If `args` - # includes any symbols that are not part of the hash, each symbol - # is treated as a key in the hash with the value `true`. - # - # ### Note - # - # Filters set using this method can be overridden from the command line - # or config files (e.g. `.rspec`). - # - # @example - # # given this declaration - # describe "something", :foo => 'bar' do - # # ... - # end - # - # # any of the following will exclude that group - # config.filter_run_excluding :foo => 'bar' - # config.filter_run_excluding :foo => /^ba/ - # config.filter_run_excluding :foo => lambda {|v| v == 'bar'} - # config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'} - # - # # given a proc with an arity of 1, the lambda is passed the value related to the key, e.g. - # config.filter_run_excluding :foo => lambda {|v| v == 'bar'} - # - # # given a proc with an arity of 2, the lambda is passed the value related to the key, - # # and the metadata itself e.g. - # config.filter_run_excluding :foo => lambda {|v,m| m[:foo] == 'bar'} - # - # filter_run_excluding :foo # same as filter_run_excluding :foo => true - def filter_run_excluding(*args) - meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering) - filter_manager.exclude_with_low_priority meta - end - - # Clears and reassigns the `exclusion_filter`. Set to `nil` if you don't - # want any exclusion filter at all. - # - # ### Warning - # - # This overrides any exclusion filters/tags set on the command line or in - # configuration files. - def exclusion_filter=(filter) - meta = Metadata.build_hash_from([filter], :warn_about_example_group_filtering) - filter_manager.exclude_only meta - end - - # Returns the `exclusion_filter`. If none has been set, returns an empty - # hash. - def exclusion_filter - filter_manager.exclusions - end - - # Tells RSpec to include `mod` in example groups. Methods defined in - # `mod` are exposed to examples (not example groups). Use `filters` to - # constrain the groups in which to include the module. - # - # @example - # - # module AuthenticationHelpers - # def login_as(user) - # # ... - # end - # end - # - # module UserHelpers - # def users(username) - # # ... - # end - # end - # - # RSpec.configure do |config| - # config.include(UserHelpers) # included in all modules - # config.include(AuthenticationHelpers, :type => :request) - # end - # - # describe "edit profile", :type => :request do - # it "can be viewed by owning user" do - # login_as users(:jdoe) - # get "/profiles/jdoe" - # assert_select ".username", :text => 'jdoe' - # end - # end - # - # @see #extend - def include(mod, *filters) - meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering) - include_or_extend_modules << [:include, mod, meta] - end - - # Tells RSpec to extend example groups with `mod`. Methods defined in - # `mod` are exposed to example groups (not examples). Use `filters` to - # constrain the groups to extend. - # - # Similar to `include`, but behavior is added to example groups, which - # are classes, rather than the examples, which are instances of those - # classes. - # - # @example - # - # module UiHelpers - # def run_in_browser - # # ... - # end - # end - # - # RSpec.configure do |config| - # config.extend(UiHelpers, :type => :request) - # end - # - # describe "edit profile", :type => :request do - # run_in_browser - # - # it "does stuff in the client" do - # # ... - # end - # end - # - # @see #include - def extend(mod, *filters) - meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering) - include_or_extend_modules << [:extend, mod, meta] - end - - # @private - # - # Used internally to extend a group with modules using `include` and/or - # `extend`. - def configure_group(group) - include_or_extend_modules.each do |include_or_extend, mod, filters| - next unless filters.empty? || group.any_apply?(filters) - __send__("safe_#{include_or_extend}", mod, group) - end - end - - # @private - def safe_include(mod, host) - host.__send__(:include, mod) unless host < mod - end - - # @private - def requires=(paths) - directories = ['lib', default_path].select { |p| File.directory? p } - RSpec::Core::RubyProject.add_to_load_path(*directories) - paths.each {|path| require path} - @requires += paths - end - - # @private - if RUBY_VERSION.to_f >= 1.9 - # @private - def safe_extend(mod, host) - host.extend(mod) unless host.singleton_class < mod - end - else - # @private - def safe_extend(mod, host) - host.extend(mod) unless (class << host; self; end).included_modules.include?(mod) - end - end - - # @private - def configure_mock_framework - RSpec::Core::ExampleGroup.__send__(:include, mock_framework) - conditionally_disable_mocks_monkey_patching - end - - # @private - def configure_expectation_framework - expectation_frameworks.each do |framework| - RSpec::Core::ExampleGroup.__send__(:include, framework) - end - conditionally_disable_expectations_monkey_patching - end - - # @private - def load_spec_files - files_to_run.uniq.each {|f| load File.expand_path(f) } - @spec_files_loaded = true - end - - # @private - DEFAULT_FORMATTER = lambda { |string| string } - - # Formats the docstring output using the block provided. - # - # @example - # # This will strip the descriptions of both examples and example groups. - # RSpec.configure do |config| - # config.format_docstrings { |s| s.strip } - # end - def format_docstrings(&block) - @format_docstrings_block = block_given? ? block : DEFAULT_FORMATTER - end - - # @private - def format_docstrings_block - @format_docstrings_block ||= DEFAULT_FORMATTER - end - - # @private - # @macro [attach] delegate_to_ordering_manager - # @!method $1 - def self.delegate_to_ordering_manager(*methods) - methods.each do |method| - define_method method do |*args, &block| - ordering_manager.__send__(method, *args, &block) - end - end - end - - # @macro delegate_to_ordering_manager - # - # Sets the seed value and sets the default global ordering to random. - delegate_to_ordering_manager :seed= - - # @macro delegate_to_ordering_manager - # Seed for random ordering (default: generated randomly each run). - # - # When you run specs with `--order random`, RSpec generates a random seed - # for the randomization and prints it to the `output_stream` (assuming - # you're using RSpec's built-in formatters). If you discover an ordering - # dependency (i.e. examples fail intermittently depending on order), set - # this (on Configuration or on the command line with `--seed`) to run - # using the same seed while you debug the issue. - # - # We recommend, actually, that you use the command line approach so you - # don't accidentally leave the seed encoded. - delegate_to_ordering_manager :seed - - # @macro delegate_to_ordering_manager - # - # Sets the default global order and, if order is `'rand:'`, also sets the seed. - delegate_to_ordering_manager :order= - - # @macro delegate_to_ordering_manager - # Registers a named ordering strategy that can later be - # used to order an example group's subgroups by adding - # `:order => ` metadata to the example group. - # - # @param name [Symbol] The name of the ordering. - # @yield Block that will order the given examples or example groups - # @yieldparam list [Array, Array] The examples or groups to order - # @yieldreturn [Array, Array] The re-ordered examples or groups - # - # @example - # RSpec.configure do |rspec| - # rspec.register_ordering :reverse do |list| - # list.reverse - # end - # end - # - # describe MyClass, :order => :reverse do - # # ... - # end - # - # @note Pass the symbol `:global` to set the ordering strategy that - # will be used to order the top-level example groups and any example - # groups that do not have declared `:order` metadata. - delegate_to_ordering_manager :register_ordering - - # @private - delegate_to_ordering_manager :seed_used?, :ordering_registry - - # Set Ruby warnings on or off - def warnings=(value) - $VERBOSE = !!value - end - - # @return [Boolean] Whether or not ruby warnings are enabled. - def warnings? - $VERBOSE - end - - # Exposes the current running example via the named - # helper method. RSpec 2.x exposed this via `example`, - # but in RSpec 3.0, the example is instead exposed via - # an arg yielded to `it`, `before`, `let`, etc. However, - # some extension gems (such as Capybara) depend on the - # RSpec 2.x's `example` method, so this config option - # can be used to maintain compatibility. - # - # @param method_name [Symbol] the name of the helper method - # - # @example - # - # RSpec.configure do |rspec| - # rspec.expose_current_running_example_as :example - # end - # - # describe MyClass do - # before do - # # `example` can be used here because of the above config. - # do_something if example.metadata[:type] == "foo" - # end - # end - def expose_current_running_example_as(method_name) - ExposeCurrentExample.module_exec do - extend RSpec::SharedContext - let(method_name) { |ex| ex } - end - - include ExposeCurrentExample - end - - # @private - module ExposeCurrentExample; end - - # Turns deprecation warnings into errors, in order to surface - # the full backtrace of the call site. This can be useful when - # you need more context to address a deprecation than the - # single-line call site normally provided. - # - # @example - # - # RSpec.configure do |rspec| - # rspec.raise_errors_for_deprecations! - # end - def raise_errors_for_deprecations! - self.deprecation_stream = Formatters::DeprecationFormatter::RaiseErrorStream.new - end - - # Enables zero monkey patching mode for RSpec. It removes monkey - # patching of the top-level DSL methods (`describe`, - # `shared_examples_for`, etc) onto `main` and `Module`, instead - # requiring you to prefix these methods with `RSpec.`. It enables - # expect-only syntax for rspec-mocks and rspec-expectations. It - # simply disables monkey patching on whatever pieces of rspec - # the user is using. - # - # @note It configures rspec-mocks and rspec-expectations only - # if the user is using those (either explicitly or implicitly - # by not setting `mock_with` or `expect_with` to anything else). - # - # @note If the user uses this options with `mock_with :mocha` - # (or similiar) they will still have monkey patching active - # in their test environment from mocha. - # - # @example - # - # # It disables all monkey patching - # RSpec.configure do |config| - # config.disable_monkey_patching! - # end - # - # # Is an equivalent to - # RSpec.configure do |config| - # config.expose_dsl_globally = false - # - # config.mock_with :rspec do |mocks| - # mocks.syntax = :expect - # mocks.patch_marshal_to_support_partial_doubles = false - # end - # - # config.mock_with :rspec do |expectations| - # expectations.syntax = :expect - # end - # end - def disable_monkey_patching! - self.expose_dsl_globally = false - self.disable_monkey_patching = true - conditionally_disable_mocks_monkey_patching - conditionally_disable_expectations_monkey_patching - end - - # @private - attr_accessor :disable_monkey_patching - - # Defines a callback that can assign derived metadata values. - # - # @param filters [Array, Hash] metadata filters that determine which example - # or group metadata hashes the callback will be triggered for. If none are given, - # the callback will be run against the metadata hashes of all groups and examples. - # @yieldparam metadata [Hash] original metadata hash from an example or group. Mutate this in - # your block as needed. - # - # @example - # RSpec.configure do |config| - # # Tag all groups and examples in the spec/unit directory with :type => :unit - # config.define_derived_metadata(:file_path => %r{/spec/unit/}) do |metadata| - # metadata[:type] = :unit - # end - # end - def define_derived_metadata(*filters, &block) - meta = Metadata.build_hash_from(filters, :warn_about_example_group_filtering) - @derived_metadata_blocks << [meta, block] - end - - # @private - def apply_derived_metadata_to(metadata) - @derived_metadata_blocks.each do |filter, block| - block.call(metadata) if filter.empty? || MetadataFilter.any_apply?(filter, metadata) - end - end - - private - - def get_files_to_run(paths) - FlatMap.flat_map(paths) do |path| - path = path.gsub(File::ALT_SEPARATOR, File::SEPARATOR) if File::ALT_SEPARATOR - File.directory?(path) ? gather_directories(path) : extract_location(path) - end.sort - end - - def gather_directories(path) - stripped = "{#{pattern.gsub(/\s*,\s*/, ',')}}" - files = pattern =~ /^#{Regexp.escape path}/ ? Dir[stripped] : Dir["#{path}/#{stripped}"] - files.sort - end - - def extract_location(path) - if path =~ /^(.*?)((?:\:\d+)+)$/ - path, lines = $1, $2[1..-1].split(":").map{|n| n.to_i} - filter_manager.add_location path, lines - end - path - end - - def command - $0.split(File::SEPARATOR).last - end - - def value_for(key, default=nil) - @preferred_options.has_key?(key) ? @preferred_options[key] : default - end - - def assert_no_example_groups_defined(config_option) - if RSpec.world.example_groups.any? - raise MustBeConfiguredBeforeExampleGroupsError.new( - "RSpec's #{config_option} configuration option must be configured before " + - "any example groups are defined, but you have already defined a group." - ) - end - end - - def output_to_tty?(output=output_stream) - tty? || (output.respond_to?(:tty?) && output.tty?) - end - - def conditionally_disable_mocks_monkey_patching - return unless disable_monkey_patching && rspec_mocks_loaded? - - RSpec::Mocks.configuration.tap do |config| - config.syntax = :expect - config.patch_marshal_to_support_partial_doubles = false - end - end - - def conditionally_disable_expectations_monkey_patching - return unless disable_monkey_patching && rspec_expectations_loaded? - - RSpec::Expectations.configuration.syntax = :expect - end - - def rspec_mocks_loaded? - defined?(RSpec::Mocks.configuration) - end - - def rspec_expectations_loaded? - defined?(RSpec::Expectations.configuration) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/configuration_options.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/configuration_options.rb deleted file mode 100644 index e5e9818..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/configuration_options.rb +++ /dev/null @@ -1,173 +0,0 @@ -require 'erb' -require 'shellwords' -require 'set' - -module RSpec - module Core - # Responsible for utilizing externally provided configuration options, - # whether via the command line, `.rspec`, `~/.rspec`, `.rspec-local` - # or a custom options file. - class ConfigurationOptions - # @param args [Array] command line arguments - def initialize(args) - @args = args.dup - organize_options - end - - # Updates the provided {Configuration} instance based on the provided - # external configuration options. - # - # @param config [Configuration] the configuration instance to update - def configure(config) - process_options_into config - configure_filter_manager config.filter_manager - load_formatters_into config - end - - # @api private - # Updates the provided {FilterManager} based on the filter options. - # @param filter_manager [FilterManager] instance to update - def configure_filter_manager(filter_manager) - @filter_manager_options.each do |command, value| - filter_manager.__send__ command, value - end - end - - # @return [Hash] the final merged options, drawn from all external sources - attr_reader :options - - private - - def organize_options - @filter_manager_options = [] - - @options = (file_options << command_line_options << env_options).each { |opts| - @filter_manager_options << [:include, opts.delete(:inclusion_filter)] if opts.key?(:inclusion_filter) - @filter_manager_options << [:exclude, opts.delete(:exclusion_filter)] if opts.key?(:exclusion_filter) - }.inject(:libs => [], :requires => []) { |hash, opts| - hash.merge(opts) { |key, oldval, newval| - [:libs, :requires].include?(key) ? oldval + newval : newval - } - } - end - - UNFORCED_OPTIONS = [ - :requires, :profile, :drb, :libs, :files_or_directories_to_run, - :full_description, :full_backtrace, :tty - ].to_set - - UNPROCESSABLE_OPTIONS = [:formatters].to_set - - def force?(key) - !UNFORCED_OPTIONS.include?(key) - end - - def order(keys) - OPTIONS_ORDER.reverse.each do |key| - keys.unshift(key) if keys.delete(key) - end - keys - end - - OPTIONS_ORDER = [ - # It's important to set this before anything that might issue a - # deprecation (or otherwise access the reporter). - :deprecation_stream, - - # load paths depend on nothing, but must be set before `requires` - # to support load-path-relative requires. - :libs, - - # `files_or_directories_to_run` uses `default_path` so it must be - # set before it. - :default_path, - - # must be set before `requires` to support checking `config.files_to_run` - # from within `spec_helper.rb` when a `-rspec_helper` option is used. - :files_or_directories_to_run, - - # In general, we want to require the specified files as early as possible. - # The `--require` option is specifically intended to allow early requires. - # For later requires, they can just put the require in their spec files, but - # `--require` provides a unique opportunity for users to instruct RSpec to - # load an extension file early for maximum flexibility. - :requires - ] - - def process_options_into(config) - opts = options.reject { |k, _| UNPROCESSABLE_OPTIONS.include? k } - - order(opts.keys).each do |key| - force?(key) ? config.force(key => opts[key]) : config.__send__("#{key}=", opts[key]) - end - end - - def load_formatters_into(config) - options[:formatters].each { |pair| config.add_formatter(*pair) } if options[:formatters] - end - - def file_options - custom_options_file ? [custom_options] : [global_options, project_options, local_options] - end - - def env_options - ENV["SPEC_OPTS"] ? Parser.parse(Shellwords.split(ENV["SPEC_OPTS"])) : {} - end - - def command_line_options - @command_line_options ||= Parser.parse(@args).merge :files_or_directories_to_run => @args - end - - def custom_options - options_from(custom_options_file) - end - - def local_options - @local_options ||= options_from(local_options_file) - end - - def project_options - @project_options ||= options_from(project_options_file) - end - - def global_options - @global_options ||= options_from(global_options_file) - end - - def options_from(path) - Parser.parse(args_from_options_file(path)) - end - - def args_from_options_file(path) - return [] unless path && File.exist?(path) - config_string = options_file_as_erb_string(path) - FlatMap.flat_map(config_string.split(/\n+/), &:shellsplit) - end - - def options_file_as_erb_string(path) - ERB.new(File.read(path), nil, '-').result(binding) - end - - def custom_options_file - command_line_options[:custom_options_file] - end - - def project_options_file - ".rspec" - end - - def local_options_file - ".rspec-local" - end - - def global_options_file - begin - File.join(File.expand_path("~"), ".rspec") - rescue ArgumentError - RSpec.warning "Unable to find ~/.rspec because the HOME environment variable is not set" - nil - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/drb.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/drb.rb deleted file mode 100644 index 3185433..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/drb.rb +++ /dev/null @@ -1,111 +0,0 @@ -require 'drb/drb' - -module RSpec - module Core - # @private - class DRbRunner - def initialize(options, configuration=RSpec.configuration) - @options = options - @configuration = configuration - end - - def drb_port - @options.options[:drb_port] || ENV['RSPEC_DRB'] || 8989 - end - - def run(err, out) - begin - DRb.start_service("druby://localhost:0") - rescue SocketError, Errno::EADDRNOTAVAIL - DRb.start_service("druby://:0") - end - spec_server = DRbObject.new_with_uri("druby://127.0.0.1:#{drb_port}") - spec_server.run(drb_argv, err, out) - end - - def drb_argv - @drb_argv ||= begin - @options.configure_filter_manager(@configuration.filter_manager) - DRbOptions.new(@options.options, @configuration.filter_manager).options - end - end - end - - # @private - class DRbOptions - def initialize(submitted_options, filter_manager) - @submitted_options = submitted_options - @filter_manager = filter_manager - end - - def options - argv = [] - argv << "--color" if @submitted_options[:color] - argv << "--profile" if @submitted_options[:profile_examples] - argv << "--backtrace" if @submitted_options[:full_backtrace] - argv << "--tty" if @submitted_options[:tty] - argv << "--fail-fast" if @submitted_options[:fail_fast] - argv << "--options" << @submitted_options[:custom_options_file] if @submitted_options[:custom_options_file] - argv << "--order" << @submitted_options[:order] if @submitted_options[:order] - - add_failure_exit_code(argv) - add_full_description(argv) - add_filter(argv, :inclusion, @filter_manager.inclusions) - add_filter(argv, :exclusion, @filter_manager.exclusions) - add_formatters(argv) - add_libs(argv) - add_requires(argv) - - argv + @submitted_options[:files_or_directories_to_run] - end - - def add_failure_exit_code(argv) - if @submitted_options[:failure_exit_code] - argv << "--failure-exit-code" << @submitted_options[:failure_exit_code].to_s - end - end - - def add_full_description(argv) - if @submitted_options[:full_description] - # The argument to --example is regexp-escaped before being stuffed - # into a regexp when received for the first time (see OptionParser). - # Hence, merely grabbing the source of this regexp will retain the - # backslashes, so we must remove them. - @submitted_options[:full_description].each do |description| - argv << "--example" << description.source.delete('\\') - end - end - end - - CONDITIONAL_FILTERS = [:if, :unless] - - def add_filter(argv, name, hash) - hash.each_pair do |k, v| - next if CONDITIONAL_FILTERS.include?(k) - tag = name == :inclusion ? k.to_s : "~#{k}" - tag << ":#{v}" if v.is_a?(String) - argv << "--tag" << tag - end unless hash.empty? - end - - def add_formatters(argv) - @submitted_options[:formatters].each do |pair| - argv << "--format" << pair[0] - argv << "--out" << pair[1] if pair[1] - end if @submitted_options[:formatters] - end - - def add_libs(argv) - @submitted_options[:libs].each do |path| - argv << "-I" << path - end if @submitted_options[:libs] - end - - def add_requires(argv) - @submitted_options[:requires].each do |path| - argv << "--require" << path - end if @submitted_options[:requires] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/dsl.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/dsl.rb deleted file mode 100644 index 92a3893..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/dsl.rb +++ /dev/null @@ -1,94 +0,0 @@ -module RSpec - module Core - # DSL defines methods to group examples, most notably `describe`, - # and exposes them as class methods of {RSpec}. They can also be - # exposed globally (on `main` and instances of `Module`) through - # the {Configuration} option `expose_dsl_globally`. - # - # By default the methods `describe`, `context` and `example_group` - # are exposed. These methods define a named context for one or - # more examples. The given block is evaluated in the context of - # a generated subclass of {RSpec::Core::ExampleGroup} - # - # ## Examples: - # - # RSpec.describe "something" do - # context "when something is a certain way" do - # it "does something" do - # # example code goes here - # end - # end - # end - # - # @see ExampleGroup - # @see ExampleGroup.example_group - module DSL - # @private - def self.example_group_aliases - @example_group_aliases ||= [] - end - - # @private - def self.exposed_globally? - @exposed_globally ||= false - end - - # @private - def self.expose_example_group_alias(name) - example_group_aliases << name - - (class << RSpec; self; end).__send__(:define_method, name) do |*args, &example_group_block| - RSpec.world.register RSpec::Core::ExampleGroup.__send__(name, *args, &example_group_block) - end - - expose_example_group_alias_globally(name) if exposed_globally? - end - - class << self - # @private - attr_accessor :top_level - end - - # Adds the describe method to Module and the top level binding - # @api private - def self.expose_globally! - return if exposed_globally? - - example_group_aliases.each do |method_name| - expose_example_group_alias_globally(method_name) - end - - @exposed_globally = true - end - - # Removes the describe method from Module and the top level binding - # @api private - def self.remove_globally! - return unless exposed_globally? - - example_group_aliases.each do |method_name| - change_global_dsl { undef_method method_name } - end - - @exposed_globally = false - end - - # @private - def self.expose_example_group_alias_globally(method_name) - change_global_dsl do - define_method(method_name) { |*a, &b| ::RSpec.__send__(method_name, *a, &b) } - end - end - - # @private - def self.change_global_dsl(&changes) - (class << top_level; self; end).class_exec(&changes) - Module.class_exec(&changes) - end - - end - end -end - -# capture main without an eval -::RSpec::Core::DSL.top_level = self diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/example.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/example.rb deleted file mode 100644 index 83600ec..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/example.rb +++ /dev/null @@ -1,474 +0,0 @@ -module RSpec - module Core - # Wrapper for an instance of a subclass of {ExampleGroup}. An instance of - # `RSpec::Core::Example` is returned by example definition methods - # such as {ExampleGroup.it it} and is yielded to the {ExampleGroup.it it}, - # {Hooks#before before}, {Hooks#after after}, {Hooks#around around}, - # {MemoizedHelpers::ClassMethods#let let} and - # {MemoizedHelpers::ClassMethods#subject subject} blocks. - # - # This allows us to provide rich metadata about each individual - # example without adding tons of methods directly to the ExampleGroup - # that users may inadvertantly redefine. - # - # Useful for configuring logging and/or taking some action based - # on the state of an example's metadata. - # - # @example - # - # RSpec.configure do |config| - # config.before do |example| - # log example.description - # end - # - # config.after do |example| - # log example.description - # end - # - # config.around do |example| - # log example.description - # example.run - # end - # end - # - # shared_examples "auditable" do - # it "does something" do - # log "#{example.full_description}: #{auditable.inspect}" - # auditable.should do_something - # end - # end - # - # @see ExampleGroup - # @note Example blocks are evaluated in the context of an instance - # of an `ExampleGroup`, not in the context of an instance of `Example`. - class Example - # @private - # - # Used to define methods that delegate to this example's metadata - def self.delegate_to_metadata(key) - define_method(key) { @metadata[key] } - end - - # @return [ExecutionResult] represents the result of running this example. - delegate_to_metadata :execution_result - # @return [String] the relative path to the file where this example was defined. - delegate_to_metadata :file_path - # @return [String] the full description (including the docstrings of - # all parent example groups). - delegate_to_metadata :full_description - # @return [String] the exact source location of this example in a form - # like `./path/to/spec.rb:17` - delegate_to_metadata :location - # @return [Boolean] flag that indicates that the example is not expected to pass. - # It will be run and will either have a pending result (if a failure occurs) - # or a failed result (if no failure occurs). - delegate_to_metadata :pending - # @return [Boolean] flag that will cause the example to not run. - # The {ExecutionResult} status will be `:pending`. - delegate_to_metadata :skip - - # Returns the string submitted to `example` or its aliases (e.g. - # `specify`, `it`, etc). If no string is submitted (e.g. `it { is_expected.to - # do_something }`) it returns the message generated by the matcher if - # there is one, otherwise returns a message including the location of the - # example. - def description - description = metadata[:description].to_s.empty? ? - "example at #{location}" : - metadata[:description] - RSpec.configuration.format_docstrings_block.call(description) - end - - # @attr_reader - # - # Returns the first exception raised in the context of running this - # example (nil if no exception is raised) - attr_reader :exception - - # @attr_reader - # - # Returns the metadata object associated with this example. - attr_reader :metadata - - # @attr_reader - # @private - # - # Returns the example_group_instance that provides the context for - # running this example. - attr_reader :example_group_instance - - # @attr - # @private - attr_accessor :clock - - # Creates a new instance of Example. - # @param example_group_class [Class] the subclass of ExampleGroup in which this Example is declared - # @param description [String] the String passed to the `it` method (or alias) - # @param user_metadata [Hash] additional args passed to `it` to be used as metadata - # @param example_block [Proc] the block of code that represents the example - # @api private - def initialize(example_group_class, description, user_metadata, example_block=nil) - @example_group_class = example_group_class - @example_block = example_block - - @metadata = Metadata::ExampleHash.create( - @example_group_class.metadata, user_metadata, description, example_block - ) - - @example_group_instance = @exception = nil - @clock = RSpec::Core::Time - end - - # Returns the example group class that provides the context for running - # this example. - def example_group - @example_group_class - end - - alias_method :pending?, :pending - alias_method :skipped?, :skip - - # @api private - # instance_execs the block passed to the constructor in the context of - # the instance of {ExampleGroup}. - # @param example_group_instance the instance of an ExampleGroup subclass - def run(example_group_instance, reporter) - @example_group_instance = example_group_instance - RSpec.current_example = self - - start(reporter) - - begin - if skipped? - Pending.mark_pending! self, skip - elsif !RSpec.configuration.dry_run? - with_around_example_hooks do - begin - run_before_example - @example_group_instance.instance_exec(self, &@example_block) - - if pending? - Pending.mark_fixed! self - - raise Pending::PendingExampleFixedError, - 'Expected example to fail since it is pending, but it passed.', - [location] - end - rescue Pending::SkipDeclaredInExample - # no-op, required metadata has already been set by the `skip` - # method. - rescue Exception => e - set_exception(e) - ensure - run_after_example - end - end - end - rescue Exception => e - set_exception(e) - ensure - @example_group_instance.instance_variables.each do |ivar| - @example_group_instance.instance_variable_set(ivar, nil) - end - @example_group_instance = nil - end - - finish(reporter) - ensure - RSpec.current_example = nil - end - - # Wraps both a `Proc` and an {Example} for use in {Hooks#around - # around} hooks. In around hooks we need to yield this special - # kind of object (rather than the raw {Example}) because when - # there are multiple `around` hooks we have to wrap them recursively. - # - # @example - # - # RSpec.configure do |c| - # c.around do |ex| # Procsy which wraps the example - # if ex.metadata[:key] == :some_value && some_global_condition - # raise "some message" - # end - # ex.run # run delegates to ex.call - # end - # end - # - # @note This class also exposes the instance methods of {Example}, - # proxying them through to the wrapped {Example} instance. - class Procsy - # The {Example} instance. - attr_reader :example - - Example.public_instance_methods(false).each do |name| - unless name.to_sym == :run - define_method(name) { |*a, &b| @example.__send__(name, *a, &b) } - end - end - - Proc.public_instance_methods(false).each do |name| - define_method(name) { |*a, &b| @proc.__send__(name, *a, &b) } - end - alias run call - - def initialize(example, &block) - @example = example - @proc = block - end - - # @private - def wrap(&block) - self.class.new(example, &block) - end - end - - # @private - def any_apply?(filters) - MetadataFilter.any_apply?(filters, metadata) - end - - # @private - def all_apply?(filters) - MetadataFilter.all_apply?(filters, metadata) || @example_group_class.all_apply?(filters) - end - - # @private - def around_example_hooks - @around_example_hooks ||= example_group.hooks.around_example_hooks_for(self) - end - - # @private - # - # Used internally to set an exception in an after hook, which - # captures the exception but doesn't raise it. - def set_exception(exception, context=nil) - if pending? && !(Pending::PendingExampleFixedError === exception) - execution_result.pending_exception = exception - else - if @exception - # An error has already been set; we don't want to override it, - # but we also don't want silence the error, so let's print it. - msg = <<-EOS - - An error occurred #{context} - #{exception.class}: #{exception.message} - occurred at #{exception.backtrace.first} - - EOS - RSpec.configuration.reporter.message(msg) - end - - @exception ||= exception - end - end - - # @private - # - # Used internally to set an exception and fail without actually executing - # the example when an exception is raised in before(:context). - def fail_with_exception(reporter, exception) - start(reporter) - set_exception(exception) - finish(reporter) - end - - # @private - # - # Used internally to skip without actually executing the example when - # skip is used in before(:context) - def skip_with_exception(reporter, exception) - start(reporter) - Pending.mark_skipped! self, exception.argument - finish(reporter) - end - - # @private - def instance_exec_with_rescue(context, &block) - @example_group_instance.instance_exec(self, &block) - rescue Exception => e - set_exception(e, context) - end - - # @private - def instance_exec(*args, &block) - @example_group_instance.instance_exec(*args, &block) - end - - private - - def with_around_example_hooks(&block) - if around_example_hooks.empty? - yield - else - @example_group_class.hooks.run(:around, :example, self, Procsy.new(self, &block)) - end - rescue Exception => e - set_exception(e, "in an `around(:example)` hook") - end - - def start(reporter) - reporter.example_started(self) - execution_result.started_at = clock.now - end - - def finish(reporter) - pending_message = execution_result.pending_message - - if @exception - record_finished :failed - execution_result.exception = @exception - reporter.example_failed self - false - elsif pending_message - record_finished :pending - execution_result.pending_message = pending_message - reporter.example_pending self - true - else - record_finished :passed - reporter.example_passed self - true - end - end - - def record_finished(status) - execution_result.record_finished(status, clock.now) - end - - def run_before_example - @example_group_instance.setup_mocks_for_rspec - @example_group_class.hooks.run(:before, :example, self) - end - - def run_after_example - @example_group_class.hooks.run(:after, :example, self) - verify_mocks - assign_generated_description if RSpec.configuration.expecting_with_rspec? - rescue Exception => e - set_exception(e, "in an `after(:example)` hook") - ensure - @example_group_instance.teardown_mocks_for_rspec - end - - def verify_mocks - @example_group_instance.verify_mocks_for_rspec if mocks_need_verification? - rescue Exception => e - if pending? - execution_result.pending_fixed = false - @exception = nil - else - set_exception(e) - end - end - - def mocks_need_verification? - exception.nil? || execution_result.pending_fixed? - end - - def assign_generated_description - if metadata[:description].empty? && (description = RSpec::Matchers.generated_description) - metadata[:description] = description - metadata[:full_description] << description - end - rescue Exception => e - set_exception(e, "while assigning the example description") - ensure - RSpec::Matchers.clear_generated_description - end - - def skip_message - if String === skip - skip - else - Pending::NO_REASON_GIVEN - end - end - - # Represents the result of executing an example. - # Behaves like a hash for backwards compatibility. - class ExecutionResult - include HashImitatable - - # @return [Symbol] `:passed`, `:failed` or `:pending`. - attr_accessor :status - - # @return [Exception, nil] The failure, if there was one. - attr_accessor :exception - - # @return [Time] When the example started. - attr_accessor :started_at - - # @return [Time] When the example finished. - attr_accessor :finished_at - - # @return [Float] How long the example took in seconds. - attr_accessor :run_time - - # @return [String, nil] The reason the example was pending, - # or nil if the example was not pending. - attr_accessor :pending_message - - # @return [Exception, nil] The exception triggered while - # executing the pending example. If no exception was triggered - # it would no longer get a status of `:pending` unless it was - # tagged with `:skip`. - attr_accessor :pending_exception - - # @return [Boolean] For examples tagged with `:pending`, - # this indicates whether or not it now passes. - attr_accessor :pending_fixed - - alias pending_fixed? pending_fixed - - # @api private - # Records the finished status of the example. - def record_finished(status, finished_at) - self.status = status - self.finished_at = finished_at - self.run_time = (finished_at - started_at).to_f - end - - private - - # For backwards compatibility we present `status` as a string - # when presenting the legacy hash interface. - def hash_for_delegation - super.tap do |hash| - hash[:status] &&= status.to_s - end - end - - def set_value(name, value) - value &&= value.to_sym if name == :status - super(name, value) - end - - def get_value(name) - if name == :status - status.to_s if status - else - super - end - end - - def issue_deprecation(method_name, *args) - RSpec.deprecate("Treating `metadata[:execution_result]` as a hash", - :replacement => "the attributes methods to access the data") - end - end - end - - # @private - # Provides an execution context for before/after :suite hooks. - class SuiteHookContext < Example - def initialize - super(AnonymousExampleGroup, "", {}) - end - - # To ensure we don't silence errors... - def set_exception(exception, context=nil) - raise exception - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/example_group.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/example_group.rb deleted file mode 100644 index 07c0d03..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/example_group.rb +++ /dev/null @@ -1,697 +0,0 @@ -module RSpec - module Core - # ExampleGroup and {Example} are the main structural elements of - # rspec-core. Consider this example: - # - # describe Thing do - # it "does something" do - # end - # end - # - # The object returned by `describe Thing` is a subclass of ExampleGroup. - # The object returned by `it "does something"` is an instance of Example, - # which serves as a wrapper for an instance of the ExampleGroup in which it - # is declared. - # - # Example group bodies (e.g. `describe` or `context` blocks) are evaluated - # in the context of a new subclass of ExampleGroup. Individual examples are - # evalutaed in the context of an instance of the specific ExampleGroup subclass - # to which they belong. - # - # Besides the class methods defined here, there are other interesting macros - # defined in {Hooks}, {MemoizedHelpers::ClassMethods} and {SharedExampleGroup}. - # There are additional instance methods available to your examples defined in - # {MemoizedHelpers} and {Pending}. - class ExampleGroup - extend Hooks - - include MemoizedHelpers - extend MemoizedHelpers::ClassMethods - include Pending - extend SharedExampleGroup - - unless respond_to?(:define_singleton_method) - # @private - def self.define_singleton_method(*a, &b) - (class << self; self; end).__send__(:define_method, *a, &b) - end - end - - # @!group Metadata - - # The [Metadata](Metadata) object associated with this group. - # @see Metadata - def self.metadata - @metadata if defined?(@metadata) - end - - # @private - # @return [Metadata] belonging to the parent of a nested {ExampleGroup} - def self.superclass_metadata - @superclass_metadata ||= self.superclass.respond_to?(:metadata) ? self.superclass.metadata : nil - end - - # @private - def self.delegate_to_metadata(*names) - names.each do |name| - define_singleton_method(name) { metadata.fetch(name) } - end - end - - delegate_to_metadata :described_class, :file_path, :location - - # @return [String] the current example group description - def self.description - description = metadata[:description] - RSpec.configuration.format_docstrings_block.call(description) - end - - # Returns the class or module passed to the `describe` method (or alias). - # Returns nil if the subject is not a class or module. - # @example - # describe Thing do - # it "does something" do - # described_class == Thing - # end - # end - # - # - def described_class - self.class.described_class - end - - # @!endgroup - - # @!group Defining Examples - - # @private - # @macro [attach] define_example_method - # @!scope class - # @param name [String] - # @param extra_options [Hash] - # @param implementation [Block] - # @yield [Example] the example object - # @example - # $1 do - # end - # - # $1 "does something" do - # end - # - # $1 "does something", :with => 'additional metadata' do - # end - # - # $1 "does something" do |ex| - # # ex is the Example object that contains metadata about the example - # end - def self.define_example_method(name, extra_options={}) - define_singleton_method(name) do |*all_args, &block| - desc, *args = *all_args - options = Metadata.build_hash_from(args) - options.update(:skip => RSpec::Core::Pending::NOT_YET_IMPLEMENTED) unless block - options.update(extra_options) - - # Metadata inheritance normally happens in `Example#initialize`, - # but for `:pending` specifically we need it earlier. - pending_metadata = options[:pending] || metadata[:pending] - - if pending_metadata - options, block = ExampleGroup.pending_metadata_and_block_for( - options.merge(:pending => pending_metadata), - block - ) - end - - examples << RSpec::Core::Example.new(self, desc, options, block) - examples.last - end - end - - # Defines an example within a group. - define_example_method :example - # Defines an example within a group. - # This is the primary API to define a code example. - define_example_method :it - # Defines an example within a group. - # Useful for when your docstring does not read well off of `it`. - # @example - # RSpec.describe MyClass do - # specify "#do_something is deprecated" do - # # ... - # end - # end - define_example_method :specify - - # Shortcut to define an example with `:focus => true` - # @see example - define_example_method :focus, :focus => true - # Shortcut to define an example with `:focus => true` - # @see example - define_example_method :fexample, :focus => true - # Shortcut to define an example with `:focus => true` - # @see example - define_example_method :fit, :focus => true - # Shortcut to define an example with `:focus => true` - # @see example - define_example_method :fspecify, :focus => true - # Shortcut to define an example with `:skip => 'Temporarily skipped with xexample'` - # @see example - define_example_method :xexample, :skip => 'Temporarily skipped with xexample' - # Shortcut to define an example with `:skip => 'Temporarily skipped with xit'` - # @see example - define_example_method :xit, :skip => 'Temporarily skipped with xit' - # Shortcut to define an example with `:skip => 'Temporarily skipped with xspecify'` - # @see example - define_example_method :xspecify, :skip => 'Temporarily skipped with xspecify' - # Shortcut to define an example with `:skip => true` - # @see example - define_example_method :skip, :skip => true - # Shortcut to define an example with `:pending => true` - # @see example - define_example_method :pending, :pending => true - - # @!endgroup - - # @!group Defining Example Groups - - # @private - # @macro [attach] alias_example_group_to - # @!scope class - # @param name [String] The example group doc string - # @param metadata [Hash] Additional metadata to attach to the example group - # @yield The example group definition - # - # Generates a subclass of this example group which inherits - # everything except the examples themselves. - # - # @example - # - # RSpec.describe "something" do # << This describe method is defined in - # # << RSpec::Core::DSL, included in the - # # << global namespace (optional) - # before do - # do_something_before - # end - # - # let(:thing) { Thing.new } - # - # $1 "attribute (of something)" do - # # examples in the group get the before hook - # # declared above, and can access `thing` - # end - # end - # - # @see DSL#describe - def self.define_example_group_method(name, metadata={}) - define_singleton_method(name) do |*args, &example_group_block| - thread_data = RSpec.thread_local_metadata - top_level = self == ExampleGroup - - if top_level - if thread_data[:in_example_group] - raise "Creating an isolated context from within a context is " + - "not allowed. Change `RSpec.#{name}` to `#{name}` or " + - "move this to a top-level scope." - end - - thread_data[:in_example_group] = true - end - - begin - - description = args.shift - combined_metadata = metadata.dup - combined_metadata.merge!(args.pop) if args.last.is_a? Hash - args << combined_metadata - - subclass(self, description, args, &example_group_block).tap do |child| - children << child - end - - ensure - thread_data.delete(:in_example_group) if top_level - end - end - - RSpec::Core::DSL.expose_example_group_alias(name) - end - - define_example_group_method :example_group - - # An alias of `example_group`. Generally used when grouping - # examples by a thing you are describing (e.g. an object, class or method). - # @see example_group - define_example_group_method :describe - - # An alias of `example_group`. Generally used when grouping examples - # contextually (e.g. "with xyz", "when xyz" or "if xyz"). - # @see example_group - define_example_group_method :context - - # Shortcut to temporarily make an example group skipped. - # @see example_group - define_example_group_method :xdescribe, :skip => "Temporarily skipped with xdescribe" - - # Shortcut to temporarily make an example group skipped. - # @see example_group - define_example_group_method :xcontext, :skip => "Temporarily skipped with xcontext" - - # Shortcut to define an example group with `:focus => true`. - # @see example_group - define_example_group_method :fdescribe, :focus => true - - # Shortcut to define an example group with `:focus => true`. - # @see example_group - define_example_group_method :fcontext, :focus => true - - # @!endgroup - - # @!group Including Shared Example Groups - - # @private - # @macro [attach] define_nested_shared_group_method - # @!scope class - # - # @see SharedExampleGroup - def self.define_nested_shared_group_method(new_name, report_label="it should behave like") - define_singleton_method(new_name) do |name, *args, &customization_block| - # Pass :caller so the :location metadata is set properly... - # otherwise, it'll be set to the next line because that's - # the block's source_location. - group = example_group("#{report_label} #{name}", :caller => caller) do - find_and_eval_shared("examples", name, *args, &customization_block) - end - group.metadata[:shared_group_name] = name - group - end - end - - # Generates a nested example group and includes the shared content - # mapped to `name` in the nested group. - define_nested_shared_group_method :it_behaves_like, "behaves like" - # Generates a nested example group and includes the shared content - # mapped to `name` in the nested group. - define_nested_shared_group_method :it_should_behave_like - - # Includes shared content mapped to `name` directly in the group in which - # it is declared, as opposed to `it_behaves_like`, which creates a nested - # group. If given a block, that block is also eval'd in the current context. - # - # @see SharedExampleGroup - def self.include_context(name, *args, &block) - find_and_eval_shared("context", name, *args, &block) - end - - # Includes shared content mapped to `name` directly in the group in which - # it is declared, as opposed to `it_behaves_like`, which creates a nested - # group. If given a block, that block is also eval'd in the current context. - # - # @see SharedExampleGroup - def self.include_examples(name, *args, &block) - find_and_eval_shared("examples", name, *args, &block) - end - - # @private - def self.find_and_eval_shared(label, name, *args, &customization_block) - unless shared_block = RSpec.world.shared_example_group_registry.find(parent_groups, name) - raise ArgumentError, "Could not find shared #{label} #{name.inspect}" - end - - module_exec(*args, &shared_block) - module_exec(&customization_block) if customization_block - end - - # @!endgroup - - # @private - def self.subclass(parent, description, args, &example_group_block) - subclass = Class.new(parent) - subclass.set_it_up(description, *args, &example_group_block) - ExampleGroups.assign_const(subclass) - subclass.module_exec(&example_group_block) if example_group_block - - # The LetDefinitions module must be included _after_ other modules - # to ensure that it takes precedence when there are name collisions. - # Thus, we delay including it until after the example group block - # has been eval'd. - MemoizedHelpers.define_helpers_on(subclass) - - subclass - end - - # @private - def self.set_it_up(*args, &example_group_block) - # Ruby 1.9 has a bug that can lead to infinite recursion and a - # SystemStackError if you include a module in a superclass after - # including it in a subclass: https://gist.github.com/845896 - # To prevent this, we must include any modules in RSpec::Core::ExampleGroup - # before users create example groups and have a chance to include - # the same module in a subclass of RSpec::Core::ExampleGroup. - # So we need to configure example groups here. - ensure_example_groups_are_configured - - description = args.shift - user_metadata = Metadata.build_hash_from(args) - args.unshift(description) - - @metadata = Metadata::ExampleGroupHash.create( - superclass_metadata, user_metadata, *args, &example_group_block - ) - - hooks.register_globals(self, RSpec.configuration.hooks) - RSpec.world.configure_group(self) - end - - # @private - def self.examples - @examples ||= [] - end - - # @private - def self.filtered_examples - RSpec.world.filtered_examples[self] - end - - # @private - def self.descendant_filtered_examples - @descendant_filtered_examples ||= filtered_examples + children.inject([]){|l,c| l + c.descendant_filtered_examples} - end - - # @private - def self.children - @children ||= [] - end - - # @private - def self.descendants - @_descendants ||= [self] + children.inject([]) {|list, c| list + c.descendants} - end - - ## @private - def self.parent_groups - @parent_groups ||= ancestors.select {|a| a < RSpec::Core::ExampleGroup} - end - - # @private - def self.top_level? - @top_level ||= superclass == ExampleGroup - end - - # @private - def self.ensure_example_groups_are_configured - unless defined?(@@example_groups_configured) - RSpec.configuration.configure_mock_framework - RSpec.configuration.configure_expectation_framework - @@example_groups_configured = true - end - end - - # @private - def self.before_context_ivars - @before_context_ivars ||= {} - end - - # @private - def self.store_before_context_ivars(example_group_instance) - return if example_group_instance.instance_variables.empty? - - example_group_instance.instance_variables.each { |ivar| - before_context_ivars[ivar] = example_group_instance.instance_variable_get(ivar) - } - end - - # @private - def self.run_before_context_hooks(example_group_instance) - return if descendant_filtered_examples.empty? - begin - set_ivars(example_group_instance, superclass.before_context_ivars) - - ContextHookMemoizedHash::Before.isolate_for_context_hook(example_group_instance) do - hooks.run(:before, :context, example_group_instance) - end - ensure - store_before_context_ivars(example_group_instance) - end - end - - # @private - def self.run_after_context_hooks(example_group_instance) - return if descendant_filtered_examples.empty? - set_ivars(example_group_instance, before_context_ivars) - - ContextHookMemoizedHash::After.isolate_for_context_hook(example_group_instance) do - hooks.run(:after, :context, example_group_instance) - end - end - - # Runs all the examples in this group - def self.run(reporter) - if RSpec.world.wants_to_quit - RSpec.world.clear_remaining_example_groups if top_level? - return - end - reporter.example_group_started(self) - - begin - run_before_context_hooks(new) - result_for_this_group = run_examples(reporter) - results_for_descendants = ordering_strategy.order(children).map { |child| child.run(reporter) }.all? - result_for_this_group && results_for_descendants - rescue Pending::SkipDeclaredInExample => ex - for_filtered_examples(reporter) {|example| example.skip_with_exception(reporter, ex) } - rescue Exception => ex - RSpec.world.wants_to_quit = true if fail_fast? - for_filtered_examples(reporter) {|example| example.fail_with_exception(reporter, ex) } - ensure - run_after_context_hooks(new) - before_context_ivars.clear - reporter.example_group_finished(self) - end - end - - # @private - def self.ordering_strategy - order = metadata.fetch(:order, :global) - registry = RSpec.configuration.ordering_registry - - registry.fetch(order) do - warn <<-WARNING.gsub(/^ +\|/, '') - |WARNING: Ignoring unknown ordering specified using `:order => #{order.inspect}` metadata. - | Falling back to configured global ordering. - | Unrecognized ordering specified at: #{location} - WARNING - - registry.fetch(:global) - end - end - - # @private - def self.run_examples(reporter) - ordering_strategy.order(filtered_examples).map do |example| - next if RSpec.world.wants_to_quit - instance = new - set_ivars(instance, before_context_ivars) - succeeded = example.run(instance, reporter) - RSpec.world.wants_to_quit = true if fail_fast? && !succeeded - succeeded - end.all? - end - - # @private - def self.for_filtered_examples(reporter, &block) - filtered_examples.each(&block) - - children.each do |child| - reporter.example_group_started(child) - child.for_filtered_examples(reporter, &block) - reporter.example_group_finished(child) - end - false - end - - # @private - def self.fail_fast? - RSpec.configuration.fail_fast? - end - - # @private - def self.any_apply?(filters) - MetadataFilter.any_apply?(filters, metadata) - end - - # @private - def self.all_apply?(filters) - MetadataFilter.all_apply?(filters, metadata) - end - - # @private - def self.declaration_line_numbers - @declaration_line_numbers ||= [metadata[:line_number]] + - examples.collect {|e| e.metadata[:line_number]} + - children.inject([]) {|l,c| l + c.declaration_line_numbers} - end - - # @private - def self.top_level_description - parent_groups.last.description - end - - # @private - def self.set_ivars(instance, ivars) - ivars.each {|name, value| instance.instance_variable_set(name, value)} - end - - # @private - def self.pending_metadata_and_block_for(options, block) - if String === options[:pending] - reason = options[:pending] - else - options[:pending] = true - reason = RSpec::Core::Pending::NO_REASON_GIVEN - end - - # Assign :caller so that the callback's source_location isn't used - # as the example location. - options[:caller] ||= Metadata.backtrace_from(block) - - # This will fail if no block is provided, which is effectively the - # same as failing the example so it will be marked correctly as - # pending. - callback = Proc.new { pending(reason); instance_exec(&block) } - - return options, callback - end - end - - # @private - # Unnamed example group used by `SuiteHookContext`. - class AnonymousExampleGroup < ExampleGroup - def self.metadata - {} - end - end - end - - # Provides recursive constant lookup methods useful for - # constant stubbing. - # @private - module RecursiveConstMethods - # We only want to consider constants that are defined directly on a - # particular module, and not include top-level/inherited constants. - # Unfortunately, the constant API changed between 1.8 and 1.9, so - # we need to conditionally define methods to ignore the top-level/inherited - # constants. - # - # Given: - # class A; B = 1; end - # class C < A; end - # - # On 1.8: - # - C.const_get("Hash") # => ::Hash - # - C.const_defined?("Hash") # => false - # - C.constants # => ["B"] - # - None of these methods accept the extra `inherit` argument - # On 1.9: - # - C.const_get("Hash") # => ::Hash - # - C.const_defined?("Hash") # => true - # - C.const_get("Hash", false) # => raises NameError - # - C.const_defined?("Hash", false) # => false - # - C.constants # => [:B] - # - C.constants(false) #=> [] - if Module.method(:const_defined?).arity == 1 - def const_defined_on?(mod, const_name) - mod.const_defined?(const_name) - end - - def get_const_defined_on(mod, const_name) - if const_defined_on?(mod, const_name) - return mod.const_get(const_name) - end - - raise NameError, "uninitialized constant #{mod.name}::#{const_name}" - end - - def constants_defined_on(mod) - mod.constants.select { |c| const_defined_on?(mod, c) } - end - else - def const_defined_on?(mod, const_name) - mod.const_defined?(const_name, false) - end - - def get_const_defined_on(mod, const_name) - mod.const_get(const_name, false) - end - - def constants_defined_on(mod) - mod.constants(false) - end - end - - def recursive_const_get(const_name) - normalize_const_name(const_name).split('::').inject(Object) do |mod, name| - get_const_defined_on(mod, name) - end - end - - def recursive_const_defined?(const_name) - normalize_const_name(const_name).split('::').inject([Object, '']) do |(mod, full_name), name| - yield(full_name, name) if block_given? && !(Module === mod) - return false unless const_defined_on?(mod, name) - [get_const_defined_on(mod, name), [mod, name].join('::')] - end - end - - def normalize_const_name(const_name) - const_name.sub(/\A::/, '') - end - end - - # @private - # - # Namespace for the example group subclasses generated by top-level `describe`. - module ExampleGroups - extend RecursiveConstMethods - - def self.assign_const(group) - base_name = base_name_for(group) - const_scope = constant_scope_for(group) - name = disambiguate(base_name, const_scope) - - const_scope.const_set(name, group) - end - - def self.constant_scope_for(group) - const_scope = group.superclass - const_scope = self if const_scope == Core::ExampleGroup - const_scope - end - - def self.base_name_for(group) - return "Anonymous" if group.description.empty? - - # convert to CamelCase - name = ' ' + group.description - name.gsub!(/[^0-9a-zA-Z]+([0-9a-zA-Z])/) { $1.upcase } - - name.lstrip! # Remove leading whitespace - name.gsub!(/\W/, '') # JRuby, RBX and others don't like non-ascii in const names - - # Ruby requires first const letter to be A-Z. Use `Nested` - # as necessary to enforce that. - name.gsub!(/\A([^A-Z]|\z)/, 'Nested\1') - - name - end - - def self.disambiguate(name, const_scope) - return name unless const_defined_on?(const_scope, name) - - # Add a trailing number if needed to disambiguate from an existing constant. - name << "_2" - name.next! while const_defined_on?(const_scope, name) - name - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/filter_manager.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/filter_manager.rb deleted file mode 100644 index 927accf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/filter_manager.rb +++ /dev/null @@ -1,260 +0,0 @@ -module RSpec - module Core - # @private - # Manages the filtering of examples and groups by matching tags declared on - # the command line or options files, or filters declared via - # `RSpec.configure`, with hash key/values submitted within example group - # and/or example declarations. For example, given this declaration: - # - # describe Thing, :awesome => true do - # it "does something" do - # # ... - # end - # end - # - # That group (or any other with `:awesome => true`) would be filtered in - # with any of the following commands: - # - # rspec --tag awesome:true - # rspec --tag awesome - # rspec -t awesome:true - # rspec -t awesome - # - # Prefixing the tag names with `~` negates the tags, thus excluding this group with - # any of: - # - # rspec --tag ~awesome:true - # rspec --tag ~awesome - # rspec -t ~awesome:true - # rspec -t ~awesome - # - # ## Options files and command line overrides - # - # Tag declarations can be stored in `.rspec`, `~/.rspec`, or a custom - # options file. This is useful for storing defaults. For example, let's - # say you've got some slow specs that you want to suppress most of the - # time. You can tag them like this: - # - # describe Something, :slow => true do - # - # And then store this in `.rspec`: - # - # --tag ~slow:true - # - # Now when you run `rspec`, that group will be excluded. - # - # ## Overriding - # - # Of course, you probably want to run them sometimes, so you can override - # this tag on the command line like this: - # - # rspec --tag slow:true - # - # ## RSpec.configure - # - # You can also store default tags with `RSpec.configure`. We use `tag` on - # the command line (and in options files like `.rspec`), but for historical - # reasons we use the term `filter` in `RSpec.configure: - # - # RSpec.configure do |c| - # c.filter_run_including :foo => :bar - # c.filter_run_excluding :foo => :bar - # end - # - # These declarations can also be overridden from the command line. - # - # @see RSpec.configure - # @see Configuration#filter_run_including - # @see Configuration#filter_run_excluding - class FilterManager - attr_reader :exclusions, :inclusions - - def initialize - @exclusions, @inclusions = FilterRules.build - end - - # @api private - # - # @param file_path [String] - # @param line_numbers [Array] - def add_location(file_path, line_numbers) - # locations is a hash of expanded paths to arrays of line - # numbers to match against. e.g. - # { "path/to/file.rb" => [37, 42] } - locations = inclusions.delete(:locations) || Hash.new { |h,k| h[k] = [] } - locations[File.expand_path(file_path)].push(*line_numbers) - inclusions.add_location(locations) - end - - def empty? - inclusions.empty? && exclusions.empty? - end - - def prune(examples) - if inclusions.standalone? - base_exclusions = ExclusionRules.new - examples.select {|e| !base_exclusions.include_example?(e) && include?(e) } - else - examples.select {|e| !exclude?(e) && include?(e)} - end - end - - def exclude(*args) - exclusions.add(args.last) - end - - def exclude_only(*args) - exclusions.use_only(args.last) - end - - def exclude_with_low_priority(*args) - exclusions.add_with_low_priority(args.last) - end - - def exclude?(example) - exclusions.include_example?(example) - end - - def include(*args) - inclusions.add(args.last) - end - - def include_only(*args) - inclusions.use_only(args.last) - end - - def include_with_low_priority(*args) - inclusions.add_with_low_priority(args.last) - end - - def include?(example) - inclusions.include_example?(example) - end - end - - # @private - class FilterRules - PROC_HEX_NUMBER = /0x[0-9a-f]+@/ - PROJECT_DIR = File.expand_path('.') - - attr_accessor :opposite - attr_reader :rules - - def self.build - exclusions = ExclusionRules.new - inclusions = InclusionRules.new - exclusions.opposite = inclusions - inclusions.opposite = exclusions - [exclusions, inclusions] - end - - def initialize(*args, &block) - @rules = Hash.new(*args, &block) - end - - def add(updated) - @rules.merge!(updated).each_key { |k| opposite.delete(k) } - end - - def add_with_low_priority(_updated) - updated = _updated.merge(@rules) - opposite.each_pair { |k,v| updated.delete(k) if updated[k] == v } - @rules.replace(updated) - end - - def use_only(updated) - updated.each_key { |k| opposite.delete(k) } - @rules.replace(updated) - end - - def clear - @rules.clear - end - - def delete(key) - @rules.delete(key) - end - - def fetch(*args, &block) - @rules.fetch(*args, &block) - end - - def [](key) - @rules[key] - end - - def empty? - rules.empty? - end - - def each_pair(&block) - @rules.each_pair(&block) - end - - def description - rules.inspect.gsub(PROC_HEX_NUMBER, '').gsub(PROJECT_DIR, '.').gsub(' (lambda)','') - end - end - - # @private - class InclusionRules < FilterRules - STANDALONE_FILTERS = [:locations, :full_description] - - def add_location(locations) - replace_filters({ :locations => locations }) - end - - def add(*args) - set_standalone_filter(*args) || super - end - - def add_with_low_priority(*args) - set_standalone_filter(*args) || super - end - - def use(*args) - set_standalone_filter(*args) || super - end - - def include_example?(example) - @rules.empty? ? true : example.any_apply?(@rules) - end - - def standalone? - is_standalone_filter?(@rules) - end - - private - - def set_standalone_filter(updated) - return true if standalone? - - if is_standalone_filter?(updated) - replace_filters(updated) - true - end - end - - def replace_filters(new_rules) - @rules.replace(new_rules) - opposite.clear - end - - def is_standalone_filter?(rules) - STANDALONE_FILTERS.any? { |key| rules.has_key?(key) } - end - end - - # @private - class ExclusionRules < FilterRules - CONDITIONAL_FILTERS = { - :if => lambda { |value| !value }, - :unless => lambda { |value| value } - }.freeze - - def include_example?(example) - example.any_apply?(@rules) || example.any_apply?(CONDITIONAL_FILTERS) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/flat_map.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/flat_map.rb deleted file mode 100644 index cc4e5a4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/flat_map.rb +++ /dev/null @@ -1,18 +0,0 @@ -module RSpec - module Core - # @private - module FlatMap - if [].respond_to?(:flat_map) - def flat_map(array) - array.flat_map { |item| yield item } - end - else # for 1.8.7 - def flat_map(array) - array.map { |item| yield item }.flatten - end - end - - module_function :flat_map - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters.rb deleted file mode 100644 index eaba1d7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters.rb +++ /dev/null @@ -1,239 +0,0 @@ -# ## Built-in Formatters -# -# * progress (default) - prints dots for passing examples, `F` for failures, `*` for pending -# * documentation - prints the docstrings passed to `describe` and `it` methods (and their aliases) -# * html -# * json - useful for archiving data for subsequent analysis -# -# The progress formatter is the default, but you can choose any one or more of -# the other formatters by passing with the `--format` (or `-f` for short) -# command-line option, e.g. -# -# rspec --format documentation -# -# You can also send the output of multiple formatters to different streams, e.g. -# -# rspec --format documentation --format html --out results.html -# -# This example sends the output of the documentation formatter to `$stdout`, and -# the output of the html formatter to results.html. -# -# ## Custom Formatters -# -# You can tell RSpec to use a custom formatter by passing its path and name to -# the `rspec` commmand. For example, if you define MyCustomFormatter in -# path/to/my_custom_formatter.rb, you would type this command: -# -# rspec --require path/to/my_custom_formatter.rb --format MyCustomFormatter -# -# The reporter calls every formatter with this protocol: -# -# * To start -# * `start(StartNotification)` -# * Once per example group -# * `example_group_started(GroupNotification)` -# * Once per example -# * `example_started(ExampleNotification)` -# * One of these per example, depending on outcome -# * `example_passed(ExampleNotification)` -# * `example_failed(FailedExampleNotification)` -# * `example_pending(ExampleNotification)` -# * Optionally at any time -# * `message(MessageNotification)` -# * At the end of the suite -# * `stop(ExamplesNotification)` -# * `start_dump(NullNotification)` -# * `dump_pending(ExamplesNotification)` -# * `dump_failures(ExamplesNotification)` -# * `dump_summary(SummaryNotification)` -# * `seed(SeedNotification)` -# * `close(NullNotification)` -# -# Only the notifications to which you subscribe your formatter will be called -# on your formatter. To subscribe your formatter use: -# `RSpec::Core::Formatters#register` e.g. -# -# `RSpec::Core::Formatters.register FormatterClassName, :example_passed, :example_failed` -# -# We recommend you implement the methods yourself; for simplicity we provide the -# default formatter output via our notification objects but if you prefer you -# can subclass `RSpec::Core::Formatters::BaseTextFormatter` and override the -# methods you wish to enhance. -# -# @see RSpec::Core::Formatters::BaseTextFormatter -# @see RSpec::Core::Reporter -module RSpec::Core::Formatters - autoload :DocumentationFormatter, 'rspec/core/formatters/documentation_formatter' - autoload :HtmlFormatter, 'rspec/core/formatters/html_formatter' - autoload :ProgressFormatter, 'rspec/core/formatters/progress_formatter' - autoload :ProfileFormatter, 'rspec/core/formatters/profile_formatter' - autoload :JsonFormatter, 'rspec/core/formatters/json_formatter' - - # Register the formatter class - # @param formatter_class [Class] formatter class to register - # @param notifications [Symbol, ...] one or more notifications to be registered to the specified formatter - # - # @see RSpec::Core::Formatters::BaseFormatter - def self.register(formatter_class, *notifications) - Loader.formatters[formatter_class] = notifications - end - - # @api private - # - # `RSpec::Core::Formatters::Loader` is an internal class for - # managing formatters used by a particular configuration. It is - # not expected to be used directly, but only through the configuration - # interface. - class Loader - # @api private - # - # Internal formatters are stored here when loaded - def self.formatters - @formatters ||= {} - end - - # @api private - def initialize(reporter) - @formatters = [] - @reporter = reporter - self.default_formatter = 'progress' - end - - # @return [Array] the loaded formatters - attr_reader :formatters - - # @return [Reporter] the reporter - attr_reader :reporter - - # @return [String] the default formatter to setup, defaults to `progress` - attr_accessor :default_formatter - - # @private - def setup_default(output_stream, deprecation_stream) - if @formatters.empty? - add default_formatter, output_stream - end - unless @formatters.any? { |formatter| DeprecationFormatter === formatter } - add DeprecationFormatter, deprecation_stream, output_stream - end - if RSpec.configuration.profile_examples? && !existing_formatter_implements?(:dump_profile) - add RSpec::Core::Formatters::ProfileFormatter, output_stream - end - end - - # @private - def add(formatter_to_use, *paths) - formatter_class = find_formatter(formatter_to_use) - - args = paths.map { |p| p.respond_to?(:puts) ? p : file_at(p) } - - if !Loader.formatters[formatter_class].nil? - formatter = formatter_class.new(*args) - @reporter.register_listener formatter, *notifications_for(formatter_class) - elsif defined?(RSpec::LegacyFormatters) - formatter = RSpec::LegacyFormatters.load_formatter formatter_class, *args - @reporter.register_listener formatter, *formatter.notifications - else - line = ::RSpec::CallerFilter.first_non_rspec_line - if line - call_site = "Formatter added at: #{line}" - else - call_site = "The formatter was added via command line flag or your "+ - "`.rspec` file." - end - - RSpec.warn_deprecation <<-WARNING.gsub(/\s*\|/,' ') - |The #{formatter_class} formatter uses the deprecated formatter - |interface not supported directly by RSpec 3. - | - |To continue to use this formatter you must install the - |`rspec-legacy_formatters` gem, which provides support - |for legacy formatters or upgrade the formatter to a - |compatible version. - | - |#{call_site} - WARNING - return - end - @formatters << formatter unless duplicate_formatter_exists?(formatter) - formatter - end - - private - - def find_formatter(formatter_to_use) - built_in_formatter(formatter_to_use) || - custom_formatter(formatter_to_use) || - (raise ArgumentError, "Formatter '#{formatter_to_use}' unknown - maybe you meant 'documentation' or 'progress'?.") - end - - def duplicate_formatter_exists?(new_formatter) - @formatters.any? do |formatter| - formatter.class === new_formatter && formatter.output == new_formatter.output - end - end - - def existing_formatter_implements?(notification) - @reporter.registered_listeners(notification).any? - end - - def built_in_formatter(key) - case key.to_s - when 'd', 'doc', 'documentation' - DocumentationFormatter - when 'h', 'html' - HtmlFormatter - when 'p', 'progress' - ProgressFormatter - when 'j', 'json' - JsonFormatter - end - end - - def notifications_for(formatter_class) - formatter_class.ancestors.inject(Set.new) do |notifications, klass| - notifications + Loader.formatters.fetch(klass) { Set.new } - end - end - - def custom_formatter(formatter_ref) - if Class === formatter_ref - formatter_ref - elsif string_const?(formatter_ref) - begin - formatter_ref.gsub(/^::/,'').split('::').inject(Object) { |const,string| const.const_get string } - rescue NameError - require( path_for(formatter_ref) ) ? retry : raise - end - end - end - - def string_const?(str) - str.is_a?(String) && /\A[A-Z][a-zA-Z0-9_:]*\z/ =~ str - end - - def path_for(const_ref) - underscore_with_fix_for_non_standard_rspec_naming(const_ref) - end - - def underscore_with_fix_for_non_standard_rspec_naming(string) - underscore(string).sub(%r{(^|/)r_spec($|/)}, '\\1rspec\\2') - end - - # activesupport/lib/active_support/inflector/methods.rb, line 48 - def underscore(camel_cased_word) - word = camel_cased_word.to_s.dup - word.gsub!(/::/, '/') - word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2') - word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') - word.tr!("-", "_") - word.downcase! - word - end - - def file_at(path) - FileUtils.mkdir_p(File.dirname(path)) - File.new(path, 'w') - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/base_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/base_formatter.rb deleted file mode 100644 index 923a6ca..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/base_formatter.rb +++ /dev/null @@ -1,172 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/helpers" -require 'stringio' - -module RSpec - module Core - module Formatters - # RSpec's built-in formatters are all subclasses of RSpec::Core::Formatters::BaseTextFormatter, - # but the BaseTextFormatter documents all of the notifications implemented as part of the standard - # interface. The reporter will issue these during a normal test suite run, but a formatter will - # only receive those notifications it has registered itself to receive. - # - # @see RSpec::Core::Formatters::BaseTextFormatter - # @see RSpec::Core::Reporter - class BaseFormatter - - # all formatters inheriting from this formatter will receive these notifications - Formatters.register self, :start, :example_group_started, :close - attr_accessor :example_group - attr_reader :output - - # @api public - # - # @param output [IO] the formatter output - def initialize(output) - @output = output || StringIO.new - @example_group = nil - end - - # @api public - # - # This method is invoked before any examples are run, right after - # they have all been collected. This can be useful for special - # formatters that need to provide progress on feedback (graphical ones). - # - # This will only be invoked once, and the next one to be invoked - # is {#example_group_started}. - # - # @param notification [StartNotification] - def start(notification) - start_sync_output - @example_count = notification.count - end - - # @api public - # - # This method is invoked at the beginning of the execution of each example group. - # - # The next method to be invoked after this is {#example_passed}, - # {#example_pending}, or {#example_group_finished}. - # - # @param notification [GroupNotification] containing example_group subclass of `RSpec::Core::ExampleGroup` - def example_group_started(notification) - @example_group = notification.group - end - - # @method example_group_finished - # @api public - # - # Invoked at the end of the execution of each example group. - # - # @param notification [GroupNotification] containing example_group subclass of `RSpec::Core::ExampleGroup` - - # @method example_started - # @api public - # - # Invoked at the beginning of the execution of each example. - # - # @param notification [ExampleNotification] containing example subclass of `RSpec::Core::Example` - - # @method example_passed - # @api public - # - # Invoked when an example passes. - # - # @param notification [ExampleNotification] containing example subclass of `RSpec::Core::Example` - - # @method example_pending - # Invoked when an example is pending. - # - # @param notification [ExampleNotification] containing example subclass of `RSpec::Core::Example` - - # @method example_failed - # @api public - # - # Invoked when an example fails. - # - # @param notification [ExampleNotification] containing example subclass of `RSpec::Core::Example` - - # @method message - # @api public - # - # Used by the reporter to send messages to the output stream. - # - # @param notification [MessageNotification] containing message - - # @method stop - # @api public - # - # Invoked after all examples have executed, before dumping post-run reports. - # - # @param notification [NullNotification] - - # @method start_dump - # @api public - # - # This method is invoked after all of the examples have executed. The next method - # to be invoked after this one is {#dump_failures} - # (BaseTextFormatter then calls {#dump_failure} once for each failed example.) - # - # @param notification [NullNotification] - - # @method dump_failures - # @api public - # - # Dumps detailed information about each example failure. - # - # @param notification [NullNotification] - - # @method dump_summary - # @api public - # - # This method is invoked after the dumping of examples and failures. Each parameter - # is assigned to a corresponding attribute. - # - # @param summary [SummaryNotification] containing duration, example_count, - # failure_count and pending_count - - # @method dump_profile - # @api public - # - # This method is invoked after the dumping the summary if profiling is - # enabled. - # - # @param profile [ProfileNotification] containing duration, slowest_examples - # and slowest_example_groups - - # @method dump_pending - # @api public - # - # Outputs a report of pending examples. This gets invoked - # after the summary if option is set to do so. - # - # @param notification [NullNotification] - - # @api public - # - # Invoked at the very end, `close` allows the formatter to clean - # up resources, e.g. open streams, etc. - # - # @param notification [NullNotification] - def close(notification) - restore_sync_output - end - - private - - def start_sync_output - @old_sync, output.sync = output.sync, true if output_supports_sync - end - - def restore_sync_output - output.sync = @old_sync if output_supports_sync and !output.closed? - end - - def output_supports_sync - output.respond_to?(:sync=) - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/base_text_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/base_text_formatter.rb deleted file mode 100644 index cb3bcde..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/base_text_formatter.rb +++ /dev/null @@ -1,78 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/base_formatter" -RSpec::Support.require_rspec_core "formatters/console_codes" - -module RSpec - module Core - module Formatters - - # Base for all of RSpec's built-in formatters. See RSpec::Core::Formatters::BaseFormatter - # to learn more about all of the methods called by the reporter. - # - # @see RSpec::Core::Formatters::BaseFormatter - # @see RSpec::Core::Reporter - class BaseTextFormatter < BaseFormatter - Formatters.register self, :message, :dump_summary, :dump_failures, - :dump_pending, :seed - - # @method message - # @api public - # - # Used by the reporter to send messages to the output stream. - # - # @param notification [MessageNotification] containing message - def message(notification) - output.puts notification.message - end - - # @method dump_failures - # @api public - # - # Dumps detailed information about each example failure. - # - # @param notification [NullNotification] - def dump_failures(notification) - return if notification.failure_notifications.empty? - output.puts notification.fully_formatted_failed_examples - end - - # @method dump_summary - # @api public - # - # This method is invoked after the dumping of examples and failures. Each parameter - # is assigned to a corresponding attribute. - # - # @param summary [SummaryNotification] containing duration, example_count, - # failure_count and pending_count - def dump_summary(summary) - output.puts summary.fully_formatted - end - - # @private - def dump_pending(notification) - return if notification.pending_examples.empty? - output.puts notification.fully_formatted_pending_examples - end - - # @private - def seed(notification) - return unless notification.seed_used? - output.puts notification.fully_formatted - end - - # @api public - # - # Invoked at the very end, `close` allows the formatter to clean - # up resources, e.g. open streams, etc. - # - # @param notification [NullNotification] - def close(notification) - return unless IO === output - return if output.closed? || output == $stdout - - output.close - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/console_codes.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/console_codes.rb deleted file mode 100644 index 812df1e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/console_codes.rb +++ /dev/null @@ -1,65 +0,0 @@ -module RSpec - module Core - module Formatters - # ConsoleCodes provides helpers for formatting console output - # with ANSI codes, e.g. color's and bold. - module ConsoleCodes - # @private - VT100_CODES = - { - :black => 30, - :red => 31, - :green => 32, - :yellow => 33, - :blue => 34, - :magenta => 35, - :cyan => 36, - :white => 37, - :bold => 1, - } - # @private - VT100_CODE_VALUES = VT100_CODES.invert - - module_function - - # Fetches the correct code for the supplied symbol, or checks - # that a code is valid. Defaults to white (37). - # - # @param code_or_symbol [Symbol, Fixnum] Symbol or code to check - # @return [Fixnum] a console code - def console_code_for(code_or_symbol) - if RSpec.configuration.respond_to?(:"#{code_or_symbol}_color") - console_code_for configuration_color(code_or_symbol) - elsif VT100_CODE_VALUES.has_key?(code_or_symbol) - code_or_symbol - else - VT100_CODES.fetch(code_or_symbol) do - console_code_for(:white) - end - end - end - - # Wraps a piece of text in ANSI codes with the supplied code. Will - # only apply the control code if `RSpec.configuration.color_enabled?` - # returns true. - # - # @param text [String] the text to wrap - # @param code_or_symbol [Symbol, Fixnum] the desired control code - # @return [String] the wrapped text - def wrap(text, code_or_symbol) - if RSpec.configuration.color_enabled? - "\e[#{console_code_for(code_or_symbol)}m#{text}\e[0m" - else - text - end - end - - # @private - def configuration_color(code) - RSpec.configuration.__send__(:"#{code}_color") - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/deprecation_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/deprecation_formatter.rb deleted file mode 100644 index fc63fd5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/deprecation_formatter.rb +++ /dev/null @@ -1,223 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/helpers" -require 'set' - -module RSpec - module Core - module Formatters - # @private - class DeprecationFormatter - Formatters.register self, :deprecation, :deprecation_summary - - attr_reader :count, :deprecation_stream, :summary_stream - - def initialize(deprecation_stream, summary_stream) - @deprecation_stream = deprecation_stream - @summary_stream = summary_stream - @seen_deprecations = Set.new - @count = 0 - end - alias :output :deprecation_stream - - def printer - @printer ||= case deprecation_stream - when File - ImmediatePrinter.new(FileStream.new(deprecation_stream), summary_stream, self) - when RaiseErrorStream - ImmediatePrinter.new(deprecation_stream, summary_stream, self) - else - DelayedPrinter.new(deprecation_stream, summary_stream, self) - end - end - - def deprecation(notification) - return if @seen_deprecations.include? notification - - @count += 1 - printer.print_deprecation_message notification - @seen_deprecations << notification - end - - def deprecation_summary(notification) - printer.deprecation_summary - end - - def deprecation_message_for(data) - if data.message - SpecifiedDeprecationMessage.new(data) - else - GeneratedDeprecationMessage.new(data) - end - end - - RAISE_ERROR_CONFIG_NOTICE = <<-EOS.gsub(/^\s+\|/, '') - | - |If you need more of the backtrace for any of these deprecations to - |identify where to make the necessary changes, you can configure - |`config.raise_errors_for_deprecations!`, and it will turn the - |deprecation warnings into errors, giving you the full backtrace. - EOS - - DEPRECATION_STREAM_NOTICE = "Pass `--deprecation-out` or set " + - "`config.deprecation_stream` to a file for full output." - - SpecifiedDeprecationMessage = Struct.new(:type) do - def initialize(data) - @message = data.message - super deprecation_type_for(data) - end - - def to_s - output_formatted @message - end - - def too_many_warnings_message - msg = "Too many similar deprecation messages reported, disregarding further reports. " - msg << DEPRECATION_STREAM_NOTICE - msg - end - - private - - def output_formatted(str) - return str unless str.lines.count > 1 - separator = "#{'-' * 80}" - "#{separator}\n#{str.chomp}\n#{separator}" - end - - def deprecation_type_for(data) - data.message.gsub(/(\w+\/)+\w+\.rb:\d+/, '') - end - end - - GeneratedDeprecationMessage = Struct.new(:type) do - def initialize(data) - @data = data - super data.deprecated - end - - def to_s - msg = "#{@data.deprecated} is deprecated." - msg << " Use #{@data.replacement} instead." if @data.replacement - msg << " Called from #{@data.call_site}." if @data.call_site - msg - end - - def too_many_warnings_message - msg = "Too many uses of deprecated '#{type}'. " - msg << DEPRECATION_STREAM_NOTICE - msg - end - end - - # @private - class ImmediatePrinter - attr_reader :deprecation_stream, :summary_stream, :deprecation_formatter - - def initialize(deprecation_stream, summary_stream, deprecation_formatter) - @deprecation_stream = deprecation_stream - - @summary_stream = summary_stream - @deprecation_formatter = deprecation_formatter - end - - def print_deprecation_message(data) - deprecation_message = deprecation_formatter.deprecation_message_for(data) - deprecation_stream.puts deprecation_message.to_s - end - - def deprecation_summary - return if deprecation_formatter.count.zero? - deprecation_stream.summarize(summary_stream, deprecation_formatter.count) - end - end - - # @private - class DelayedPrinter - TOO_MANY_USES_LIMIT = 4 - - attr_reader :deprecation_stream, :summary_stream, :deprecation_formatter - - def initialize(deprecation_stream, summary_stream, deprecation_formatter) - @deprecation_stream = deprecation_stream - @summary_stream = summary_stream - @deprecation_formatter = deprecation_formatter - @seen_deprecations = Hash.new { 0 } - @deprecation_messages = Hash.new { |h, k| h[k] = [] } - end - - def print_deprecation_message(data) - deprecation_message = deprecation_formatter.deprecation_message_for(data) - @seen_deprecations[deprecation_message] += 1 - - stash_deprecation_message(deprecation_message) - end - - def stash_deprecation_message(deprecation_message) - if @seen_deprecations[deprecation_message] < TOO_MANY_USES_LIMIT - @deprecation_messages[deprecation_message] << deprecation_message.to_s - elsif @seen_deprecations[deprecation_message] == TOO_MANY_USES_LIMIT - @deprecation_messages[deprecation_message] << deprecation_message.too_many_warnings_message - end - end - - def deprecation_summary - return unless @deprecation_messages.any? - - print_deferred_deprecation_warnings - deprecation_stream.puts RAISE_ERROR_CONFIG_NOTICE - - summary_stream.puts "\n#{Helpers.pluralize(deprecation_formatter.count, 'deprecation warning')} total" - end - - def print_deferred_deprecation_warnings - deprecation_stream.puts "\nDeprecation Warnings:\n\n" - @deprecation_messages.keys.sort_by(&:type).each do |deprecation| - messages = @deprecation_messages[deprecation] - messages.each { |msg| deprecation_stream.puts msg } - deprecation_stream.puts - end - end - end - - # @private - # Not really a stream, but is usable in place of one. - class RaiseErrorStream - def puts(message) - raise DeprecationError, message - end - - def summarize(summary_stream, deprecation_count) - summary_stream.puts "\n#{Helpers.pluralize(deprecation_count, 'deprecation')} found." - end - end - - # @private - # Wraps a File object and provides file-specific operations. - class FileStream - def initialize(file) - @file = file - - # In one of my test suites, I got lots of duplicate output in the - # deprecation file (e.g. 200 of the same deprecation, even though - # the `puts` below was only called 6 times). Setting `sync = true` - # fixes this (but we really have no idea why!). - @file.sync = true - end - - def puts(*args) - @file.puts(*args) - end - - def summarize(summary_stream, deprecation_count) - summary_stream.puts "\n#{Helpers.pluralize(deprecation_count, 'deprecation')} logged to #{@file.path}" - puts RAISE_ERROR_CONFIG_NOTICE - end - end - - end - end - - # Deprecation Error - DeprecationError = Class.new(StandardError) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/documentation_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/documentation_formatter.rb deleted file mode 100644 index b1c78c7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/documentation_formatter.rb +++ /dev/null @@ -1,69 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/base_text_formatter" - -module RSpec - module Core - module Formatters - # @private - class DocumentationFormatter < BaseTextFormatter - Formatters.register self, :example_group_started, :example_group_finished, - :example_passed, :example_pending, :example_failed - - def initialize(output) - super - @group_level = 0 - end - - def example_group_started(notification) - output.puts if @group_level == 0 - output.puts "#{current_indentation}#{notification.group.description.strip}" - - @group_level += 1 - end - - def example_group_finished(notification) - @group_level -= 1 - end - - def example_passed(passed) - output.puts passed_output(passed.example) - end - - def example_pending(pending) - output.puts pending_output(pending.example, pending.example.execution_result.pending_message) - end - - def example_failed(failure) - output.puts failure_output(failure.example, failure.example.execution_result.exception) - end - - private - - def passed_output(example) - ConsoleCodes.wrap("#{current_indentation}#{example.description.strip}", :success) - end - - def pending_output(example, message) - ConsoleCodes.wrap("#{current_indentation}#{example.description.strip} (PENDING: #{message})", :pending) - end - - def failure_output(example, exception) - ConsoleCodes.wrap("#{current_indentation}#{example.description.strip} (FAILED - #{next_failure_index})", :failure) - end - - def next_failure_index - @next_failure_index ||= 0 - @next_failure_index += 1 - end - - def current_indentation - ' ' * @group_level - end - - def example_group_chain - example_group.parent_groups.reverse - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/helpers.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/helpers.rb deleted file mode 100644 index 8e724e0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/helpers.rb +++ /dev/null @@ -1,88 +0,0 @@ -module RSpec - module Core - module Formatters - # Formatters helpers - module Helpers - - # @private - SUB_SECOND_PRECISION = 5 - - # @private - DEFAULT_PRECISION = 2 - - # @api private - # - # Formats seconds into a human-readable string. - # - # @param duration [Float, Fixnum] in seconds - # @return [String] human-readable time - # - # @example - # format_duration(1) #=> "1 minute 1 second" - # format_duration(135.14) #=> "2 minutes 15.14 seconds" - def self.format_duration(duration) - precision = case - when duration < 1; SUB_SECOND_PRECISION - when duration < 120; DEFAULT_PRECISION - when duration < 300; 1 - else 0 - end - - if duration > 60 - minutes = (duration.to_i / 60).to_i - seconds = duration - minutes * 60 - - "#{pluralize(minutes, 'minute')} #{pluralize(format_seconds(seconds, precision), 'second')}" - else - pluralize(format_seconds(duration, precision), 'second') - end - end - - # @api private - # - # Formats seconds to have 5 digits of precision with trailing zeros removed if the number - # is less than 1 or with 2 digits of precision if the number is greater than zero. - # - # @param float [Float] - # @return [String] formatted float - # - # @example - # format_seconds(0.000006) #=> "0.00001" - # format_seconds(0.020000) #=> "0.02" - # format_seconds(1.00000000001) #=> "1" - # - # The precision used is set in {Helpers::SUB_SECOND_PRECISION} and {Helpers::DEFAULT_PRECISION}. - # - # @see #strip_trailing_zeroes - def self.format_seconds(float, precision = nil) - precision ||= (float < 1) ? SUB_SECOND_PRECISION : DEFAULT_PRECISION - formatted = sprintf("%.#{precision}f", float) - strip_trailing_zeroes(formatted) - end - - # @api private - # - # Remove trailing zeros from a string. - # - # @param string [String] string with trailing zeros - # @return [String] string with trailing zeros removed - def self.strip_trailing_zeroes(string) - stripped = string.sub(/[^1-9]+$/, '') - stripped.empty? ? "0" : stripped - end - private_class_method :strip_trailing_zeroes - - # @api private - # - # Pluralize a word based on a count. - # - # @param count [Fixnum] number of objects - # @param string [String] word to be pluralized - # @return [String] pluralized word - def self.pluralize(count, string) - "#{count} #{string}#{'s' unless count.to_f == 1}" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/html_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/html_formatter.rb deleted file mode 100644 index b266835..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/html_formatter.rb +++ /dev/null @@ -1,148 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/base_text_formatter" -RSpec::Support.require_rspec_core "formatters/html_printer" - -module RSpec - module Core - module Formatters - # @private - class HtmlFormatter < BaseFormatter - Formatters.register self, :start, :example_group_started, :start_dump, - :example_started, :example_passed, :example_failed, - :example_pending, :dump_summary - - def initialize(output) - super(output) - @failed_examples = [] - @example_group_number = 0 - @example_number = 0 - @header_red = nil - @printer = HtmlPrinter.new(output) - end - - def start(notification) - super - @printer.print_html_start - @printer.flush - end - - def example_group_started(notification) - super - @example_group_red = false - @example_group_number += 1 - - unless example_group_number == 1 - @printer.print_example_group_end - end - @printer.print_example_group_start( example_group_number, notification.group.description, notification.group.parent_groups.size ) - @printer.flush - end - - def start_dump(notification) - @printer.print_example_group_end - @printer.flush - end - - def example_started(notification) - @example_number += 1 - end - - def example_passed(passed) - @printer.move_progress(percent_done) - @printer.print_example_passed( passed.example.description, passed.example.execution_result.run_time ) - @printer.flush - end - - def example_failed(failure) - @failed_examples << failure.example - unless @header_red - @header_red = true - @printer.make_header_red - end - - unless @example_group_red - @example_group_red = true - @printer.make_example_group_header_red(example_group_number) - end - - @printer.move_progress(percent_done) - - example = failure.example - - exception = failure.exception - exception_details = if exception - { - :message => exception.message, - :backtrace => failure.formatted_backtrace.join("\n") - } - else - false - end - extra = extra_failure_content(failure) - - @printer.print_example_failed( - example.execution_result.pending_fixed, - example.description, - example.execution_result.run_time, - @failed_examples.size, - exception_details, - (extra == "") ? false : extra, - true - ) - @printer.flush - end - - def example_pending(pending) - example = pending.example - - @printer.make_header_yellow unless @header_red - @printer.make_example_group_header_yellow(example_group_number) unless @example_group_red - @printer.move_progress(percent_done) - @printer.print_example_pending( example.description, example.execution_result.pending_message ) - @printer.flush - end - - def dump_summary(summary) - @printer.print_summary( - summary.duration, - summary.example_count, - summary.failure_count, - summary.pending_count - ) - @printer.flush - end - - private - - # The number of the currently running example_group - def example_group_number - @example_group_number - end - - # The number of the currently running example (a global counter) - def example_number - @example_number - end - - def percent_done - result = 100.0 - if @example_count > 0 - result = (((example_number).to_f / @example_count.to_f * 1000).to_i / 10.0).to_f - end - result - end - - # Override this method if you wish to output extra HTML for a failed spec. For example, you - # could output links to images or other files produced during the specs. - # - def extra_failure_content(failure) - RSpec::Support.require_rspec_core "formatters/snippet_extractor" - backtrace = failure.exception.backtrace.map {|line| RSpec.configuration.backtrace_formatter.backtrace_line(line)} - backtrace.compact! - @snippet_extractor ||= SnippetExtractor.new - "
#{@snippet_extractor.snippet(backtrace)}
" - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/html_printer.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/html_printer.rb deleted file mode 100644 index 3143cf1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/html_printer.rb +++ /dev/null @@ -1,402 +0,0 @@ -require 'erb' - -module RSpec - module Core - module Formatters - # @private - class HtmlPrinter - include ERB::Util # for the #h method - def initialize(output) - @output = output - end - - def print_html_start - @output.puts HTML_HEADER - @output.puts REPORT_HEADER - end - - def print_example_group_end - @output.puts " " - @output.puts "" - end - - def print_example_group_start(group_id, description, number_of_parents) - @output.puts "
" - @output.puts "
" - @output.puts "
#{h(description)}
" - end - - def print_example_passed(description, run_time) - formatted_run_time = sprintf("%.5f", run_time) - @output.puts "
#{h(description)}#{formatted_run_time}s
" - end - - def print_example_failed(pending_fixed, description, run_time, failure_id, exception, extra_content, escape_backtrace = false) - formatted_run_time = sprintf("%.5f", run_time) - - @output.puts "
" - @output.puts " #{h(description)}" - @output.puts " #{formatted_run_time}s" - @output.puts "
" - if exception - @output.puts "
#{h(exception[:message])}
" - if escape_backtrace - @output.puts "
#{h exception[:backtrace]}
" - else - @output.puts "
#{exception[:backtrace]}
" - end - end - @output.puts extra_content if extra_content - @output.puts "
" - @output.puts "
" - end - - def print_example_pending(description, pending_message) - @output.puts "
#{h(description)} (PENDING: #{h(pending_message)})
" - end - - def print_summary(duration, example_count, failure_count, pending_count) - totals = "#{example_count} example#{'s' unless example_count == 1}, " - totals << "#{failure_count} failure#{'s' unless failure_count == 1}" - totals << ", #{pending_count} pending" if pending_count > 0 - - formatted_duration = sprintf("%.5f", duration) - - @output.puts "" - @output.puts "" - @output.puts "
" - @output.puts "" - @output.puts "" - @output.puts "" - end - - def flush - @output.flush - end - - def move_progress(percent_done) - @output.puts " " - @output.flush - end - - def make_header_red - @output.puts " " - end - - def make_header_yellow - @output.puts " " - end - - def make_example_group_header_red(group_id) - @output.puts " " - @output.puts " " - end - - def make_example_group_header_yellow(group_id) - @output.puts " " - @output.puts " " - end - - private - - def indentation_style(number_of_parents) - "style=\"margin-left: #{(number_of_parents - 1) * 15}px;\"" - end - - REPORT_HEADER = <<-EOF -
- -
-
-

RSpec Code Examples

-
- -
- - - -
- -
-

 

-

 

-
-
- - -
-EOF - - GLOBAL_SCRIPTS = <<-EOF - -function addClass(element_id, classname) { - document.getElementById(element_id).className += (" " + classname); -} - -function removeClass(element_id, classname) { - var elem = document.getElementById(element_id); - var classlist = elem.className.replace(classname,''); - elem.className = classlist; -} - -function moveProgressBar(percentDone) { - document.getElementById("rspec-header").style.width = percentDone +"%"; -} - -function makeRed(element_id) { - removeClass(element_id, 'passed'); - removeClass(element_id, 'not_implemented'); - addClass(element_id,'failed'); -} - -function makeYellow(element_id) { - var elem = document.getElementById(element_id); - if (elem.className.indexOf("failed") == -1) { // class doesn't includes failed - if (elem.className.indexOf("not_implemented") == -1) { // class doesn't include not_implemented - removeClass(element_id, 'passed'); - addClass(element_id,'not_implemented'); - } - } -} - -function apply_filters() { - var passed_filter = document.getElementById('passed_checkbox').checked; - var failed_filter = document.getElementById('failed_checkbox').checked; - var pending_filter = document.getElementById('pending_checkbox').checked; - - assign_display_style("example passed", passed_filter); - assign_display_style("example failed", failed_filter); - assign_display_style("example not_implemented", pending_filter); - - assign_display_style_for_group("example_group passed", passed_filter); - assign_display_style_for_group("example_group not_implemented", pending_filter, pending_filter || passed_filter); - assign_display_style_for_group("example_group failed", failed_filter, failed_filter || pending_filter || passed_filter); -} - -function get_display_style(display_flag) { - var style_mode = 'none'; - if (display_flag == true) { - style_mode = 'block'; - } - return style_mode; -} - -function assign_display_style(classname, display_flag) { - var style_mode = get_display_style(display_flag); - var elems = document.getElementsByClassName(classname) - for (var i=0; i - - - RSpec results - - - - - - - - -EOF - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/json_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/json_formatter.rb deleted file mode 100644 index 4e694a7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/json_formatter.rb +++ /dev/null @@ -1,93 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/base_formatter" -require 'json' - -module RSpec - module Core - module Formatters - # @private - class JsonFormatter < BaseFormatter - Formatters.register self, :message, :dump_summary, :dump_profile, :stop, :close - - attr_reader :output_hash - - def initialize(output) - super - @output_hash = {} - end - - def message(notification) - (@output_hash[:messages] ||= []) << notification.message - end - - def dump_summary(summary) - @output_hash[:summary] = { - :duration => summary.duration, - :example_count => summary.example_count, - :failure_count => summary.failure_count, - :pending_count => summary.pending_count - } - @output_hash[:summary_line] = summary.totals_line - end - - def stop(notification) - @output_hash[:examples] = notification.examples.map do |example| - format_example(example).tap do |hash| - if e=example.exception - hash[:exception] = { - :class => e.class.name, - :message => e.message, - :backtrace => e.backtrace, - } - end - end - end - end - - def close(notification) - output.write @output_hash.to_json - output.close if IO === output && output != $stdout - end - - def dump_profile(profile) - @output_hash[:profile] = {} - dump_profile_slowest_examples(profile) - dump_profile_slowest_example_groups(profile) - end - - # @api private - def dump_profile_slowest_examples(profile) - @output_hash[:profile] = {} - sorted_examples = profile.slowest_examples - @output_hash[:profile][:examples] = sorted_examples.map do |example| - format_example(example).tap do |hash| - hash[:run_time] = example.execution_result.run_time - end - end - @output_hash[:profile][:slowest] = profile.slow_duration - @output_hash[:profile][:total] = profile.duration - end - - # @api private - def dump_profile_slowest_example_groups(profile) - @output_hash[:profile] ||= {} - @output_hash[:profile][:groups] = profile.slowest_groups.map do |loc, hash| - hash.update(:location => loc) - end - end - - private - - def format_example(example) - { - :description => example.description, - :full_description => example.full_description, - :status => example.execution_result.status.to_s, - :file_path => example.metadata[:file_path], - :line_number => example.metadata[:line_number], - :run_time => example.execution_result.run_time - } - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/profile_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/profile_formatter.rb deleted file mode 100644 index e3f94db..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/profile_formatter.rb +++ /dev/null @@ -1,67 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/console_codes" - -module RSpec - module Core - module Formatters - - # @api private - # Formatter for providing profile output - class ProfileFormatter - Formatters.register self, :dump_profile - - def initialize(output) - @output = output - end - - # @private - attr_reader :output - - # @method dump_profile - # @api public - # - # This method is invoked after the dumping the summary if profiling is - # enabled. - # - # @param profile [ProfileNotification] containing duration, slowest_examples - # and slowest_example_groups - def dump_profile(profile) - dump_profile_slowest_examples(profile) - dump_profile_slowest_example_groups(profile) - end - - private - - def dump_profile_slowest_examples(profile) - @output.puts "\nTop #{profile.slowest_examples.size} slowest examples (#{Helpers.format_seconds(profile.slow_duration)} seconds, #{profile.percentage}% of total time):\n" - - profile.slowest_examples.each do |example| - @output.puts " #{example.full_description}" - @output.puts " #{bold(Helpers.format_seconds(example.execution_result.run_time))} #{bold("seconds")} #{format_caller(example.location)}" - end - end - - def dump_profile_slowest_example_groups(profile) - return if profile.slowest_groups.empty? - - @output.puts "\nTop #{profile.slowest_groups.size} slowest example groups:" - profile.slowest_groups.each do |loc, hash| - average = "#{bold(Helpers.format_seconds(hash[:average]))} #{bold("seconds")} average" - total = "#{Helpers.format_seconds(hash[:total_time])} seconds" - count = Helpers.pluralize(hash[:count], "example") - @output.puts " #{hash[:description]}" - @output.puts " #{average} (#{total} / #{count}) #{loc}" - end - end - - def format_caller(caller_info) - RSpec.configuration.backtrace_formatter.backtrace_line(caller_info.to_s.split(':in `block').first) - end - - def bold(text) - ConsoleCodes.wrap(text, :bold) - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/progress_formatter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/progress_formatter.rb deleted file mode 100644 index 3e4bb15..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/progress_formatter.rb +++ /dev/null @@ -1,28 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/base_text_formatter" - -module RSpec - module Core - module Formatters - # @private - class ProgressFormatter < BaseTextFormatter - Formatters.register self, :example_passed, :example_pending, :example_failed, :start_dump - - def example_passed(notification) - output.print ConsoleCodes.wrap('.', :success) - end - - def example_pending(notification) - output.print ConsoleCodes.wrap('*', :pending) - end - - def example_failed(notification) - output.print ConsoleCodes.wrap('F', :failure) - end - - def start_dump(notification) - output.puts - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/snippet_extractor.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/snippet_extractor.rb deleted file mode 100644 index 564cb63..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/formatters/snippet_extractor.rb +++ /dev/null @@ -1,103 +0,0 @@ -module RSpec - module Core - module Formatters - # @api private - # - # Extracts code snippets by looking at the backtrace of the passed error and applies synax highlighting and line numbers using html. - class SnippetExtractor - # @private - class NullConverter - def convert(code) - %Q(#{code}\n# Install the coderay gem to get syntax highlighting) - end - end - - # @private - class CoderayConverter - def convert(code) - CodeRay.scan(code, :ruby).html(:line_numbers => false) - end - end - - begin - require 'coderay' - @@converter = CoderayConverter.new - rescue LoadError - @@converter = NullConverter.new - end - - # @api private - # - # Extract lines of code corresponding to a backtrace. - # - # @param backtrace [String] the backtrace from a test failure - # @return [String] highlighted code snippet indicating where the test failure occured - # - # @see #post_process - def snippet(backtrace) - raw_code, line = snippet_for(backtrace[0]) - highlighted = @@converter.convert(raw_code) - post_process(highlighted, line) - end - - # @api private - # - # Create a snippet from a line of code. - # - # @param error_line [String] file name with line number (i.e. 'foo_spec.rb:12') - # @return [String] lines around the target line within the file - # - # @see #lines_around - def snippet_for(error_line) - if error_line =~ /(.*):(\d+)/ - file = $1 - line = $2.to_i - [lines_around(file, line), line] - else - ["# Couldn't get snippet for #{error_line}", 1] - end - end - - # @api private - # - # Extract lines of code centered around a particular line within a source file. - # - # @param file [String] filename - # @param line [Fixnum] line number - # @return [String] lines around the target line within the file (2 above and 1 below). - def lines_around(file, line) - if File.file?(file) - lines = File.read(file).split("\n") - min = [0, line-3].max - max = [line+1, lines.length-1].min - selected_lines = [] - selected_lines.join("\n") - lines[min..max].join("\n") - else - "# Couldn't get snippet for #{file}" - end - rescue SecurityError - "# Couldn't get snippet for #{file}" - end - - # @api private - # - # Adds line numbers to all lines and highlights the line where the failure occurred using html `span` tags. - # - # @param highlighted [String] syntax-highlighted snippet surrounding the offending line of code - # @param offending_line [Fixnum] line where failure occured - # @return [String] completed snippet - def post_process(highlighted, offending_line) - new_lines = [] - highlighted.split("\n").each_with_index do |line, i| - new_line = "#{offending_line+i-2}#{line}" - new_line = "#{new_line}" if i == 2 - new_lines << new_line - end - new_lines.join("\n") - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/hooks.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/hooks.rb deleted file mode 100644 index 7f1b6c9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/hooks.rb +++ /dev/null @@ -1,576 +0,0 @@ -module RSpec - module Core - # Provides `before`, `after` and `around` hooks as a means of - # supporting common setup and teardown. This module is extended - # onto {ExampleGroup}, making the methods available from any `describe` - # or `context` block and included in {Configuration}, making them - # available off of the configuration object to define global setup - # or teardown logic. - module Hooks - # @api public - # - # @overload before(&block) - # @overload before(scope, &block) - # @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to `:example`) - # @overload before(scope, conditions, &block) - # @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to `:example`) - # @param conditions [Hash] - # constrains this hook to examples matching these conditions e.g. - # `before(:example, :ui => true) { ... }` will only run with examples or - # groups declared with `:ui => true`. - # @overload before(conditions, &block) - # @param conditions [Hash] - # constrains this hook to examples matching these conditions e.g. - # `before(:example, :ui => true) { ... }` will only run with examples or - # groups declared with `:ui => true`. - # - # @see #after - # @see #around - # @see ExampleGroup - # @see SharedContext - # @see SharedExampleGroup - # @see Configuration - # - # Declare a block of code to be run before each example (using `:example`) - # or once before any example (using `:context`). These are usually declared - # directly in the {ExampleGroup} to which they apply, but they can also - # be shared across multiple groups. - # - # You can also use `before(:suite)` to run a block of code before any - # example groups are run. This should be declared in {RSpec.configure} - # - # Instance variables declared in `before(:example)` or `before(:context)` are - # accessible within each example. - # - # ### Order - # - # `before` hooks are stored in three scopes, which are run in order: - # `:suite`, `:context`, and `:example`. They can also be declared in several - # different places: `RSpec.configure`, a parent group, the current group. - # They are run in the following order: - # - # before(:suite) # declared in RSpec.configure - # before(:context) # declared in RSpec.configure - # before(:context) # declared in a parent group - # before(:context) # declared in the current group - # before(:example) # declared in RSpec.configure - # before(:example) # declared in a parent group - # before(:example) # declared in the current group - # - # If more than one `before` is declared within any one scope, they are run - # in the order in which they are declared. - # - # ### Conditions - # - # When you add a conditions hash to `before(:example)` or `before(:context)`, - # RSpec will only apply that hook to groups or examples that match the - # conditions. e.g. - # - # RSpec.configure do |config| - # config.before(:example, :authorized => true) do - # log_in_as :authorized_user - # end - # end - # - # describe Something, :authorized => true do - # # the before hook will run in before each example in this group - # end - # - # describe SomethingElse do - # it "does something", :authorized => true do - # # the before hook will run before this example - # end - # - # it "does something else" do - # # the hook will not run before this example - # end - # end - # - # ### Warning: `before(:suite, :with => :conditions)` - # - # The conditions hash is used to match against specific examples. Since - # `before(:suite)` is not run in relation to any specific example or - # group, conditions passed along with `:suite` are effectively ignored. - # - # ### Exceptions - # - # When an exception is raised in a `before` block, RSpec skips any - # subsequent `before` blocks and the example, but runs all of the - # `after(:example)` and `after(:context)` hooks. - # - # ### Warning: implicit before blocks - # - # `before` hooks can also be declared in shared contexts which get - # included implicitly either by you or by extension libraries. Since - # RSpec runs these in the order in which they are declared within each - # scope, load order matters, and can lead to confusing results when one - # before block depends on state that is prepared in another before block - # that gets run later. - # - # ### Warning: `before(:context)` - # - # It is very tempting to use `before(:context)` to speed things up, but we - # recommend that you avoid this as there are a number of gotchas, as well - # as things that simply don't work. - # - # #### context - # - # `before(:context)` is run in an example that is generated to provide group - # context for the block. - # - # #### instance variables - # - # Instance variables declared in `before(:context)` are shared across all the - # examples in the group. This means that each example can change the - # state of a shared object, resulting in an ordering dependency that can - # make it difficult to reason about failures. - # - # #### unsupported rspec constructs - # - # RSpec has several constructs that reset state between each example - # automatically. These are not intended for use from within `before(:context)`: - # - # * `let` declarations - # * `subject` declarations - # * Any mocking, stubbing or test double declaration - # - # ### other frameworks - # - # Mock object frameworks and database transaction managers (like - # ActiveRecord) are typically designed around the idea of setting up - # before an example, running that one example, and then tearing down. - # This means that mocks and stubs can (sometimes) be declared in - # `before(:context)`, but get torn down before the first real example is ever - # run. - # - # You _can_ create database-backed model objects in a `before(:context)` in - # rspec-rails, but it will not be wrapped in a transaction for you, so - # you are on your own to clean up in an `after(:context)` block. - # - # @example before(:example) declared in an {ExampleGroup} - # - # describe Thing do - # before(:example) do - # @thing = Thing.new - # end - # - # it "does something" do - # # here you can access @thing - # end - # end - # - # @example before(:context) declared in an {ExampleGroup} - # - # describe Parser do - # before(:context) do - # File.open(file_to_parse, 'w') do |f| - # f.write <<-CONTENT - # stuff in the file - # CONTENT - # end - # end - # - # it "parses the file" do - # Parser.parse(file_to_parse) - # end - # - # after(:context) do - # File.delete(file_to_parse) - # end - # end - # - # @note The `:example` and `:context` scopes are also available as - # `:each` and `:all`, respectively. Use whichever you prefer. - def before(*args, &block) - hooks.register :append, :before, *args, &block - end - - alias_method :append_before, :before - - # Adds `block` to the front of the list of `before` blocks in the same - # scope (`:example`, `:context`, or `:suite`). - # - # See {#before} for scoping semantics. - def prepend_before(*args, &block) - hooks.register :prepend, :before, *args, &block - end - - # @api public - # @overload after(&block) - # @overload after(scope, &block) - # @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to `:example`) - # @overload after(scope, conditions, &block) - # @param scope [Symbol] `:example`, `:context`, or `:suite` (defaults to `:example`) - # @param conditions [Hash] - # constrains this hook to examples matching these conditions e.g. - # `after(:example, :ui => true) { ... }` will only run with examples or - # groups declared with `:ui => true`. - # @overload after(conditions, &block) - # @param conditions [Hash] - # constrains this hook to examples matching these conditions e.g. - # `after(:example, :ui => true) { ... }` will only run with examples or - # groups declared with `:ui => true`. - # - # @see #before - # @see #around - # @see ExampleGroup - # @see SharedContext - # @see SharedExampleGroup - # @see Configuration - # - # Declare a block of code to be run after each example (using `:example`) or - # once after all examples n the context (using `:context`). See {#before} for - # more information about ordering. - # - # ### Exceptions - # - # `after` hooks are guaranteed to run even when there are exceptions in - # `before` hooks or examples. When an exception is raised in an after - # block, the exception is captured for later reporting, and subsequent - # `after` blocks are run. - # - # ### Order - # - # `after` hooks are stored in three scopes, which are run in order: - # `:example`, `:context`, and `:suite`. They can also be declared in several - # different places: `RSpec.configure`, a parent group, the current group. - # They are run in the following order: - # - # after(:example) # declared in the current group - # after(:example) # declared in a parent group - # after(:example) # declared in RSpec.configure - # after(:context) # declared in the current group - # after(:context) # declared in a parent group - # after(:context) # declared in RSpec.configure - # after(:suite) # declared in RSpec.configure - # - # This is the reverse of the order in which `before` hooks are run. - # Similarly, if more than one `after` is declared within any one scope, - # they are run in reverse order of that in which they are declared. - # - # @note The `:example` and `:context` scopes are also available as - # `:each` and `:all`, respectively. Use whichever you prefer. - def after(*args, &block) - hooks.register :prepend, :after, *args, &block - end - - alias_method :prepend_after, :after - - # Adds `block` to the back of the list of `after` blocks in the same - # scope (`:example`, `:context`, or `:suite`). - # - # See {#after} for scoping semantics. - def append_after(*args, &block) - hooks.register :append, :after, *args, &block - end - - # @api public - # @overload around(&block) - # @overload around(scope, &block) - # @param scope [Symbol] `:example` (defaults to `:example`) - # present for syntax parity with `before` and `after`, but - # `:example`/`:each` is the only supported value. - # @overload around(scope, conditions, &block) - # @param scope [Symbol] `:example` (defaults to `:example`) - # present for syntax parity with `before` and `after`, but - # `:example`/`:each` is the only supported value. - # @param conditions [Hash] - # constrains this hook to examples matching these conditions e.g. - # `around(:example, :ui => true) { ... }` will only run with examples or - # groups declared with `:ui => true`. - # @overload around(conditions, &block) - # @param conditions [Hash] - # constrains this hook to examples matching these conditions e.g. - # `around(:example, :ui => true) { ... }` will only run with examples or - # groups declared with `:ui => true`. - # - # @yield [Example] the example to run - # - # @note the syntax of `around` is similar to that of `before` and `after` - # but the semantics are quite different. `before` and `after` hooks are - # run in the context of of the examples with which they are associated, - # whereas `around` hooks are actually responsible for running the - # examples. Consequently, `around` hooks do not have direct access to - # resources that are made available within the examples and their - # associated `before` and `after` hooks. - # - # @note `:example`/`:each` is the only supported scope. - # - # Declare a block of code, parts of which will be run before and parts - # after the example. It is your responsibility to run the example: - # - # around(:example) do |ex| - # # do some stuff before - # ex.run - # # do some stuff after - # end - # - # The yielded example aliases `run` with `call`, which lets you treat it - # like a `Proc`. This is especially handy when working with libaries - # that manage their own setup and teardown using a block or proc syntax, - # e.g. - # - # around(:example) {|ex| Database.transaction(&ex)} - # around(:example) {|ex| FakeFS(&ex)} - # - def around(*args, &block) - hooks.register :prepend, :around, *args, &block - end - - # @private - # Holds the various registered hooks. - def hooks - @hooks ||= HookCollections.new(self, - :around => { :example => AroundHookCollection.new }, - :before => { :example => HookCollection.new, :context => HookCollection.new, :suite => HookCollection.new }, - :after => { :example => HookCollection.new, :context => HookCollection.new, :suite => HookCollection.new } - ) - end - - private - - # @private - class Hook - attr_reader :block, :options - - def initialize(block, options) - @block = block - @options = options - end - - def options_apply?(example_or_group) - example_or_group.all_apply?(options) - end - end - - # @private - class BeforeHook < Hook - def run(example) - example.instance_exec(example, &block) - end - end - - # @private - class AfterHook < Hook - def run(example) - example.instance_exec_with_rescue("in an after hook", &block) - end - end - - # @private - class AfterContextHook < Hook - def run(example) - example.instance_exec(example, &block) - rescue Exception => e - # TODO: come up with a better solution for this. - RSpec.configuration.reporter.message <<-EOS - -An error occurred in an `after(:context)` hook. - #{e.class}: #{e.message} - occurred at #{e.backtrace.first} - -EOS - end - end - - # @private - AroundHook = Hook - - # @private - class BaseHookCollection - Array.public_instance_methods(false).each do |name| - define_method(name) { |*a, &b| hooks.__send__(name, *a, &b) } - end - - attr_reader :hooks - protected :hooks - - alias append push - alias prepend unshift - - def initialize(hooks=[]) - @hooks = hooks - end - end - - # @private - class HookCollection < BaseHookCollection - def for(example_or_group) - self.class. - new(hooks.select {|hook| hook.options_apply?(example_or_group)}). - with(example_or_group) - end - - def with(example) - @example = example - self - end - - def run - hooks.each {|h| h.run(@example)} - end - end - - # @private - class AroundHookCollection < BaseHookCollection - def for(example, initial_procsy=nil) - self.class.new(hooks.select {|hook| hook.options_apply?(example)}). - with(example, initial_procsy) - end - - def with(example, initial_procsy) - @example = example - @initial_procsy = initial_procsy - self - end - - def run - hooks.inject(@initial_procsy) do |procsy, around_hook| - procsy.wrap do - @example.instance_exec(procsy, &around_hook.block) - end - end.call - end - end - - # @private - class GroupHookCollection < BaseHookCollection - def for(group) - @group = group - self - end - - def run - hooks.shift.run(@group) until hooks.empty? - end - end - - # @private - class HookCollections - def initialize(owner, data) - @owner = owner - @data = data - end - - def [](key) - @data[key] - end - - def register_globals(host, globals) - process(host, globals, :before, :example) - process(host, globals, :after, :example) - process(host, globals, :around, :example) - - process(host, globals, :before, :context) - process(host, globals, :after, :context) - end - - def around_example_hooks_for(example, initial_procsy=nil) - AroundHookCollection.new(FlatMap.flat_map(@owner.parent_groups) do |a| - a.hooks[:around][:example] - end).for(example, initial_procsy) - end - - def register(prepend_or_append, hook, *args, &block) - scope, options = scope_and_options_from(*args) - self[hook][scope].__send__(prepend_or_append, HOOK_TYPES[hook][scope].new(block, options)) - end - - # @private - # - # Runs all of the blocks stored with the hook in the context of the - # example. If no example is provided, just calls the hook directly. - def run(hook, scope, example_or_group, initial_procsy=nil) - return if RSpec.configuration.dry_run? - find_hook(hook, scope, example_or_group, initial_procsy).run - end - - SCOPES = [:example, :context, :suite] - - SCOPE_ALIASES = { :each => :example, :all => :context } - - HOOK_TYPES = { - :before => Hash.new { BeforeHook }, - :after => Hash.new { AfterHook }, - :around => Hash.new { AroundHook } - } - - HOOK_TYPES[:after][:context] = AfterContextHook - - private - - def process(host, globals, position, scope) - globals[position][scope].each do |hook| - next unless scope == :example || hook.options_apply?(host) - next if host.parent_groups.any? {|a| a.hooks[position][scope].include?(hook)} - self[position][scope] << hook - end - end - - def scope_and_options_from(*args) - scope = extract_scope_from(args) - meta = Metadata.build_hash_from(args, :warn_about_example_group_filtering) - return scope, meta - end - - def extract_scope_from(args) - if known_scope?(args.first) - normalized_scope_for(args.shift) - elsif args.any? { |a| a.is_a?(Symbol) } - error_message = "You must explicitly give a scope (#{SCOPES.join(", ")}) or scope alias (#{SCOPE_ALIASES.keys.join(", ")}) when using symbols as metadata for a hook." - raise ArgumentError.new error_message - else - :example - end - end - - # @api private - def known_scope?(scope) - SCOPES.include?(scope) || SCOPE_ALIASES.keys.include?(scope) - end - - # @api private - def normalized_scope_for(scope) - SCOPE_ALIASES[scope] || scope - end - - def find_hook(hook, scope, example_or_group, initial_procsy) - case [hook, scope] - when [:before, :context] - before_context_hooks_for(example_or_group) - when [:after, :context] - after_context_hooks_for(example_or_group) - when [:around, :example] - around_example_hooks_for(example_or_group, initial_procsy) - when [:before, :example] - before_example_hooks_for(example_or_group) - when [:after, :example] - after_example_hooks_for(example_or_group) - when [:before, :suite], [:after, :suite] - self[hook][:suite].with(example_or_group) - end - end - - def before_context_hooks_for(group) - GroupHookCollection.new(self[:before][:context]).for(group) - end - - def after_context_hooks_for(group) - GroupHookCollection.new(self[:after][:context]).for(group) - end - - def before_example_hooks_for(example) - HookCollection.new(FlatMap.flat_map(@owner.parent_groups.reverse) do |a| - a.hooks[:before][:example] - end).for(example) - end - - def after_example_hooks_for(example) - HookCollection.new(FlatMap.flat_map(@owner.parent_groups) do |a| - a.hooks[:after][:example] - end).for(example) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/memoized_helpers.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/memoized_helpers.rb deleted file mode 100644 index a8f880e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/memoized_helpers.rb +++ /dev/null @@ -1,470 +0,0 @@ -module RSpec - module Core - # This module is included in {ExampleGroup}, making the methods - # available to be called from within example blocks. - # - # @see ClassMethods - module MemoizedHelpers - # @note `subject` was contributed by Joe Ferris to support the one-liner - # syntax embraced by shoulda matchers: - # - # describe Widget do - # it { is_expected.to validate_presence_of(:name) } - # # or - # it { should validate_presence_of(:name) } - # end - # - # While the examples below demonstrate how to use `subject` - # explicitly in examples, we recommend that you define a method with - # an intention revealing name instead. - # - # @example - # - # # explicit declaration of subject - # describe Person do - # subject { Person.new(:birthdate => 19.years.ago) } - # it "should be eligible to vote" do - # subject.should be_eligible_to_vote - # # ^ ^ explicit reference to subject not recommended - # end - # end - # - # # implicit subject => { Person.new } - # describe Person do - # it "should be eligible to vote" do - # subject.should be_eligible_to_vote - # # ^ ^ explicit reference to subject not recommended - # end - # end - # - # # one-liner syntax - expectation is set on the subject - # describe Person do - # it { is_expected.to be_eligible_to_vote } - # # or - # it { should be_eligible_to_vote } - # end - # - # @note Because `subject` is designed to create state that is reset between - # each example, and `before(:context)` is designed to setup state that is - # shared across _all_ examples in an example group, `subject` is _not_ - # intended to be used in a `before(:context)` hook. - # - # @see #should - # @see #should_not - # @see #is_expected - def subject - __memoized.fetch(:subject) do - __memoized[:subject] = begin - described = described_class || self.class.description - Class === described ? described.new : described - end - end - end - - # When `should` is called with no explicit receiver, the call is - # delegated to the object returned by `subject`. Combined with an - # implicit subject this supports very concise expressions. - # - # @example - # - # describe Person do - # it { should be_eligible_to_vote } - # end - # - # @see #subject - # @see #is_expected - # - # @note This only works if you are using rspec-expectations. - # @note If you are using RSpec's newer expect-based syntax you may - # want to use `is_expected.to` instead of `should`. - def should(matcher=nil, message=nil) - RSpec::Expectations::PositiveExpectationHandler.handle_matcher(subject, matcher, message) - end - - # Just like `should`, `should_not` delegates to the subject (implicit or - # explicit) of the example group. - # - # @example - # - # describe Person do - # it { should_not be_eligible_to_vote } - # end - # - # @see #subject - # @see #is_expected - # - # @note This only works if you are using rspec-expectations. - # @note If you are using RSpec's newer expect-based syntax you may - # want to use `is_expected.to_not` instead of `should_not`. - def should_not(matcher=nil, message=nil) - RSpec::Expectations::NegativeExpectationHandler.handle_matcher(subject, matcher, message) - end - - # Wraps the `subject` in `expect` to make it the target of an expectation. - # Designed to read nicely for one-liners. - # - # @example - # - # describe [1, 2, 3] do - # it { is_expected.to be_an Array } - # it { is_expected.not_to include 4 } - # end - # - # @see #subject - # @see #should - # @see #should_not - # - # @note This only works if you are using rspec-expectations. - def is_expected - expect(subject) - end - - private - - # @private - def __memoized - @__memoized ||= {} - end - - # Used internally to customize the behavior of the - # memoized hash when used in a `before(:context)` hook. - # - # @private - class ContextHookMemoizedHash - def self.isolate_for_context_hook(example_group_instance) - hash = self - - example_group_instance.instance_exec do - @__memoized = hash - - begin - yield - ensure - @__memoized = nil - end - end - end - - def self.fetch(key, &block) - description = if key == :subject - "subject" - else - "let declaration `#{key}`" - end - - raise <<-EOS -#{description} accessed in #{article} #{hook_expression} hook at: - #{CallerFilter.first_non_rspec_line} - -`let` and `subject` declarations are not intended to be called -in #{article} #{hook_expression} hook, as they exist to define state that -is reset between each example, while #{hook_expression} exists to -#{hook_intention}. -EOS - end - - # @private - class Before < self - def self.hook_expression - "`before(:context)`" - end - - def self.article - "a" - end - - def self.hook_intention - "define state that is shared across examples in an example group" - end - end - - # @private - class After < self - def self.hook_expression - "`after(:context)`" - end - - def self.article - "an" - end - - def self.hook_intention - "cleanup state that is shared across examples in an example group" - end - end - end - - # This module is extended onto {ExampleGroup}, making the methods - # available to be called from within example group blocks. - # You can think of them as being analagous to class macros. - module ClassMethods - # Generates a method whose return value is memoized after the first - # call. Useful for reducing duplication between examples that assign - # values to the same local variable. - # - # @note `let` _can_ enhance readability when used sparingly (1,2, or - # maybe 3 declarations) in any given example group, but that can - # quickly degrade with overuse. YMMV. - # - # @note `let` uses an `||=` conditional that has the potential to - # behave in surprising ways in examples that spawn separate threads, - # though we have yet to see this in practice. You've been warned. - # - # @note Because `let` is designed to create state that is reset between - # each example, and `before(:context)` is designed to setup state that is - # shared across _all_ examples in an example group, `let` is _not_ - # intended to be used in a `before(:context)` hook. - # - # @example - # - # describe Thing do - # let(:thing) { Thing.new } - # - # it "does something" do - # # first invocation, executes block, memoizes and returns result - # thing.do_something - # - # # second invocation, returns the memoized value - # thing.should be_something - # end - # end - def let(name, &block) - # We have to pass the block directly to `define_method` to - # allow it to use method constructs like `super` and `return`. - raise "#let or #subject called without a block" if block.nil? - MemoizedHelpers.module_for(self).__send__(:define_method, name, &block) - - # Apply the memoization. The method has been defined in an ancestor - # module so we can use `super` here to get the value. - if block.arity == 1 - define_method(name) { __memoized.fetch(name) { |k| __memoized[k] = super(RSpec.current_example, &nil) } } - else - define_method(name) { __memoized.fetch(name) { |k| __memoized[k] = super(&nil) } } - end - end - - # Just like `let`, except the block is invoked by an implicit `before` - # hook. This serves a dual purpose of setting up state and providing a - # memoized reference to that state. - # - # @example - # - # class Thing - # def self.count - # @count ||= 0 - # end - # - # def self.count=(val) - # @count += val - # end - # - # def self.reset_count - # @count = 0 - # end - # - # def initialize - # self.class.count += 1 - # end - # end - # - # describe Thing do - # after(:example) { Thing.reset_count } - # - # context "using let" do - # let(:thing) { Thing.new } - # - # it "is not invoked implicitly" do - # Thing.count.should eq(0) - # end - # - # it "can be invoked explicitly" do - # thing - # Thing.count.should eq(1) - # end - # end - # - # context "using let!" do - # let!(:thing) { Thing.new } - # - # it "is invoked implicitly" do - # Thing.count.should eq(1) - # end - # - # it "returns memoized version on first invocation" do - # thing - # Thing.count.should eq(1) - # end - # end - # end - def let!(name, &block) - let(name, &block) - before { __send__(name) } - end - - # Declares a `subject` for an example group which can then be wrapped - # with `expect` using `is_expected` to make it the target of an expectation - # in a concise, one-line example. - # - # Given a `name`, defines a method with that name which returns the - # `subject`. This lets you declare the subject once and access it - # implicitly in one-liners and explicitly using an intention revealing - # name. - # - # @param name [String,Symbol] used to define an accessor with an - # intention revealing name - # @param block defines the value to be returned by `subject` in examples - # - # @example - # - # describe CheckingAccount, "with $50" do - # subject { CheckingAccount.new(Money.new(50, :USD)) } - # it { is_expected.to have_a_balance_of(Money.new(50, :USD)) } - # it { is_expected.not_to be_overdrawn } - # end - # - # describe CheckingAccount, "with a non-zero starting balance" do - # subject(:account) { CheckingAccount.new(Money.new(50, :USD)) } - # it { is_expected.not_to be_overdrawn } - # it "has a balance equal to the starting balance" do - # account.balance.should eq(Money.new(50, :USD)) - # end - # end - # - # @see MemoizedHelpers#should - # @see MemoizedHelpers#should_not - # @see MemoizedHelpers#is_expected - def subject(name=nil, &block) - if name - let(name, &block) - alias_method :subject, name - - self::NamedSubjectPreventSuper.__send__(:define_method, name) do - raise NotImplementedError, "`super` in named subjects is not supported" - end - else - let(:subject, &block) - end - end - - # Just like `subject`, except the block is invoked by an implicit `before` - # hook. This serves a dual purpose of setting up state and providing a - # memoized reference to that state. - # - # @example - # - # class Thing - # def self.count - # @count ||= 0 - # end - # - # def self.count=(val) - # @count += val - # end - # - # def self.reset_count - # @count = 0 - # end - # - # def initialize - # self.class.count += 1 - # end - # end - # - # describe Thing do - # after(:example) { Thing.reset_count } - # - # context "using subject" do - # subject { Thing.new } - # - # it "is not invoked implicitly" do - # Thing.count.should eq(0) - # end - # - # it "can be invoked explicitly" do - # subject - # Thing.count.should eq(1) - # end - # end - # - # context "using subject!" do - # subject!(:thing) { Thing.new } - # - # it "is invoked implicitly" do - # Thing.count.should eq(1) - # end - # - # it "returns memoized version on first invocation" do - # subject - # Thing.count.should eq(1) - # end - # end - # end - def subject!(name=nil, &block) - subject(name, &block) - before { subject } - end - end - - # @private - # - # Gets the LetDefinitions module. The module is mixed into - # the example group and is used to hold all let definitions. - # This is done so that the block passed to `let` can be - # forwarded directly on to `define_method`, so that all method - # constructs (including `super` and `return`) can be used in - # a `let` block. - # - # The memoization is provided by a method definition on the - # example group that supers to the LetDefinitions definition - # in order to get the value to memoize. - def self.module_for(example_group) - get_constant_or_yield(example_group, :LetDefinitions) do - mod = Module.new do - include Module.new { - example_group.const_set(:NamedSubjectPreventSuper, self) - } - end - - example_group.const_set(:LetDefinitions, mod) - mod - end - end - - # @private - def self.define_helpers_on(example_group) - example_group.__send__(:include, module_for(example_group)) - end - - if Module.method(:const_defined?).arity == 1 # for 1.8 - # @private - # - # Gets the named constant or yields. - # On 1.8, const_defined? / const_get do not take into - # account the inheritance hierarchy. - def self.get_constant_or_yield(example_group, name) - if example_group.const_defined?(name) - example_group.const_get(name) - else - yield - end - end - else - # @private - # - # Gets the named constant or yields. - # On 1.9, const_defined? / const_get take into account the - # the inheritance by default, and accept an argument to - # disable this behavior. It's important that we don't - # consider inheritance here; each example group level that - # uses a `let` should get its own `LetDefinitions` module. - def self.get_constant_or_yield(example_group, name) - if example_group.const_defined?(name, (check_ancestors = false)) - example_group.const_get(name, check_ancestors) - else - yield - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/metadata.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/metadata.rb deleted file mode 100644 index a5fc706..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/metadata.rb +++ /dev/null @@ -1,427 +0,0 @@ -module RSpec - module Core - # Each ExampleGroup class and Example instance owns an instance of - # Metadata, which is Hash extended to support lazy evaluation of values - # associated with keys that may or may not be used by any example or group. - # - # In addition to metadata that is used internally, this also stores - # user-supplied metadata, e.g. - # - # describe Something, :type => :ui do - # it "does something", :slow => true do - # # ... - # end - # end - # - # `:type => :ui` is stored in the Metadata owned by the example group, and - # `:slow => true` is stored in the Metadata owned by the example. These can - # then be used to select which examples are run using the `--tag` option on - # the command line, or several methods on `Configuration` used to filter a - # run (e.g. `filter_run_including`, `filter_run_excluding`, etc). - # - # @see Example#metadata - # @see ExampleGroup.metadata - # @see FilterManager - # @see Configuration#filter_run_including - # @see Configuration#filter_run_excluding - module Metadata - # @api private - # - # @param line [String] current code line - # @return [String] relative path to line - def self.relative_path(line) - line = line.sub(File.expand_path("."), ".") - line = line.sub(/\A([^:]+:\d+)$/, '\\1') - return nil if line == '-e:1' - line - rescue SecurityError - nil - end - - # @private - # Used internally to build a hash from an args array. - # Symbols are converted into hash keys with a value of `true`. - # This is done to support simple tagging using a symbol, rather - # than needing to do `:symbol => true`. - def self.build_hash_from(args, warn_about_example_group_filtering=false) - hash = args.last.is_a?(Hash) ? args.pop : {} - - while args.last.is_a?(Symbol) - hash[args.pop] = true - end - - if warn_about_example_group_filtering && hash.key?(:example_group) - RSpec.deprecate("Filtering by an `:example_group` subhash", - :replacement => "the subhash to filter directly") - end - - hash - end - - # @private - def self.backtrace_from(block) - return caller unless block.respond_to?(:source_location) - [block.source_location.join(':')] - end - - # @private - # Used internally to populate metadata hashes with computed keys - # managed by RSpec. - class HashPopulator - attr_reader :metadata, :user_metadata, :description_args, :block - - def initialize(metadata, user_metadata, description_args, block) - @metadata = metadata - @user_metadata = user_metadata - @description_args = description_args - @block = block - end - - def populate - ensure_valid_user_keys - - metadata[:execution_result] = Example::ExecutionResult.new - metadata[:block] = block - metadata[:description_args] = description_args - metadata[:description] = build_description_from(*metadata[:description_args]) - metadata[:full_description] = full_description - metadata[:described_class] = described_class - - populate_location_attributes - metadata.update(user_metadata) - RSpec.configuration.apply_derived_metadata_to(metadata) - end - - private - - def populate_location_attributes - file_path, line_number = if backtrace = user_metadata.delete(:caller) - file_path_and_line_number_from(backtrace) - elsif block.respond_to?(:source_location) - block.source_location - else - file_path_and_line_number_from(caller) - end - - file_path = Metadata.relative_path(file_path) - metadata[:file_path] = file_path - metadata[:line_number] = line_number.to_i - metadata[:location] = "#{file_path}:#{line_number}" - end - - def file_path_and_line_number_from(backtrace) - first_caller_from_outside_rspec = backtrace.detect { |l| l !~ CallerFilter::LIB_REGEX } - first_caller_from_outside_rspec ||= backtrace.first - /(.+?):(\d+)(?:|:\d+)/.match(first_caller_from_outside_rspec).captures - end - - def description_separator(parent_part, child_part) - if parent_part.is_a?(Module) && child_part =~ /^(#|::|\.)/ - '' - else - ' ' - end - end - - def build_description_from(parent_description=nil, my_description=nil) - return parent_description.to_s unless my_description - separator = description_separator(parent_description, my_description) - parent_description.to_s + separator + my_description.to_s - end - - def ensure_valid_user_keys - RESERVED_KEYS.each do |key| - if user_metadata.has_key?(key) - raise <<-EOM.gsub(/^\s+\|/, '') - |#{"*"*50} - |:#{key} is not allowed - | - |RSpec reserves some hash keys for its own internal use, - |including :#{key}, which is used on: - | - | #{CallerFilter.first_non_rspec_line}. - | - |Here are all of RSpec's reserved hash keys: - | - | #{RESERVED_KEYS.join("\n ")} - |#{"*"*50} - EOM - end - end - end - end - - # @private - class ExampleHash < HashPopulator - def self.create(group_metadata, user_metadata, description, block) - example_metadata = group_metadata.dup - group_metadata = Hash.new(&ExampleGroupHash.backwards_compatibility_default_proc do |hash| - hash[:parent_example_group] - end) - group_metadata.update(example_metadata) - - example_metadata[:example_group] = group_metadata - example_metadata.delete(:parent_example_group) - - hash = new(example_metadata, user_metadata, [description].compact, block) - hash.populate - hash.metadata - end - - private - - def described_class - metadata[:example_group][:described_class] - end - - def full_description - build_description_from( - metadata[:example_group][:full_description], - metadata[:description] - ) - end - end - - # @private - class ExampleGroupHash < HashPopulator - def self.create(parent_group_metadata, user_metadata, *args, &block) - group_metadata = hash_with_backwards_compatibility_default_proc - - if parent_group_metadata - group_metadata.update(parent_group_metadata) - group_metadata[:parent_example_group] = parent_group_metadata - end - - hash = new(group_metadata, user_metadata, args, block) - hash.populate - hash.metadata - end - - def self.hash_with_backwards_compatibility_default_proc - Hash.new(&backwards_compatibility_default_proc { |hash| hash }) - end - - def self.backwards_compatibility_default_proc(&example_group_selector) - Proc.new do |hash, key| - case key - when :example_group - # We commonly get here when rspec-core is applying a previously configured - # filter rule, such as when a gem configures: - # - # RSpec.configure do |c| - # c.include MyGemHelpers, :example_group => { :file_path => /spec\/my_gem_specs/ } - # end - # - # It's confusing for a user to get a deprecation at this point in the code, so instead - # we issue a deprecation from the config APIs that take a metadata hash, and MetadataFilter - # sets this thread local to silence the warning here since it would be so confusing. - unless RSpec.thread_local_metadata[:silence_metadata_example_group_deprecations] - RSpec.deprecate("The `:example_group` key in an example group's metadata hash", - :replacement => "the example group's hash directly for the " + - "computed keys and `:parent_example_group` to access the parent " + - "example group metadata") - end - - group_hash = example_group_selector.call(hash) - LegacyExampleGroupHash.new(group_hash) if group_hash - when :example_group_block - RSpec.deprecate("`metadata[:example_group_block]`", - :replacement => "`metadata[:block]`") - hash[:block] - when :describes - RSpec.deprecate("`metadata[:describes]`", - :replacement => "`metadata[:described_class]`") - hash[:described_class] - end - end - end - - private - - def described_class - candidate = metadata[:description_args].first - return candidate unless NilClass === candidate || String === candidate - parent_group = metadata[:parent_example_group] - parent_group && parent_group[:described_class] - end - - def full_description - description = metadata[:description] - parent_example_group = metadata[:parent_example_group] - return description unless parent_example_group - - parent_description = parent_example_group[:full_description] - separator = description_separator(parent_example_group[:description_args].last, - metadata[:description_args].first) - - parent_description + separator + description - end - end - - # @private - RESERVED_KEYS = [ - :description, - :example_group, - :parent_example_group, - :execution_result, - :file_path, - :full_description, - :line_number, - :location, - :block - ] - end - - # Mixin that makes the including class imitate a hash for backwards - # compatibility. The including class should use `attr_accessor` to - # declare attributes. - # @private - module HashImitatable - def self.included(klass) - klass.extend ClassMethods - end - - def to_h - hash = extra_hash_attributes.dup - - self.class.hash_attribute_names.each do |name| - hash[name] = __send__(name) - end - - hash - end - - (Hash.public_instance_methods - Object.public_instance_methods).each do |method_name| - next if [:[], :[]=, :to_h].include?(method_name.to_sym) - - define_method(method_name) do |*args, &block| - issue_deprecation(method_name, *args) - - hash = hash_for_delegation - self.class.hash_attribute_names.each do |name| - hash.delete(name) unless instance_variable_defined?(:"@#{name}") - end - - hash.__send__(method_name, *args, &block).tap do - # apply mutations back to the object - hash.each do |name, value| - if directly_supports_attribute?(name) - set_value(name, value) - else - extra_hash_attributes[name] = value - end - end - end - end - end - - def [](key) - issue_deprecation(:[], key) - - if directly_supports_attribute?(key) - get_value(key) - else - extra_hash_attributes[key] - end - end - - def []=(key, value) - issue_deprecation(:[]=, key, value) - - if directly_supports_attribute?(key) - set_value(key, value) - else - extra_hash_attributes[key] = value - end - end - - private - - def extra_hash_attributes - @extra_hash_attributes ||= {} - end - - def directly_supports_attribute?(name) - self.class.hash_attribute_names.include?(name) - end - - def get_value(name) - __send__(name) - end - - def set_value(name, value) - __send__(:"#{name}=", value) - end - - def hash_for_delegation - to_h - end - - def issue_deprecation(method_name, *args) - # no-op by default: subclasses can override - end - - # @private - module ClassMethods - def hash_attribute_names - @hash_attribute_names ||= [] - end - - def attr_accessor(*names) - hash_attribute_names.concat(names) - super - end - end - end - - # @private - # Together with the example group metadata hash default block, - # provides backwards compatibility for the old `:example_group` - # key. In RSpec 2.x, the computed keys of a group's metadata - # were exposed from a nested subhash keyed by `[:example_group]`, and - # then the parent group's metadata was exposed by sub-subhash - # keyed by `[:example_group][:example_group]`. - # - # In RSpec 3, we reorganized this to that the computed keys are - # exposed directly of the group metadata hash (no nesting), and - # `:parent_example_group` returns the parent group's metadata. - # - # Maintaining backwards compatibility was difficult: we wanted - # `:example_group` to return an object that: - # - # * Exposes the top-level metadata keys that used to be nested - # under `:example_group`. - # * Supports mutation (rspec-rails, for example, assigns - # `metadata[:example_group][:described_class]` when you use - # anonymous controller specs) such that changes are written - # back to the top-level metadata hash. - # * Exposes the parent group metadata as `[:example_group][:example_group]`. - class LegacyExampleGroupHash - include HashImitatable - - def initialize(metadata) - @metadata = metadata - parent_group_metadata = metadata.fetch(:parent_example_group) { {} }[:example_group] - self[:example_group] = parent_group_metadata if parent_group_metadata - end - - def to_h - super.merge(@metadata) - end - - private - - def directly_supports_attribute?(name) - name != :example_group - end - - def get_value(name) - @metadata[name] - end - - def set_value(name, value) - @metadata[name] = value - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/metadata_filter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/metadata_filter.rb deleted file mode 100644 index cffc683..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/metadata_filter.rb +++ /dev/null @@ -1,95 +0,0 @@ -module RSpec - module Core - # Contains metadata filtering logic. This has been extracted from - # the metadata classes because it operates ON a metadata hash but - # does not manage any of the state in the hash. We're moving towards - # having metadata be a raw hash (not a custom subclass), so externalizing - # this filtering logic helps us move in that direction. - module MetadataFilter - extend self - - # @private - def any_apply?(filters, metadata) - filters.any? { |k, v| filter_applies?(k, v, metadata) } - end - - # @private - def all_apply?(filters, metadata) - filters.all? { |k, v| filter_applies?(k, v, metadata) } - end - - # @private - def filter_applies?(key, value, metadata) - silence_metadata_example_group_deprecations do - return filter_applies_to_any_value?(key, value, metadata) if Array === metadata[key] && !(Proc === value) - return location_filter_applies?(value, metadata) if key == :locations - return filters_apply?(key, value, metadata) if Hash === value - - return false unless metadata.has_key?(key) - - case value - when Regexp - metadata[key] =~ value - when Proc - case value.arity - when 0 then value.call - when 2 then value.call(metadata[key], metadata) - else value.call(metadata[key]) - end - else - metadata[key].to_s == value.to_s - end - end - end - - private - - def filter_applies_to_any_value?(key, value, metadata) - metadata[key].any? {|v| filter_applies?(key, v, {key => value})} - end - - def location_filter_applies?(locations, metadata) - # it ignores location filters for other files - line_number = example_group_declaration_line(locations, metadata) - line_number ? line_number_filter_applies?(line_number, metadata) : true - end - - def line_number_filter_applies?(line_numbers, metadata) - preceding_declaration_lines = line_numbers.map {|n| RSpec.world.preceding_declaration_line(n)} - !(relevant_line_numbers(metadata) & preceding_declaration_lines).empty? - end - - def relevant_line_numbers(metadata) - return [] unless metadata - [metadata[:line_number]].compact + (relevant_line_numbers(parent_of metadata)) - end - - def example_group_declaration_line(locations, metadata) - parent = parent_of(metadata) - return nil unless parent - locations[File.expand_path(parent[:file_path])] - end - - def filters_apply?(key, value, metadata) - subhash = metadata[key] - return false unless Hash === subhash || HashImitatable === subhash - value.all? { |k, v| filter_applies?(k, v, subhash) } - end - - def parent_of(metadata) - if metadata.key?(:example_group) - metadata[:example_group] - else - metadata[:parent_example_group] - end - end - - def silence_metadata_example_group_deprecations - RSpec.thread_local_metadata[:silence_metadata_example_group_deprecations] = true - yield - ensure - RSpec.thread_local_metadata.delete(:silence_metadata_example_group_deprecations) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/minitest_assertions_adapter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/minitest_assertions_adapter.rb deleted file mode 100644 index 2afa33e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/minitest_assertions_adapter.rb +++ /dev/null @@ -1,28 +0,0 @@ -begin - # Only the minitest 5.x gem includes the minitest.rb and assertions.rb files - require 'minitest' - require 'minitest/assertions' -rescue LoadError => _ignored - # We must be using Ruby Core's MiniTest or the Minitest gem 4.x - require 'minitest/unit' - Minitest = MiniTest -end - -module RSpec - module Core - # @private - module MinitestAssertionsAdapter - include ::Minitest::Assertions - - # Minitest 5.x requires this accessor to be available. See - # https://github.com/seattlerb/minitest/blob/38f0a5fcbd9c37c3f80a3eaad4ba84d3fc9947a0/lib/minitest/assertions.rb#L8 - # - # It is not required for other extension libraries, and RSpec does not - # report or make this information available to formatters. - attr_writer :assertions - def assertions - @assertions ||= 0 - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/flexmock.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/flexmock.rb deleted file mode 100644 index 6736f63..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/flexmock.rb +++ /dev/null @@ -1,29 +0,0 @@ -# Created by Jim Weirich on 2007-04-10. -# Copyright (c) 2007. All rights reserved. - -require 'flexmock/rspec' - -module RSpec - module Core - module MockingAdapters - # @private - module Flexmock - include ::FlexMock::MockContainer - - def self.framework_name; :flexmock end - - def setup_mocks_for_rspec - # No setup required - end - - def verify_mocks_for_rspec - flexmock_verify - end - - def teardown_mocks_for_rspec - flexmock_close - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/mocha.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/mocha.rb deleted file mode 100644 index f45a736..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/mocha.rb +++ /dev/null @@ -1,55 +0,0 @@ -# In order to support all versions of mocha, we have to jump through some -# hoops here. -# -# mocha >= '0.13.0': -# require 'mocha/api' is required -# require 'mocha/object' raises a LoadError b/c the file no longer exists -# mocha < '0.13.0', >= '0.9.7' -# require 'mocha/api' is required -# require 'mocha/object' is required -# mocha < '0.9.7': -# require 'mocha/api' raises a LoadError b/c the file does not yet exist -# require 'mocha/standalone' is required -# require 'mocha/object' is required -begin - require 'mocha/api' - - begin - require 'mocha/object' - rescue LoadError - # Mocha >= 0.13.0 no longer contains this file nor needs it to be loaded - end -rescue LoadError - require 'mocha/standalone' - require 'mocha/object' -end - -module RSpec - module Core - module MockingAdapters - # @private - module Mocha - def self.framework_name; :mocha end - - # Mocha::Standalone was deprecated as of Mocha 0.9.7. - begin - include ::Mocha::API - rescue NameError - include ::Mocha::Standalone - end - - def setup_mocks_for_rspec - mocha_setup - end - - def verify_mocks_for_rspec - mocha_verify - end - - def teardown_mocks_for_rspec - mocha_teardown - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/null.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/null.rb deleted file mode 100644 index 6aec488..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/null.rb +++ /dev/null @@ -1,12 +0,0 @@ -module RSpec - module Core - module MockingAdapters - # @private - module Null - def setup_mocks_for_rspec; end - def verify_mocks_for_rspec; end - def teardown_mocks_for_rspec; end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/rr.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/rr.rb deleted file mode 100644 index 92f105e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/rr.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'rr' - -RSpec.configuration.backtrace_exclusion_patterns.push(RR::Errors::BACKTRACE_IDENTIFIER) - -module RSpec - module Core - # @private - module MockingAdapters - # @private - module RR - def self.framework_name; :rr end - - include ::RR::Extensions::InstanceMethods - - def setup_mocks_for_rspec - ::RR::Space.instance.reset - end - - def verify_mocks_for_rspec - ::RR::Space.instance.verify_doubles - end - - def teardown_mocks_for_rspec - ::RR::Space.instance.reset - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/rspec.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/rspec.rb deleted file mode 100644 index cd563f0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/mocking_adapters/rspec.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'rspec/mocks' - -module RSpec - module Core - module MockingAdapters - # @private - module RSpec - include ::RSpec::Mocks::ExampleMethods - - def self.framework_name; :rspec end - - def self.configuration - ::RSpec::Mocks.configuration - end - - def setup_mocks_for_rspec - ::RSpec::Mocks.setup - end - - def verify_mocks_for_rspec - ::RSpec::Mocks.verify - end - - def teardown_mocks_for_rspec - ::RSpec::Mocks.teardown - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/notifications.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/notifications.rb deleted file mode 100644 index 66a4799..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/notifications.rb +++ /dev/null @@ -1,535 +0,0 @@ -RSpec::Support.require_rspec_core "formatters/helpers" - -module RSpec::Core - # Notifications are value objects passed to formatters to provide them - # with information about a particular event of interest. - module Notifications - - # @private - class NullColorizer - def wrap(line, _code_or_symbol) - line - end - end - - # The `StartNotification` represents a notification sent by the reporter - # when the suite is started. It contains the expected amount of examples - # to be executed, and the load time of RSpec. - # - # @attr count [Fixnum] the number counted - # @attr load_time [Float] the number of seconds taken to boot RSpec - # and load the spec files - StartNotification = Struct.new(:count, :load_time) - - # The `ExampleNotification` represents notifications sent by the reporter - # which contain information about the current (or soon to be) example. - # It is used by formatters to access information about that example. - # - # @example - # def example_started(notification) - # puts "Hey I started #{notification.example.description}" - # end - # - # @attr example [RSpec::Core::Example] the current example - ExampleNotification = Struct.new(:example) do - # @private - def self.for(example) - if example.execution_result.pending_fixed? - PendingExampleFixedNotification.new(example) - elsif example.execution_result.status == :failed - FailedExampleNotification.new(example) - else - new(example) - end - end - private_class_method :new - end - - # The `ExamplesNotification` represents notifications sent by the reporter - # which contain information about the suites examples. - # - # @example - # def stop(notification) - # puts "Hey I ran #{notification.examples.size}" - # end - # - class ExamplesNotification - - def initialize(reporter) - @reporter = reporter - end - - # @return [Array(RSpec::Core::Example)] list of examples - def examples - @reporter.examples - end - - # @return [Array(RSpec::Core::Example)] list of failed examples - def failed_examples - @reporter.failed_examples - end - - # @return [Array(RSpec::Core::Example)] list of pending examples - def pending_examples - @reporter.pending_examples - end - - # @return [Array(Rspec::Core::Notifications::ExampleNotification] - # returns examples as notifications - def notifications - @notifications ||= format(examples) - end - - # @return [Array(Rspec::Core::Notifications::FailedExampleNotification] - # returns failed examples as notifications - def failure_notifications - @failed_notifications ||= format(failed_examples) - end - - # @return [String] The list of failed examples, fully formatted in the way that - # RSpec's built-in formatters emit. - def fully_formatted_failed_examples(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - formatted = "\nFailures:\n" - - failure_notifications.each_with_index do |failure, index| - formatted << failure.fully_formatted(index.next, colorizer) - end - - formatted - end - - # @return [String] The list of pending examples, fully formatted in the way that - # RSpec's built-in formatters emit. - def fully_formatted_pending_examples(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - formatted = "\nPending:\n" - - pending_examples.each do |example| - formatted_caller = RSpec.configuration.backtrace_formatter.backtrace_line(example.location) - - formatted << - " #{colorizer.wrap(example.full_description, :pending)}\n" << - " # #{colorizer.wrap(example.execution_result.pending_message, :detail)}\n" << - " # #{colorizer.wrap(formatted_caller, :detail)}\n" - end - - formatted - end - - private - - def format(examples) - examples.map do |example| - ExampleNotification.for(example) - end - end - - end - - # The `FailedExampleNotification` extends `ExampleNotification` with - # things useful for failed specs. - # - # @example - # def example_failed(notification) - # puts "Hey I failed :(" - # puts "Here's my stack trace" - # puts notification.exception.backtrace.join("\n") - # end - # - # @attr [RSpec::Core::Example] example the current example - # @see ExampleNotification - class FailedExampleNotification < ExampleNotification - public_class_method :new - - # @return [Exception] The example failure - def exception - example.execution_result.exception - end - - # @return [String] The example description - def description - example.full_description - end - - # Returns the message generated for this failure line by line. - # - # @return [Array(String)] The example failure message - def message_lines - add_shared_group_line(failure_lines, NullColorizer) - end - - # Returns the message generated for this failure colorized line by line. - # - # @param colorizer [#wrap] An object to colorize the message_lines by - # @return [Array(String)] The example failure message colorized - def colorized_message_lines(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - add_shared_group_line(failure_lines, colorizer).map do |line| - colorizer.wrap line, RSpec.configuration.failure_color - end - end - - # Returns the failures formatted backtrace. - # - # @return [Array(String)] the examples backtrace lines - def formatted_backtrace - backtrace_formatter.format_backtrace(exception.backtrace, example.metadata) - end - - # Returns the failures colorized formatted backtrace. - # - # @param colorizer [#wrap] An object to colorize the message_lines by - # @return [Array(String)] the examples colorized backtrace lines - def colorized_formatted_backtrace(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - formatted_backtrace.map do |backtrace_info| - colorizer.wrap "# #{backtrace_info}", RSpec.configuration.detail_color - end - end - - # @return [String] The failure information fully formatted in the way that - # RSpec's built-in formatters emit. - def fully_formatted(failure_number, colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - formatted = "\n #{failure_number}) #{description}\n" - - colorized_message_lines(colorizer).each do |line| - formatted << " #{line}\n" - end - - colorized_formatted_backtrace(colorizer).each do |line| - formatted << " #{line}\n" - end - - formatted - end - - private - - def backtrace_formatter - RSpec.configuration.backtrace_formatter - end - - def exception_class_name - name = exception.class.name.to_s - name ="(anonymous error class)" if name == '' - name - end - - def failure_lines - @failure_lines ||= - begin - lines = ["Failure/Error: #{read_failed_line.strip}"] - lines << "#{exception_class_name}:" unless exception_class_name =~ /RSpec/ - exception.message.to_s.split("\n").each do |line| - lines << " #{line}" if exception.message - end - lines - end - end - - def add_shared_group_line(lines, colorizer) - unless shared_group_line == "" - lines << colorizer.wrap(shared_group_line, RSpec.configuration.default_color) - end - lines - end - - def shared_group - @shared_group ||= group_and_parent_groups.find { |group| group.metadata[:shared_group_name] } - end - - def shared_group_line - @shared_group_line ||= - if shared_group - "Shared Example Group: \"#{shared_group.metadata[:shared_group_name]}\"" + - " called from #{backtrace_formatter.backtrace_line(shared_group.location)}" - else - "" - end - end - - def group_and_parent_groups - example.example_group.parent_groups + [example.example_group] - end - - def read_failed_line - unless matching_line = find_failed_line - return "Unable to find matching line from backtrace" - end - - file_path, line_number = matching_line.match(/(.+?):(\d+)(|:\d+)/)[1..2] - - if File.exist?(file_path) - File.readlines(file_path)[line_number.to_i - 1] || - "Unable to find matching line in #{file_path}" - else - "Unable to find #{file_path} to read failed line" - end - rescue SecurityError - "Unable to read failed line" - end - - def find_failed_line - path = File.expand_path(example.file_path) - exception.backtrace.detect do |line| - match = line.match(/(.+?):(\d+)(|:\d+)/) - match && match[1].downcase == path.downcase - end - end - end - - # The `PendingExampleFixedNotification` extends `ExampleNotification` with - # things useful for specs that pass when they are expected to fail. - # - # @attr [RSpec::Core::Example] example the current example - # @see ExampleNotification - class PendingExampleFixedNotification < FailedExampleNotification - public_class_method :new - - # Returns the examples description - # - # @return [String] The example description - def description - "#{example.full_description} FIXED" - end - - # Returns the message generated for this failure line by line. - # - # @return [Array(String)] The example failure message - def message_lines - ["Expected pending '#{example.execution_result.pending_message}' to fail. No Error was raised."] - end - - # Returns the message generated for this failure colorized line by line. - # - # @param colorizer [#wrap] An object to colorize the message_lines by - # @return [Array(String)] The example failure message colorized - def colorized_message_lines(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - message_lines.map { |line| colorizer.wrap(line, RSpec.configuration.fixed_color) } - end - end - - # The `GroupNotification` represents notifications sent by the reporter which - # contain information about the currently running (or soon to be) example group - # It is used by formatters to access information about that group. - # - # @example - # def example_group_started(notification) - # puts "Hey I started #{notification.group.description}" - # end - # @attr group [RSpec::Core::ExampleGroup] the current group - GroupNotification = Struct.new(:group) - - # The `MessageNotification` encapsulates generic messages that the reporter - # sends to formatters. - # - # @attr message [String] the message - MessageNotification = Struct.new(:message) - - # The `SeedNotification` holds the seed used to randomize examples and - # wether that seed has been used or not. - # - # @attr seed [Fixnum] the seed used to randomize ordering - # @attr used [Boolean] wether the seed has been used or not - SeedNotification = Struct.new(:seed, :used) do - # @api - # @return [Boolean] has the seed been used? - def seed_used? - !!used - end - private :used - - # @return [String] The seed information fully formatted in the way that - # RSpec's built-in formatters emit. - def fully_formatted - "\nRandomized with seed #{seed}\n\n" - end - end - - # The `SummaryNotification` holds information about the results of running - # a test suite. It is used by formatters to provide information at the end - # of the test run. - # - # @attr duration [Float] the time taken (in seconds) to run the suite - # @attr examples [Array(RSpec::Core::Example)] the examples run - # @attr failed_examples [Array(RSpec::Core::Example)] the failed examples - # @attr pending_examples [Array(RSpec::Core::Example)] the pending examples - # @attr load_time [Float] the number of seconds taken to boot RSpec - # and load the spec files - SummaryNotification = Struct.new(:duration, :examples, :failed_examples, :pending_examples, :load_time) do - - # @api - # @return [Fixnum] the number of examples run - def example_count - @example_count ||= examples.size - end - - # @api - # @return [Fixnum] the number of failed examples - def failure_count - @failure_count ||= failed_examples.size - end - - # @api - # @return [Fixnum] the number of pending examples - def pending_count - @pending_count ||= pending_examples.size - end - - # @api - # @return [String] A line summarising the result totals of the spec run. - def totals_line - summary = Formatters::Helpers.pluralize(example_count, "example") - summary << ", " << Formatters::Helpers.pluralize(failure_count, "failure") - summary << ", #{pending_count} pending" if pending_count > 0 - summary - end - - # @api public - # - # Wraps the results line with colors based on the configured - # colors for failure, pending, and success. Defaults to red, - # yellow, green accordingly. - # - # @param colorizer [#wrap] An object which supports wrapping text with - # specific colors. - # @return [String] A colorized results line. - def colorized_totals_line(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - if failure_count > 0 - colorizer.wrap(totals_line, RSpec.configuration.failure_color) - elsif pending_count > 0 - colorizer.wrap(totals_line, RSpec.configuration.pending_color) - else - colorizer.wrap(totals_line, RSpec.configuration.success_color) - end - end - - # @api public - # - # Formats failures into a rerunable command format. - # - # @param colorizer [#wrap] An object which supports wrapping text with - # specific colors. - # @return [String] A colorized summary line. - def colorized_rerun_commands(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - "\nFailed examples:\n\n" + - failed_examples.map do |example| - colorizer.wrap("rspec #{example.location}", RSpec.configuration.failure_color) + " " + - colorizer.wrap("# #{example.full_description}", RSpec.configuration.detail_color) - end.join("\n") - end - - # @return [String] a formatted version of the time it took to run the suite - def formatted_duration - Formatters::Helpers.format_duration(duration) - end - - # @return [String] a formatted version of the time it took to boot RSpec and - # load the spec files - def formatted_load_time - Formatters::Helpers.format_duration(load_time) - end - - # @return [String] The summary information fully formatted in the way that - # RSpec's built-in formatters emit. - def fully_formatted(colorizer = ::RSpec::Core::Formatters::ConsoleCodes) - formatted = "\nFinished in #{formatted_duration} " \ - "(files took #{formatted_load_time} to load)\n" \ - "#{colorized_totals_line(colorizer)}\n" - - unless failed_examples.empty? - formatted << colorized_rerun_commands(colorizer) << "\n" - end - - formatted - end - end - - # The `ProfileNotification` holds information about the results of running - # a test suite when profiling is enabled. It is used by formatters to provide - # information at the end of the test run for profiling information. - # - # @attr duration [Float] the time taken (in seconds) to run the suite - # @attr examples [Array(RSpec::Core::Example)] the examples run - # @attr number_of_examples [Fixnum] the number of examples to profile - ProfileNotification = Struct.new(:duration, :examples, :number_of_examples) do - - # @return [Array(RSpec::Core::Example)] the slowest examples - def slowest_examples - @slowest_examples ||= - examples.sort_by do |example| - -example.execution_result.run_time - end.first(number_of_examples) - end - - # @return [Float] the time taken (in seconds) to run the slowest examples - def slow_duration - @slow_duration ||= - slowest_examples.inject(0.0) do |i, e| - i + e.execution_result.run_time - end - end - - # @return [String] the percentage of total time taken - def percentage - @percentage ||= - begin - time_taken = slow_duration / duration - '%.1f' % ((time_taken.nan? ? 0.0 : time_taken) * 100) - end - end - - # @return [Array(RSpec::Core::Example)] the slowest example groups - def slowest_groups - @slowest_groups ||= calculate_slowest_groups - end - - private - - def calculate_slowest_groups - example_groups = {} - - examples.each do |example| - location = example.example_group.parent_groups.last.metadata[:location] - - location_hash = example_groups[location] ||= Hash.new(0) - location_hash[:total_time] += example.execution_result.run_time - location_hash[:count] += 1 - unless location_hash.has_key?(:description) - location_hash[:description] = example.example_group.top_level_description - end - end - - # stop if we've only one example group - return {} if example_groups.keys.length <= 1 - - example_groups.each_value do |hash| - hash[:average] = hash[:total_time].to_f / hash[:count] - end - - example_groups.sort_by { |_, hash| -hash[:average] }.first(number_of_examples) - end - end - - # The `DeprecationNotification` is issued by the reporter when a deprecated - # part of RSpec is encountered. It represents information about the deprecated - # call site. - # - # @attr message [String] A custom message about the deprecation - # @attr deprecated [String] A custom message about the deprecation (alias of message) - # @attr replacement [String] An optional replacement for the deprecation - # @attr call_site [String] An optional call site from which the deprecation was issued - DeprecationNotification = Struct.new(:deprecated, :message, :replacement, :call_site) do - private_class_method :new - - # @api - # Convenience way to initialize the notification - def self.from_hash(data) - new data[:deprecated], data[:message], data[:replacement], data[:call_site] - end - end - - # `NullNotification` represents a placeholder value for notifications that - # currently require no information, but we may wish to extend in future. - class NullNotification - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/option_parser.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/option_parser.rb deleted file mode 100644 index 03e91fe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/option_parser.rb +++ /dev/null @@ -1,218 +0,0 @@ -# http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html -require 'optparse' - -module RSpec::Core - # @private - class Parser - def self.parse(args) - new.parse(args) - end - - def parse(args) - return {} if args.empty? - - options = args.delete('--tty') ? {:tty => true} : {} - begin - parser(options).parse!(args) - rescue OptionParser::InvalidOption => e - abort "#{e.message}\n\nPlease use --help for a listing of valid options" - end - - options - end - - def parser(options) - OptionParser.new do |parser| - parser.banner = "Usage: rspec [options] [files or directories]\n\n" - - parser.on('-I PATH', 'Specify PATH to add to $LOAD_PATH (may be used more than once).') do |dir| - options[:libs] ||= [] - options[:libs] << dir - end - - parser.on('-r', '--require PATH', 'Require a file.') do |path| - options[:requires] ||= [] - options[:requires] << path - end - - parser.on('-O', '--options PATH', 'Specify the path to a custom options file.') do |path| - options[:custom_options_file] = path - end - - parser.on('--order TYPE[:SEED]', 'Run examples by the specified order type.', - ' [defined] examples and groups are run in the order they are defined', - ' [rand] randomize the order of groups and examples', - ' [random] alias for rand', - ' [random:SEED] e.g. --order random:123') do |o| - options[:order] = o - end - - parser.on('--seed SEED', Integer, 'Equivalent of --order rand:SEED.') do |seed| - options[:order] = "rand:#{seed}" - end - - parser.on('--fail-fast', 'Abort the run on first failure.') do |o| - options[:fail_fast] = true - end - - parser.on('--no-fail-fast', 'Do not abort the run on first failure.') do |o| - options[:fail_fast] = false - end - - parser.on('--failure-exit-code CODE', Integer, 'Override the exit code used when there are failing specs.') do |code| - options[:failure_exit_code] = code - end - - parser.on('--dry-run', 'Print the formatter output of your suite without', - ' running any examples or hooks') do |o| - options[:dry_run] = true - end - - parser.on('-X', '--[no-]drb', 'Run examples via DRb.') do |o| - options[:drb] = o - end - - parser.on('--drb-port PORT', 'Port to connect to the DRb server.') do |o| - options[:drb_port] = o.to_i - end - - parser.on('--init', 'Initialize your project with RSpec.') do |cmd| - RSpec::Support.require_rspec_core "project_initializer" - ProjectInitializer.new.run - exit - end - - parser.separator("\n **** Output ****\n\n") - - parser.on('-f', '--format FORMATTER', 'Choose a formatter.', - ' [p]rogress (default - dots)', - ' [d]ocumentation (group and example names)', - ' [h]tml', - ' [j]son', - ' custom formatter class name') do |o| - options[:formatters] ||= [] - options[:formatters] << [o] - end - - parser.on('-o', '--out FILE', - 'Write output to a file instead of $stdout. This option applies', - ' to the previously specified --format, or the default format', - ' if no format is specified.' - ) do |o| - options[:formatters] ||= [['progress']] - options[:formatters].last << o - end - - parser.on('--deprecation-out FILE', 'Write deprecation warnings to a file instead of $stderr.') do |file| - options[:deprecation_stream] = file - end - - parser.on('-b', '--backtrace', 'Enable full backtrace.') do |o| - options[:full_backtrace] = true - end - - parser.on('-c', '--[no-]color', '--[no-]colour', 'Enable color in the output.') do |o| - options[:color] = o - end - - parser.on('-p', '--[no-]profile [COUNT]', 'Enable profiling of examples and list the slowest examples (default: 10).') do |argument| - options[:profile_examples] = if argument.nil? - true - elsif argument == false - false - else - begin - Integer(argument) - rescue ArgumentError - RSpec.warning "Non integer specified as profile count, seperate " + - "your path from options with -- e.g. " + - "`rspec --profile -- #{argument}`", - :call_site => nil - true - end - end - end - - parser.on('-w', '--warnings', 'Enable ruby warnings') do - $VERBOSE = true - end - - parser.separator <<-FILTERING - - **** Filtering/tags **** - - In addition to the following options for selecting specific files, groups, - or examples, you can select a single example by appending the line number to - the filename: - - rspec path/to/a_spec.rb:37 - -FILTERING - - parser.on('-P', '--pattern PATTERN', 'Load files matching pattern (default: "spec/**/*_spec.rb").') do |o| - options[:pattern] = o - end - - parser.on('-e', '--example STRING', "Run examples whose full nested names include STRING (may be", - " used more than once)") do |o| - (options[:full_description] ||= []) << Regexp.compile(Regexp.escape(o)) - end - - parser.on('-t', '--tag TAG[:VALUE]', - 'Run examples with the specified tag, or exclude examples', - 'by adding ~ before the tag.', - ' - e.g. ~slow', - ' - TAG is always converted to a symbol') do |tag| - filter_type = tag =~ /^~/ ? :exclusion_filter : :inclusion_filter - - name,value = tag.gsub(/^(~@|~|@)/, '').split(':',2) - name = name.to_sym - - options[filter_type] ||= {} - options[filter_type][name] = case value - when nil then true # The default value for tags is true - when 'true' then true - when 'false' then false - when 'nil' then nil - when /^:/ then value[1..-1].to_sym - when /^\d+$/ then Integer(value) - when /^\d+.\d+$/ then Float(value) - else - value - end - end - - parser.on('--default-path PATH', 'Set the default path where RSpec looks for examples (can', - ' be a path to a file or a directory).') do |path| - options[:default_path] = path - end - - parser.separator("\n **** Utility ****\n\n") - - parser.on('-v', '--version', 'Display the version.') do - puts RSpec::Core::Version::STRING - exit - end - - # these options would otherwise be confusing to users, so we forcibly prevent them from executing - # --I is too similar to -I - # -d was a shorthand for --debugger, which is removed, but now would trigger --default-path - invalid_options = %w[-d --I] - - parser.on_tail('-h', '--help', "You're looking at it.") do - # removing the blank invalid options from the output - puts parser.to_s.gsub(/^\s+(#{invalid_options.join('|')})\s*$\n/,'') - exit - end - - # this prevents usage of the invalid_options - invalid_options.each do |option| - parser.on(option) do - raise OptionParser::InvalidOption.new - end - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/ordering.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/ordering.rb deleted file mode 100644 index f0972f1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/ordering.rb +++ /dev/null @@ -1,156 +0,0 @@ -module RSpec - module Core - if defined?(::Random) - # @private - RandomNumberGenerator = ::Random - else - RSpec::Support.require_rspec_core "backport_random" - # @private - RandomNumberGenerator = RSpec::Core::Backports::Random - end - - # @private - module Ordering - # @private - # The default global ordering (defined order). - class Identity - def order(items) - items - end - end - - # @private - # Orders items randomly. - class Random - def initialize(configuration) - @configuration = configuration - @used = false - end - - def used? - @used - end - - def order(items) - @used = true - rng = RandomNumberGenerator.new(@configuration.seed) - shuffle items, rng - end - - if RUBY_VERSION > '1.9.3' - def shuffle(list, rng) - list.shuffle(:random => rng) - end - else - def shuffle(list, rng) - shuffled = list.dup - shuffled.size.times do |i| - j = i + rng.rand(shuffled.size - i) - next if i == j - shuffled[i], shuffled[j] = shuffled[j], shuffled[i] - end - - shuffled - end - end - end - - # @private - # Orders items based on a custom block. - class Custom - def initialize(callable) - @callable = callable - end - - def order(list) - @callable.call(list) - end - end - - # @private - # Stores the different ordering strategies. - class Registry - def initialize(configuration) - @configuration = configuration - @strategies = {} - - register(:random, Random.new(configuration)) - - identity = Identity.new - register(:defined, identity) - - # The default global ordering is --defined. - register(:global, identity) - end - - def fetch(name, &fallback) - @strategies.fetch(name, &fallback) - end - - def register(sym, strategy) - @strategies[sym] = strategy - end - - def used_random_seed? - @strategies[:random].used? - end - end - - # @private - # Manages ordering configuration. - # - # @note This is not intended to be used externally. Use - # the APIs provided by `RSpec::Core::Configuration` instead. - class ConfigurationManager - attr_reader :seed, :ordering_registry - - def initialize - @ordering_registry = Registry.new(self) - @seed = rand(0xFFFF) - @seed_forced = false - @order_forced = false - end - - def seed_used? - ordering_registry.used_random_seed? - end - - def seed=(seed) - return if @seed_forced - register_ordering(:global, ordering_registry.fetch(:random)) - @seed = seed.to_i - end - - def order=(type) - order, seed = type.to_s.split(':') - @seed = seed = seed.to_i if seed - - ordering_name = if order.include?('rand') - :random - elsif order == 'defined' - :defined - end - - register_ordering(:global, ordering_registry.fetch(ordering_name)) if ordering_name - end - - def force(hash) - if hash.has_key?(:seed) - self.seed = hash[:seed] - @seed_forced = true - @order_forced = true - elsif hash.has_key?(:order) - self.order = hash[:order] - @order_forced = true - end - end - - def register_ordering(name, strategy = Custom.new(Proc.new { |l| yield l })) - return if @order_forced && name == :global - ordering_registry.register(name, strategy) - end - end - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/pending.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/pending.rb deleted file mode 100644 index cb12794..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/pending.rb +++ /dev/null @@ -1,165 +0,0 @@ -module RSpec - module Core - # Provides methods to mark examples as pending. These methods are available to be - # called from within any example or hook. - module Pending - # Raised in the middle of an example to indicate that it should be marked as skipped. - class SkipDeclaredInExample < StandardError - attr_reader :argument - - def initialize(argument) - @argument = argument - end - end - - # If Test::Unit is loaded, we'll use its error as baseclass, so that Test::Unit - # will report unmet RSpec expectations as failures rather than errors. - begin - class PendingExampleFixedError < Test::Unit::AssertionFailedError; end - rescue - class PendingExampleFixedError < StandardError; end - end - - # @private - NO_REASON_GIVEN = 'No reason given' - - # @private - NOT_YET_IMPLEMENTED = 'Not yet implemented' - - # @overload pending() - # @overload pending(message) - # - # Marks an example as pending. The rest of the example will still be - # executed, and if it passes the example will fail to indicate that the - # pending can be removed. - # - # @param message [String] optional message to add to the summary report. - # - # @example - # describe "an example" do - # # reported as "Pending: no reason given" - # it "is pending with no message" do - # pending - # raise "broken" - # end - # - # # reported as "Pending: something else getting finished" - # it "is pending with a custom message" do - # pending("something else getting finished") - # raise "broken" - # end - # end - # - # @note `before(:example)` hooks are eval'd when you use the `pending` - # method within an example. If you want to declare an example `pending` - # and bypass the `before` hooks as well, you can pass `:pending => true` - # to the `it` method: - # - # it "does something", :pending => true do - # # ... - # end - # - # or pass `:pending => "something else getting finished"` to add a - # message to the summary report: - # - # it "does something", :pending => "something else getting finished" do - # # ... - # end - def pending(message=nil) - current_example = RSpec.current_example - - if block_given? - raise ArgumentError, <<-EOS.gsub(/^\s+\|/, '') - |The semantics of `RSpec::Core::Pending#pending` have changed in - |RSpec 3. In RSpec 2.x, it caused the example to be skipped. In - |RSpec 3, the rest of the example is still run but is expected to - |fail, and will be marked as a failure (rather than as pending) if - |the example passes. - | - |Passing a block within an example is now deprecated. Marking the - |example as pending provides the same behavior in RSpec 3 which was - |provided only by the block in RSpec 2.x. - | - |Move the code in the block provided to `pending` into the rest of - |the example body. - | - |Called from #{CallerFilter.first_non_rspec_line}. - | - EOS - elsif current_example - Pending.mark_pending! current_example, message - else - raise "`pending` may not be used outside of examples, such as in " + - "before(:context). Maybe you want `skip`?" - end - end - - # @overload skip() - # @overload skip(message) - # - # Marks an example as pending and skips execution. - # - # @param message [String] optional message to add to the summary report. - # - # @example - # describe "an example" do - # # reported as "Pending: no reason given" - # it "is skipped with no message" do - # skip - # end - # - # # reported as "Pending: something else getting finished" - # it "is skipped with a custom message" do - # skip "something else getting finished" - # end - # end - def skip(message=nil) - current_example = RSpec.current_example - - if current_example - Pending.mark_skipped! current_example, message - end - - raise SkipDeclaredInExample.new(message) - end - - # @private - # - # Mark example as skipped - # - # @param example [RSpec::Core::Example] the example to mark as skipped - # @param message_or_bool [Boolean, String] the message to use, or true - def self.mark_skipped!(example, message_or_bool) - Pending.mark_pending! example, message_or_bool - example.metadata[:skip] = true - end - - # @private - # - # Mark example as pending - # - # @param example [RSpec::Core::Example] the example to mark as pending - # @param message_or_bool [Boolean, String] the message to use, or true - def self.mark_pending!(example, message_or_bool) - message = if !message_or_bool || !(String === message_or_bool) - NO_REASON_GIVEN - else - message_or_bool - end - - example.metadata[:pending] = true - example.execution_result.pending_message = message - example.execution_result.pending_fixed = false - end - - # @private - # - # Mark example as fixed - # - # @param example [RSpec::Core::Example] the example to mark as fixed - def self.mark_fixed!(example) - example.execution_result.pending_fixed = true - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer.rb deleted file mode 100644 index bb80653..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer.rb +++ /dev/null @@ -1,46 +0,0 @@ -module RSpec - module Core - # @private - # Generates conventional files for an rspec project - class ProjectInitializer - attr_reader :destination, :stream, :template_path - - DOT_RSPEC_FILE = '.rspec' - SPEC_HELPER_FILE = 'spec/spec_helper.rb' - - def initialize(opts = {}) - @destination = opts.fetch(:destination, Dir.getwd) - @stream = opts.fetch(:report_stream, $stdout) - @template_path = opts.fetch(:template_path) do - File.expand_path("../project_initializer", __FILE__) - end - end - - def run - copy_template DOT_RSPEC_FILE - copy_template SPEC_HELPER_FILE - end - - private - - def copy_template(file) - destination_file = File.join(destination, file) - return report_exists(file) if File.exist?(destination_file) - - report_creating(file) - FileUtils.mkdir_p(File.dirname(destination_file)) - File.open(destination_file, 'w') do |f| - f.write File.read(File.join(template_path, file)) - end - end - - def report_exists(file) - stream.puts " exist #{file}" - end - - def report_creating(file) - stream.puts " create #{file}" - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer/.rspec b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer/.rspec deleted file mode 100644 index 0d786ba..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer/.rspec +++ /dev/null @@ -1,3 +0,0 @@ ---color ---warnings ---require spec_helper diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer/spec/spec_helper.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer/spec/spec_helper.rb deleted file mode 100644 index 89642b2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/project_initializer/spec/spec_helper.rb +++ /dev/null @@ -1,78 +0,0 @@ -# This file was generated by the `rspec --init` command. Conventionally, all -# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. -# The generated `.rspec` file contains `--require spec_helper` which will cause this -# file to always be loaded, without a need to explicitly require it in any files. -# -# Given that it is always loaded, you are encouraged to keep this file as -# light-weight as possible. Requiring heavyweight dependencies from this file -# will add to the boot time of your test suite on EVERY test run, even for an -# individual file that may not need all of that loaded. Instead, make a -# separate helper file that requires this one and then use it only in the specs -# that actually need it. -# -# The `.rspec` file also contains a few flags that are not defaults but that -# users commonly want. -# -# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration -RSpec.configure do |config| -# The settings below are suggested to provide a good initial experience -# with RSpec, but feel free to customize to your heart's content. -=begin - # These two settings work together to allow you to limit a spec run - # to individual examples or groups you care about by tagging them with - # `:focus` metadata. When nothing is tagged with `:focus`, all examples - # get run. - config.filter_run :focus - config.run_all_when_everything_filtered = true - - # Many RSpec users commonly either run the entire suite or an individual - # file, and it's useful to allow more verbose output when running an - # individual spec file. - if config.files_to_run.one? - # Use the documentation formatter for detailed output, - # unless a formatter has already been configured - # (e.g. via a command-line flag). - config.default_formatter = 'doc' - end - - # Print the 10 slowest examples and example groups at the - # end of the spec run, to help surface which specs are running - # particularly slow. - config.profile_examples = 10 - - # Run specs in random order to surface order dependencies. If you find an - # order dependency and want to debug it, you can fix the order by providing - # the seed, which is printed after each run. - # --seed 1234 - config.order = :random - - # Seed global randomization in this process using the `--seed` CLI option. - # Setting this allows you to use `--seed` to deterministically reproduce - # test failures related to randomization by passing the same `--seed` value - # as the one that triggered the failure. - Kernel.srand config.seed - - # rspec-expectations config goes here. You can use an alternate - # assertion/expectation library such as wrong or the stdlib/minitest - # assertions if you prefer. - config.expect_with :rspec do |expectations| - # Enable only the newer, non-monkey-patching expect syntax. - # For more details, see: - # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax - expectations.syntax = :expect - end - - # rspec-mocks config goes here. You can use an alternate test double - # library (such as bogus or mocha) by changing the `mock_with` option here. - config.mock_with :rspec do |mocks| - # Enable only the newer, non-monkey-patching expect syntax. - # For more details, see: - # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ - mocks.syntax = :expect - - # Prevents you from mocking or stubbing a method that does not exist on - # a real object. This is generally recommended. - mocks.verify_partial_doubles = true - end -=end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/rake_task.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/rake_task.rb deleted file mode 100644 index 224cdf6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/rake_task.rb +++ /dev/null @@ -1,144 +0,0 @@ -require 'rspec/support' -require 'rspec/core/version' -RSpec::Support.require_rspec_support "warnings" - -require 'rake' -require 'rake/tasklib' -require 'shellwords' - -module RSpec - module Core - # Rspec rake task - # - # @see Rakefile - class RakeTask < ::Rake::TaskLib - include ::Rake::DSL if defined?(::Rake::DSL) - - # Default path to the rspec executable - DEFAULT_RSPEC_PATH = File.expand_path('../../../../exe/rspec', __FILE__) - - # Default pattern for spec files. - DEFAULT_PATTERN = './spec{,/*/**}/*_spec.rb' - - # Name of task. - # - # default: - # :spec - attr_accessor :name - - # Glob pattern to match files. - # - # default: - # 'spec/**/*_spec.rb' - attr_accessor :pattern - - # Whether or not to fail Rake when an error occurs (typically when examples fail). - # - # default: - # true - attr_accessor :fail_on_error - - # A message to print to stderr when there are failures. - attr_accessor :failure_message - - # Use verbose output. If this is set to true, the task will print the - # executed spec command to stdout. - # - # default: - # true - attr_accessor :verbose - - # Command line options to pass to ruby. - # - # default: - # nil - attr_accessor :ruby_opts - - # Path to rspec - # - # default: - # 'rspec' - attr_accessor :rspec_path - - # Command line options to pass to rspec. - # - # default: - # nil - attr_accessor :rspec_opts - - def initialize(*args, &task_block) - @name = args.shift || :spec - @ruby_opts = nil - @rspec_opts = nil - @verbose = true - @fail_on_error = true - @rspec_path = DEFAULT_RSPEC_PATH - @pattern = DEFAULT_PATTERN - - define(args, &task_block) - end - - # @private - def run_task(verbose) - command = spec_command - - begin - puts command if verbose - success = system(command) - rescue - puts failure_message if failure_message - end - if fail_on_error && !success - $stderr.puts "#{command} failed" - exit $?.exitstatus - end - end - - private - - # @private - def define(args, &task_block) - desc "Run RSpec code examples" unless ::Rake.application.last_comment - - task name, *args do |_, task_args| - RakeFileUtils.__send__(:verbose, verbose) do - task_block.call(*[self, task_args].slice(0, task_block.arity)) if task_block - run_task verbose - end - end - end - - def files_to_run - if ENV['SPEC'] - FileList[ ENV['SPEC'] ].sort - else - FileList[ pattern ].sort.map(&:shellescape) - end - end - - def spec_command - cmd_parts = [] - cmd_parts << RUBY - cmd_parts << ruby_opts - cmd_parts << rspec_load_path - cmd_parts << "-S" << rspec_path - cmd_parts << files_to_run - cmd_parts << rspec_opts - cmd_parts.flatten.reject(&blank).join(" ") - end - - def blank - lambda {|s| s.nil? || s == ""} - end - - def rspec_load_path - @rspec_load_path ||= begin - core_and_support = $LOAD_PATH.grep \ - %r{#{File::SEPARATOR}rspec-(core|support)[^#{File::SEPARATOR}]*#{File::SEPARATOR}lib} - - "-I#{core_and_support.map(&:shellescape).join(File::PATH_SEPARATOR)}" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/reporter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/reporter.rb deleted file mode 100644 index c4366ea..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/reporter.rb +++ /dev/null @@ -1,152 +0,0 @@ -module RSpec::Core - # A reporter will send notifications to listeners, usually formatters for the - # spec suite run. - class Reporter - - def initialize(configuration) - @configuration = configuration - @listeners = Hash.new { |h,k| h[k] = Set.new } - @examples = [] - @failed_examples = [] - @pending_examples = [] - @duration = @start = @load_time = nil - end - - # @private - attr_reader :examples, :failed_examples, :pending_examples - - # Registers a listener to a list of notifications. The reporter will send notification of - # events to all registered listeners - # - # @param listener [Object] An obect that wishes to be notified of reporter events - # @param notifications [Array] Array of symbols represents the events a listener wishes to subscribe too - def register_listener(listener, *notifications) - notifications.each do |notification| - @listeners[notification.to_sym] << listener - end - true - end - - # @private - def registered_listeners(notification) - @listeners[notification].to_a - end - - # @api - # @overload report(count, &block) - # @overload report(count, &block) - # @param expected_example_count [Integer] the number of examples being run - # @yield [Block] block yields itself for further reporting. - # - # Initializes the report run and yields itself for further reporting. The - # block is required, so that the reporter can manage cleaning up after the - # run. - # - # @example - # - # reporter.report(group.examples.size) do |r| - # example_groups.map {|g| g.run(r) } - # end - # - def report(expected_example_count) - start(expected_example_count) - begin - yield self - ensure - finish - end - end - - # @private - def start(expected_example_count, time = RSpec::Core::Time.now) - @start = time - @load_time = (@start - @configuration.start_time).to_f - notify :start, Notifications::StartNotification.new(expected_example_count, @load_time) - end - - # @private - def message(message) - notify :message, Notifications::MessageNotification.new(message) - end - - # @private - def example_group_started(group) - notify :example_group_started, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty? - end - - # @private - def example_group_finished(group) - notify :example_group_finished, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty? - end - - # @private - def example_started(example) - @examples << example - notify :example_started, Notifications::ExampleNotification.for(example) - end - - # @private - def example_passed(example) - notify :example_passed, Notifications::ExampleNotification.for(example) - end - - # @private - def example_failed(example) - @failed_examples << example - notify :example_failed, Notifications::ExampleNotification.for(example) - end - - # @private - def example_pending(example) - @pending_examples << example - notify :example_pending, Notifications::ExampleNotification.for(example) - end - - # @private - def deprecation(hash) - notify :deprecation, Notifications::DeprecationNotification.from_hash(hash) - end - - # @private - def finish - begin - stop - notify :start_dump, Notifications::NullNotification - notify :dump_pending, Notifications::ExamplesNotification.new(self) - notify :dump_failures, Notifications::ExamplesNotification.new(self) - notify :deprecation_summary, Notifications::NullNotification - notify :dump_summary, Notifications::SummaryNotification.new(@duration, @examples, @failed_examples, @pending_examples, @load_time) - unless mute_profile_output? - notify :dump_profile, Notifications::ProfileNotification.new(@duration, @examples, @configuration.profile_examples) - end - notify :seed, Notifications::SeedNotification.new(@configuration.seed, seed_used?) - ensure - notify :close, Notifications::NullNotification - end - end - - # @private - def stop - @duration = (RSpec::Core::Time.now - @start).to_f if @start - notify :stop, Notifications::ExamplesNotification.new(self) - end - - # @private - def notify(event, notification) - registered_listeners(event).each do |formatter| - formatter.__send__(event, notification) - end - end - - private - - def mute_profile_output? - # Don't print out profiled info if there are failures and `--fail-fast` is used, it just clutters the output - !@configuration.profile_examples? || (@configuration.fail_fast? && @failed_examples.size > 0) - end - - def seed_used? - @configuration.seed && @configuration.seed_used? - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/ruby_project.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/ruby_project.rb deleted file mode 100644 index ee3e6a3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/ruby_project.rb +++ /dev/null @@ -1,45 +0,0 @@ -# This is borrowed (slightly modified) from Scott Taylor's -# project_path project: -# http://github.com/smtlaissezfaire/project_path - -require 'pathname' - -module RSpec - module Core - # @private - module RubyProject - def add_to_load_path(*dirs) - dirs.map {|dir| add_dir_to_load_path(File.join(root, dir))} - end - - def add_dir_to_load_path(dir) - $LOAD_PATH.unshift(dir) unless $LOAD_PATH.include?(dir) - end - - def root - @project_root ||= determine_root - end - - def determine_root - find_first_parent_containing('spec') || '.' - end - - def find_first_parent_containing(dir) - ascend_until {|path| File.exist?(File.join(path, dir))} - end - - def ascend_until - Pathname(File.expand_path('.')).ascend do |path| - return path if yield(path) - end - end - - module_function :add_to_load_path - module_function :add_dir_to_load_path - module_function :root - module_function :determine_root - module_function :find_first_parent_containing - module_function :ascend_until - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/runner.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/runner.rb deleted file mode 100644 index 5c452fd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/runner.rb +++ /dev/null @@ -1,161 +0,0 @@ -module RSpec - module Core - # Provides the main entry point to run a suite of RSpec examples. - class Runner - - # Register an `at_exit` hook that runs the suite when the process exits. - # - # @note This is not generally needed. The `rspec` command takes care - # of running examples for you without involving an `at_exit` - # hook. This is only needed if you are running specs using - # the `ruby` command, and even then, the normal way to invoke - # this is by requiring `rspec/autorun`. - def self.autorun - if autorun_disabled? - RSpec.deprecate("Requiring `rspec/autorun` when running RSpec via the `rspec` command") - return - elsif installed_at_exit? || running_in_drb? - return - end - - at_exit do - # Don't bother running any specs and just let the program terminate - # if we got here due to an unrescued exception (anything other than - # SystemExit, which is raised when somebody calls Kernel#exit). - next unless $!.nil? || $!.kind_of?(SystemExit) - - # We got here because either the end of the program was reached or - # somebody called Kernel#exit. Run the specs and then override any - # existing exit status with RSpec's exit status if any specs failed. - invoke - end - @installed_at_exit = true - end - - # Runs the suite of specs and exits the process with an appropriate exit code. - def self.invoke - disable_autorun! - status = run(ARGV, $stderr, $stdout).to_i - exit(status) if status != 0 - end - - # Run a suite of RSpec examples. Does not exit. - # - # This is used internally by RSpec to run a suite, but is available - # for use by any other automation tool. - # - # If you want to run this multiple times in the same process, and you - # want files like `spec_helper.rb` to be reloaded, be sure to load `load` - # instead of `require`. - # - # @param args [Array] command-line-supported arguments - # @param err [IO] error stream - # @param out [IO] output stream - # @return [Fixnum] exit status code. 0 if all specs passed, - # or the configured failure exit code (1 by default) if specs - # failed. - def self.run(args, err=$stderr, out=$stdout) - trap_interrupt - options = ConfigurationOptions.new(args) - - if options.options[:drb] - require 'rspec/core/drb' - begin - DRbRunner.new(options).run(err, out) - rescue DRb::DRbConnError - err.puts "No DRb server is running. Running in local process instead ..." - new(options).run(err, out) - end - else - new(options).run(err, out) - end - end - - def initialize(options, configuration=RSpec.configuration, world=RSpec.world) - @options = options - @configuration = configuration - @world = world - end - - # Configures and runs a spec suite. - # - # @param err [IO] error stream - # @param out [IO] output stream - def run(err, out) - setup(err, out) - run_specs(@world.ordered_example_groups) - end - - # Wires together the various configuration objects and state holders. - # - # @param err [IO] error stream - # @param out [IO] output stream - def setup(err, out) - @configuration.error_stream = err - @configuration.output_stream = out if @configuration.output_stream == $stdout - @options.configure(@configuration) - @configuration.load_spec_files - @world.announce_filters - end - - # Runs the provided example groups. - # - # @param example_groups [Array] groups to run - # @return [Fixnum] exit status code. 0 if all specs passed, - # or the configured failure exit code (1 by default) if specs - # failed. - def run_specs(example_groups) - @configuration.reporter.report(@world.example_count(example_groups)) do |reporter| - begin - hook_context = SuiteHookContext.new - @configuration.hooks.run(:before, :suite, hook_context) - example_groups.map { |g| g.run(reporter) }.all? ? 0 : @configuration.failure_exit_code - ensure - @configuration.hooks.run(:after, :suite, hook_context) - end - end - end - - # @private - def self.disable_autorun! - @autorun_disabled = true - end - - # @private - def self.autorun_disabled? - @autorun_disabled ||= false - end - - # @private - def self.installed_at_exit? - @installed_at_exit ||= false - end - - # @private - def self.running_in_drb? - begin - if defined?(DRb) && DRb.current_server - require 'socket' - require 'uri' - - local_ipv4 = IPSocket.getaddress(Socket.gethostname) - - local_drb = ["127.0.0.1", "localhost", local_ipv4].any? { |addr| addr == URI(DRb.current_server.uri).host } - end - rescue DRb::DRbServerNotFound - ensure - return local_drb || false - end - end - - # @private - def self.trap_interrupt - trap('INT') do - exit!(1) if RSpec.world.wants_to_quit - RSpec.world.wants_to_quit = true - STDERR.puts "\nExiting... Interrupt again to exit immediately." - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/shared_context.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/shared_context.rb deleted file mode 100644 index 6de7f64..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/shared_context.rb +++ /dev/null @@ -1,55 +0,0 @@ -module RSpec - module Core - # Exposes {ExampleGroup}-level methods to a module, so you can include that - # module in an {ExampleGroup}. - # - # @example - # - # module LoggedInAsAdmin - # extend RSpec::Core::SharedContext - # before(:example) do - # log_in_as :admin - # end - # end - # - # describe "admin section" do - # include LoggedInAsAdmin - # # ... - # end - module SharedContext - # @private - def included(group) - __shared_context_recordings.each do |recording| - recording.playback_onto(group) - end - end - - # @private - def __shared_context_recordings - @__shared_context_recordings ||= [] - end - - # @private - Recording = Struct.new(:method_name, :args, :block) do - def playback_onto(group) - group.__send__(method_name, *args, &block) - end - end - - # @private - def self.record(methods) - methods.each do |meth| - define_method(meth) do |*args, &block| - __shared_context_recordings << Recording.new(meth, args, block) - end - end - end - - # @private - record [:describe, :context] + Hooks.instance_methods(false) + - MemoizedHelpers::ClassMethods.instance_methods(false) - end - end - # @private - SharedContext = Core::SharedContext -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/shared_example_group.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/shared_example_group.rb deleted file mode 100644 index b34cf78..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/shared_example_group.rb +++ /dev/null @@ -1,181 +0,0 @@ -module RSpec - module Core - # Shared example groups let you define common context and/or common - # examples that you wish to use in multiple example groups. - # - # When defined, the shared group block is stored for later evaluation. - # It can later be included in an example group either explicitly - # (using `include_examples`, `include_context` or `it_behaves_like`) - # or implicitly (via matching metadata). - # - # Named shared example groups are scoped based on where they are - # defined. Shared groups defined in an example group are available - # for inclusion in that example group or any child example groups, - # but not in any parent or sibling example groups. Shared example - # groups defined at the top level can be included from any example group. - module SharedExampleGroup - # @overload shared_examples(name, &block) - # @param name [String, Symbol, Module] identifer to use when looking up this shared group - # @param block The block to be eval'd - # @overload shared_examples(name, metadata, &block) - # @param name [String, Symbol, Module] identifer to use when looking up this shared group - # @param metadata [Array, Hash] metadata to attach to this group; any example group - # with matching metadata will automatically include this shared example group. - # @param block The block to be eval'd - # @overload shared_examples(metadata, &block) - # @param metadata [Array, Hash] metadata to attach to this group; any example group - # with matching metadata will automatically include this shared example group. - # @param block The block to be eval'd - # - # Stores the block for later use. The block will be evaluated - # in the context of an example group via `include_examples`, - # `include_context`, or `it_behaves_like`. - # - # @example - # shared_examples "auditable" do - # it "stores an audit record on save!" do - # expect { auditable.save! }.to change(Audit, :count).by(1) - # end - # end - # - # describe Account do - # it_behaves_like "auditable" do - # let(:auditable) { Account.new } - # end - # end - # - # @see ExampleGroup.it_behaves_like - # @see ExampleGroup.include_examples - # @see ExampleGroup.include_context - def shared_examples(name, *args, &block) - top_level = self == ExampleGroup - if top_level && RSpec.thread_local_metadata[:in_example_group] - raise "Creating isolated shared examples from within a context is " + - "not allowed. Remove `RSpec.` prefix or move this to a " + - "top-level scope." - end - - RSpec.world.shared_example_group_registry.add(self, name, *args, &block) - end - alias shared_context shared_examples - alias shared_examples_for shared_examples - - # @api private - # - # Shared examples top level DSL - module TopLevelDSL - # @private - def self.definitions - proc do - def shared_examples(name, *args, &block) - RSpec.world.shared_example_group_registry.add(:main, name, *args, &block) - end - alias shared_context shared_examples - alias shared_examples_for shared_examples - end - end - - # @private - def self.exposed_globally? - @exposed_globally ||= false - end - - # @api private - # - # Adds the top level DSL methods to Module and the top level binding - def self.expose_globally! - return if exposed_globally? - Core::DSL.change_global_dsl(&definitions) - @exposed_globally = true - end - - # @api private - # - # Removes the top level DSL methods to Module and the top level binding - def self.remove_globally! - return unless exposed_globally? - - Core::DSL.change_global_dsl do - undef shared_examples - undef shared_context - undef shared_examples_for - end - - @exposed_globally = false - end - - end - - # @private - class Registry - def add(context, name, *metadata_args, &block) - ensure_block_has_source_location(block) { CallerFilter.first_non_rspec_line } - - if valid_name?(name) - warn_if_key_taken context, name, block - shared_example_groups[context][name] = block - else - metadata_args.unshift name - end - - unless metadata_args.empty? - mod = Module.new - (class << mod; self; end).__send__(:define_method, :included) do |host| - host.class_exec(&block) - end - RSpec.configuration.include mod, *metadata_args - end - end - - def find(lookup_contexts, name) - lookup_contexts.each do |context| - found = shared_example_groups[context][name] - return found if found - end - - shared_example_groups[:main][name] - end - - private - - def shared_example_groups - @shared_example_groups ||= Hash.new { |hash, context| hash[context] = {} } - end - - def valid_name?(candidate) - case candidate - when String, Symbol, Module then true - else false - end - end - - def warn_if_key_taken(context, key, new_block) - return unless existing_block = shared_example_groups[context][key] - - RSpec.warn_with <<-WARNING.gsub(/^ +\|/, ''), :call_site => nil - |WARNING: Shared example group '#{key}' has been previously defined at: - | #{formatted_location existing_block} - |...and you are now defining it at: - | #{formatted_location new_block} - |The new definition will overwrite the original one. - WARNING - end - - def formatted_location(block) - block.source_location.join ":" - end - - if Proc.method_defined?(:source_location) - def ensure_block_has_source_location(block); end - else # for 1.8.7 - def ensure_block_has_source_location(block) - source_location = yield.split(':') - block.extend Module.new { define_method(:source_location) { source_location } } - end - end - end - end - end - - instance_exec(&Core::SharedExampleGroup::TopLevelDSL.definitions) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/test_unit_assertions_adapter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/test_unit_assertions_adapter.rb deleted file mode 100644 index 71d781e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/test_unit_assertions_adapter.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'test/unit/assertions' - -module RSpec - module Core - # @private - module TestUnitAssertionsAdapter - include ::Test::Unit::Assertions - - # If using test/unit from Ruby core with Ruby 1.9+, it includes - # MiniTest::Assertions by default. Note the upcasing of 'Test'. - # - # If the test/unit gem is being loaded, it will not include any minitest - # assertions. - # - # Only if Minitest 5.x is included / loaded do we need to worry about - # adding a shim for the new updates. Thus instead of checking on the - # RUBY_VERSION we need to check ancestors. - begin - # MiniTest is 4.x - # Minitest is 5.x - if ancestors.include?(::Minitest::Assertions) - require 'rspec/core/minitest_assertions_adapter' - include ::RSpec::Core::MinitestAssertionsAdapter - end - rescue NameError => _ignored - # No-op. Minitest 5.x was not loaded - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/version.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/version.rb deleted file mode 100644 index 7af0fc2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/version.rb +++ /dev/null @@ -1,9 +0,0 @@ -module RSpec - module Core - # Version information for RSpec Core. - module Version - # Current version of RSpec Core, in semantic versioning format. - STRING = '3.0.3' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/warnings.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/warnings.rb deleted file mode 100644 index bc2dabe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/warnings.rb +++ /dev/null @@ -1,40 +0,0 @@ -require "rspec/support/warnings" - -module RSpec - module Core - # @private - module Warnings - # @private - # - # Used internally to print deprecation warnings - def deprecate(deprecated, data = {}) - RSpec.configuration.reporter.deprecation( - { - :deprecated => deprecated, - :call_site => CallerFilter.first_non_rspec_line - }.merge(data) - ) - end - - # @private - # - # Used internally to print deprecation warnings - def warn_deprecation(message, opts = {}) - RSpec.configuration.reporter.deprecation opts.merge( :message => message ) - end - - # @private - def warn_with(message, options = {}) - if options[:use_spec_location_as_call_site] - message += "." unless message.end_with?(".") - - if RSpec.current_example - message += " Warning generated from spec at `#{RSpec.current_example.location}`." - end - end - - super(message, options) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/world.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/world.rb deleted file mode 100644 index b564616..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-core-3.0.3/lib/rspec/core/world.rb +++ /dev/null @@ -1,183 +0,0 @@ -module RSpec - module Core - # @api private - # - # Internal container for global non-configuration data - class World - - include RSpec::Core::Hooks - - # @private - attr_reader :example_groups, :filtered_examples - - # Used internally to determine what to do when a SIGINT is received - attr_accessor :wants_to_quit - - def initialize(configuration=RSpec.configuration) - @configuration = configuration - @example_groups = [] - @filtered_examples = Hash.new { |hash,group| - hash[group] = begin - examples = group.examples.dup - examples = filter_manager.prune(examples) - examples.uniq! - examples - end - } - end - - # @private - # Used internally to clear remaining groups when fail_fast is set - def clear_remaining_example_groups - example_groups.clear - end - - # @private - def windows_os? - RbConfig::CONFIG['host_os'] =~ /cygwin|mswin|mingw|bccwin|wince|emx/ - end - - # @api private - # - # Apply ordering strategy from configuration to example groups - def ordered_example_groups - ordering_strategy = @configuration.ordering_registry.fetch(:global) - ordering_strategy.order(@example_groups) - end - - # @api private - # - # Reset world to 'scratch' before running suite - def reset - example_groups.clear - @shared_example_group_registry = nil - end - - # @private - def filter_manager - @configuration.filter_manager - end - - # @api private - # - # Register an example group - def register(example_group) - example_groups << example_group - example_group - end - - # @private - def shared_example_group_registry - @shared_example_group_registry ||= SharedExampleGroup::Registry.new - end - - # @private - def inclusion_filter - @configuration.inclusion_filter - end - - # @private - def exclusion_filter - @configuration.exclusion_filter - end - - # @private - def configure_group(group) - @configuration.configure_group(group) - end - - # @api private - # - # Get count of examples to be run - def example_count(groups=example_groups) - FlatMap.flat_map(groups) {|g| g.descendants}. - inject(0) {|sum, g| sum + g.filtered_examples.size} - end - - # @api private - # - # Find line number of previous declaration - def preceding_declaration_line(filter_line) - declaration_line_numbers.sort.inject(nil) do |highest_prior_declaration_line, line| - line <= filter_line ? line : highest_prior_declaration_line - end - end - - # @private - def reporter - @configuration.reporter - end - - # @api private - # - # Notify reporter of filters - def announce_filters - filter_announcements = [] - - announce_inclusion_filter filter_announcements - announce_exclusion_filter filter_announcements - - unless filter_manager.empty? - if filter_announcements.length == 1 - reporter.message("Run options: #{filter_announcements[0]}") - else - reporter.message("Run options:\n #{filter_announcements.join("\n ")}") - end - end - - if @configuration.run_all_when_everything_filtered? && example_count.zero? - reporter.message("#{everything_filtered_message}; ignoring #{inclusion_filter.description}") - filtered_examples.clear - inclusion_filter.clear - end - - if example_count.zero? - example_groups.clear - if filter_manager.empty? - reporter.message("No examples found.") - elsif exclusion_filter.empty? - message = everything_filtered_message - if @configuration.run_all_when_everything_filtered? - message << "; ignoring #{inclusion_filter.description}" - end - reporter.message(message) - elsif inclusion_filter.empty? - reporter.message(everything_filtered_message) - end - end - end - - # @private - def everything_filtered_message - "\nAll examples were filtered out" - end - - # @api private - # - # Add inclusion filters to announcement message - def announce_inclusion_filter(announcements) - unless inclusion_filter.empty? - announcements << "include #{inclusion_filter.description}" - end - end - - # @api private - # - # Add exclusion filters to announcement message - def announce_exclusion_filter(announcements) - unless exclusion_filter.empty? - announcements << "exclude #{exclusion_filter.description}" - end - end - - private - - def declaration_line_numbers - @line_numbers ||= example_groups.inject([]) do |lines, g| - lines + g.declaration_line_numbers - end - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/.document b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/.document deleted file mode 100644 index 050e204..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/.document +++ /dev/null @@ -1,5 +0,0 @@ -lib/**/*.rb -- -README.md -License.txt -Changelog.md diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/.yardopts b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/.yardopts deleted file mode 100644 index 15f63ee..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/.yardopts +++ /dev/null @@ -1,6 +0,0 @@ ---exclude features ---no-private ---markup markdown -- -Changelog.md -License.txt diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/Changelog.md b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/Changelog.md deleted file mode 100644 index 1e8a136..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/Changelog.md +++ /dev/null @@ -1,771 +0,0 @@ -### 3.0.3 / 2014-07-21 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.2...v3.0.3) - -Bug Fixes: - -* Fix issue with detection of generic operator matchers so they work - correctly when undefined. (Myron Marston, #597) -* Don't inadvertently define `BasicObject` in 1.8.7. (Chris Griego, #603) -* Fix `include` matcher so that it fails gracefully when matched against - an object that does not respond to `include?`. (Myron Marston, #607) - -### 3.0.2 / 2014-06-19 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.1...v3.0.2) - -Bug Fixes: - -* Fix regression in `contain_exactly` (AKA `match_array`) that caused it - to wrongly pass when the expected array was empty. (Myron Marston, #581) -* Provide a better error message when you use the `change(obj, :msg)` - form of the change matcher but forget the message argument. (Alex - Sunderland, #585) -* Make the `contain_exactly` matcher work with arrays that contain hashes in - arbitrary ordering. (Sam Phippen, #578) - -### 3.0.1 / 2014-06-12 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.0...v3.0.1) - -Bug Fixes: - -* Add a missing `require` that would cause the `respond_to` matcher to - fail when used in a project where the rest of RSpec (e.g. core and - expecatations) weren't being used. (Myron Marston, #566) -* Structs are no longer treated as arrays when diffed. (Jon Rowe, #576) - -### 3.0.0 / 2014-06-01 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.0.rc1...v3.0.0) - -No code changes. Just taking it out of pre-release. - -### 3.0.0.rc1 / 2014-05-18 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.0.beta2...v3.0.0.rc1) - -Breaking Changes for 3.0.0: - -* Remove `matcher_execution_context` attribute from DSL-defined - custom matchers. (Myron Marston) -* Remove `RSpec::Matchers::Pretty#_pretty_print`. (Myron Marston) -* Remove `RSpec::Matchers::Pretty#expected_to_sentence`. (Myron Marston) -* Rename `RSpec::Matchers::Configuration` constant to - `RSpec::Expectations::Configuration`. (Myron Marston) -* Prevent `have_xyz` predicate matchers using private methods. - (Adrian Gonzalez) -* Block matchers must now implement `supports_block_expectations?`. - (Myron Marston) -* Stop supporting `require 'rspec-expectations'`. - Use `require 'rspec/expectations'` instead. (Myron Marston) - -Bug Fixes: - -* Fix `NoMethodError` triggered by beta2 when `YARD` was loaded in - the test environment. (Myron Marston) -* Fix `be_xyz` matcher to accept a `do...end` block. (Myron Marston) -* Fix composable matcher failure message generation logic - so that it does not blow up when given `$stdout` or `$stderr`. - (Myron Marston) -* Fix `change` matcher to work properly with `IO` objects. - (Myron Marston) -* Fix `exist` matcher so that it can be used in composed matcher - expressions involving objects that do not implement `exist?` or - `exists?`. (Daniel Fone) -* Fix composable matcher match logic so that it clones matchers - before using them in order to work properly with matchers - that use internal memoization based on a given `actual` value. - (Myron Marston) -* Fix `be_xyz` and `has_xyz` predicate matchers so that they can - be used in composed matcher expressions involving objects that - do not implement the predicate method. (Daniel Fone) - -Enhancements: - -* Document the remaining public APIs. rspec-expectations now has 100% of - the public API documented and will remain that way (as new undocumented - methods will fail the build). (Myron Marston) -* Improve the formatting of BigDecimal objects in `eq` matcher failure - messages. (Daniel Fone) -* Improve the failure message for `be_xyz` predicate matchers so - that it includes the `inspect` output of the receiver. - (Erik Michaels-Ober, Sam Phippen) -* Add `all` matcher, to allow you to specify that a given matcher - matches all elements in a collection: - `expect([1, 3, 5]).to all( be_odd )`. (Adam Farhi) -* Add boolean aliases (`&`/`|`) for compound operators (`and`/`or`). (Adam Farhi) -* Give users a clear error when they wrongly use a value matcher - in a block expectation expression (e.g. `expect { 3 }.to eq(3)`) - or vice versa. (Myron Marston) - -### 3.0.0.beta2 / 2014-02-17 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v3.0.0.beta1...v3.0.0.beta2) - -Breaking Changes for 3.0.0: - -* Remove deprecated support for accessing the `RSpec` constant using - `Rspec` or `Spec`. (Myron Marston) -* Remove deprecated `RSpec::Expectations.differ=`. (Myron Marston) -* Remove support for deprecated `expect(...).should`. (Myron Marston) -* Explicitly disallow `expect { }.not_to change { }` with `by`, - `by_at_least`, `by_at_most` or `to`. These have never been supported - but did not raise explicit errors. (Myron Marston) -* Provide `===` rather than `==` as an alias of `matches?` for - all matchers. The semantics of `===` are closer to an RSpec - matcher than `==`. (Myron Marston) -* Remove deprecated `RSpec::Matchers::OperatorMatcher` constant. - (Myron Marston) -* Make `RSpec::Expectations::ExpectationNotMetError` subclass - `Exception` rather than `StandardError` so they can bypass - a bare `rescue` in end-user code (e.g. when an expectation is - set from within a rspec-mocks stub implementation). (Myron Marston) -* Remove Test::Unit and Minitest 4.x integration. (Myron Marston) - -Enhancements: - -* Simplify the failure message of the `be` matcher when matching against: - `true`, `false` and `nil`. (Sam Phippen) -* Update matcher protocol and custom matcher DSL to better align - with the newer `expect` syntax. If you want your matchers to - maintain compatibility with multiple versions of RSpec, you can - alias the new names to the old. (Myron Marston) - * `failure_message_for_should` => `failure_message` - * `failure_message_for_should_not` => `failure_message_when_negated` - * `match_for_should` => `match` - * `match_for_should_not` => `match_when_negated` -* Improve generated descriptions from `change` matcher. (Myron Marston) -* Add support for compound matcher expressions using `and` and `or`. - Simply chain them off of any existing matcher to create an expression - like `expect(alphabet).to start_with("a").and end_with("z")`. - (Eloy Espinaco) -* Add `contain_exactly` as a less ambiguous version of `match_array`. - Note that it expects the expected array to be splatted as - individual args: `expect(array).to contain_exactly(1, 2)` is - the same as `expect(array).to match_array([1, 2])`. (Myron Marston) -* Update `contain_exactly`/`match_array` so that it can match against - other non-array collections (such as a `Set`). (Myron Marston) -* Update built-in matchers so that they can accept matchers as arguments - to allow you to compose matchers in arbitrary ways. (Myron Marston) -* Add `RSpec::Matchers::Composable` mixin that can be used to make - a custom matcher composable as well. Note that custom matchers - defined via `RSpec::Matchers.define` already have this. (Myron - Marston) -* Define noun-phrase aliases for built-in matchers, which can be - used when creating composed matcher expressions that read better - and provide better failure messages. (Myron Marston) -* Add `RSpec::Machers.alias_matcher` so users can define their own - matcher aliases. The `description` of the matcher will reflect the - alternate matcher name. (Myron Marston) -* Add explicit `be_between` matcher. `be_between` has worked for a - long time as a dynamic predicate matcher, but the failure message - was suboptimal. The new matcher provides a much better failure - message. (Erik Michaels-Ober) -* Enhance the `be_between` matcher to allow for `inclusive` or `exclusive` - comparison (e.g. inclusive of min/max or exclusive of min/max). - (Pedro Gimenez) -* Make failure message for `not_to be #{operator}` less confusing by - only saying it's confusing when comparison operators are used. - (Prathamesh Sonpatki) -* Improve failure message of `eq` matcher when `Time` or `DateTime` - objects are used so that the full sub-second precision is included. - (Thomas Holmes, Jeff Wallace) -* Add `output` matcher for expecting that a block outputs `to_stdout` - or `to_stderr`. (Luca Pette, Matthias Günther) -* Forward a provided block on to the `has_xyz?` method call when - the `have_xyz` matcher is used. (Damian Galarza) -* Provide integration with Minitest 5.x. Require - `rspec/expectations/minitest_integration` after loading minitest - to use rspec-expectations with minitest. (Myron Marston) - -Bug Fixes: - -* Fix wrong matcher descriptions with falsey expected value (yujinakayama) -* Fix `expect { }.not_to change { }.from(x)` so that the matcher only - passes if the starting value is `x`. (Tyler Rick, Myron Marston) -* Fix hash diffing, so that it colorizes properly and doesn't consider trailing - commas when performing the diff. (Jared Norman) -* Fix built-in matchers to fail normally rather than raising - `ArgumentError` when given an object of the wrong type to match - against, so that they work well in composite matcher expressions like - `expect([1.51, "foo"]).to include(a_string_matching(/foo/), a_value_within(0.1).of(1.5))`. - (Myron Marston) - -Deprecations: - -* Retain support for RSpec 2 matcher protocol (e.g. for matchers - in 3rd party extension gems like `shoulda`), but it will print - a deprecation warning. (Myron Marston) - -### 3.0.0.beta1 / 2013-11-07 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.2...v3.0.0.beta1) - -Breaking Changes for 3.0.0: - -* Remove explicit support for 1.8.6. (Jon Rowe) -* Remove the deprecated `be_close` matcher, preferring `be_within` instead. - (Sam Phippen) -* Remove the deprecated `have`, `have_at_least` and `have_at_most` matchers. - You can continue using those matchers through https://github.com/rspec/rspec-collection_matchers, - or you can rewrite your expectations with something like - `expect(your_object.size).to eq(num)`. (Hugo Baraúna) -* Rename `be_true` and `be_false` to `be_truthy` and `be_falsey`. (Sam Phippen) -* Make `expect { }.to_not raise_error(SomeSpecificClass, message)`, - `expect { }.to_not raise_error(SomeSpecificClass)` and - `expect { }.to_not raise_error(message)` invalid, since they are prone - to hiding failures. Instead, use `expect { }.to_not raise_error` (with no - args). (Sam Phippen) -* Within `RSpec::Matchers.define` blocks, helper methods made available - either via `def self.helper` or `extend HelperModule` are no longer - available to the `match` block (or any of the others). Instead - `include` your helper module and define the helper method as an - instance method. (Myron Marston) -* Force upgrading Diff::LCS for encoding compatability with diffs. (Jon Rowe) - -Enhancements: - -* Support `do..end` style block with `raise_error` matcher. (Yuji Nakayama) -* Rewrote custom matcher DSL to simplify its implementation and solve a - few issues. (Myron Marston) -* Allow early `return` from within custom matcher DSL blocks. (Myron - Marston) -* The custom matcher DSL's `chain` can now accept a block. (Myron - Marston) -* Support setting an expectation on a `raise_error` matcher via a chained - `with_message` method call. (Sam Phippen) - -Bug Fixes: - -* Allow `include` and `match` matchers to be used from within a - DSL-defined custom matcher's `match` block. (Myron Marston) -* Correct encoding error message on diff failure (Jon Rowe) - -Deprecations: - - * Using the old `:should` syntax without explicitly configuring it is deprecated. - It will continue to work but will emit a deprecation warning in RSpec 3 if - you do not explicitly enable it. (Sam Phippen) - -### 2.99.2 / 2014-07-21 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.1...2-99-maintenance) - -Bug Fixes: - -* Fix regression in `Expectations#method_handle_for` where proxy objects - with method delegated would wrongly not return a method handle. - (Jon Rowe, #594) -* Fix issue with detection of generic operator matchers so they work - correctly when undefined. (Myron Marston, #597) - -### 2.99.1 / 2014-06-19 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0...v2.99.1) - -Bug Fixes: - -* Fix typo in custom matcher `expected` deprecation warning -- it's - `expected_as_array`, not `expected_array`. (Frederick Cheung, #562) - -### 2.99.0 / 2014-06-01 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0.rc1...v2.99.0) - -Enhancements: - -* Special case deprecation message for `errors_on` with `rspec-rails` to be more useful. - (Aaron Kromer) - -### 2.99.0.rc1 / 2014-05-18 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0.beta2...2.99.0.rc1) - -Deprecations: - -* Deprecate `matcher_execution_context` attribute on DSL-defined - custom matchers. (Myron Marston) -* Deprecate `RSpec::Matchers::Pretty#_pretty_print`. (Myron Marston) -* Deprecate `RSpec::Matchers::Pretty#expected_to_sentence`. (Myron Marston) -* Deprecate `RSpec::Matchers::Configuration` in favor of - `RSpec::Expectations::Configuration`. (Myron Marston) -* Deprecate `be_xyz` predicate matcher on an object that doesn't respond to - `xyz?` or `xyzs?`. (Daniel Fone) -* Deprecate `have_xyz` matcher on an object that doesn't respond to `has_xyz?`. - (Daniel Fone) -* Deprecate `have_xyz` matcher on an object that has a private method `has_xyz?`. - (Jon Rowe) -* Issue a deprecation warning when a block expectation expression is - used with a matcher that doesn't explicitly support block expectations - via `supports_block_expectations?`. (Myron Marston) -* Deprecate `require 'rspec-expectations'`. Use - `require 'rspec/expectations'` instead. (Myron Marston) - -### 2.99.0.beta2 / 2014-02-17 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.99.0.beta1...v2.99.0.beta2) - -Deprecations: - -* Deprecate chaining `by`, `by_at_least`, `by_at_most` or `to` off of - `expect { }.not_to change { }`. The docs have always said these are - not supported for the negative form but now they explicitly raise - errors in RSpec 3. (Myron Marston) -* Change the semantics of `expect { }.not_to change { x }.from(y)`. - In RSpec 2.x, this expectation would only fail if `x` started with - the value of `y` and changed. If it started with a different value - and changed, it would pass. In RSpec 3, it will pass only if the - value starts at `y` and it does not change. (Myron Marston) -* Deprecate `matcher == value` as an alias for `matcher.matches?(value)`, - in favor of `matcher === value`. (Myron Marston) -* Deprecate `RSpec::Matchers::OperatorMatcher` in favor of - `RSpec::Matchers::BuiltIn::OperatorMatcher`. (Myron Marston) -* Deprecate auto-integration with Test::Unit and minitest. - Instead, include `RSpec::Matchers` in the appropriate test case - base class yourself. (Myron Marston) -* Deprecate treating `#expected` on a DSL-generated custom matcher - as an array when only 1 argument is passed to the matcher method. - In RSpec 3 it will be the single value in order to make diffs - work properly. (Jon Rowe) - -### 2.99.0.beta1 / 2013-11-07 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.4...v2.99.0.beta1) - -Deprecations - -* Deprecate `have`, `have_at_least` and `have_at_most`. You can continue using those - matchers through https://github.com/rspec/rspec-collection_matchers, or - you can rewrite your expectations with something like - `expect(your_object.size).to eq(num)`. (Hugo Baraúna) -* Deprecate `be_xyz` predicate matcher when `xyz?` is a private method. - (Jon Rowe) -* Deprecate `be_true`/`be_false` in favour of `be_truthy`/`be_falsey` - (for Ruby's conditional semantics) or `be true`/`be false` - (for exact equality). (Sam Phippen) -* Deprecate calling helper methods from a custom matcher with the wrong - scope. (Myron Marston) - * `def self.foo` / `extend Helper` can be used to add macro methods - (e.g. methods that call the custom matcher DSL methods), but should - not be used to define helper methods called from within the DSL - blocks. - * `def foo` / `include Helper` is the opposite: it's for helper methods - callable from within a DSL block, but not for defining macros. - * RSpec 2.x allowed helper methods defined either way to be used for - either purpose, but RSpec 3.0 will not. - -### 2.14.5 / 2014-02-01 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.4...v2.14.5) - -Bug fixes - -* Fix wrong matcher descriptions with falsey expected value - (yujinakayama) - -### 2.14.4 / 2013-11-06 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.3...v2.14.4) - -Bug fixes - -* Make the `match` matcher produce a diff output. (Jon Rowe, Ben Moss) -* Choose encoding for diff's more intelligently, and when all else fails fall - back to default internal encoding with replacing characters. (Jon Rowe) - -### 2.14.3 / 2013-09-22 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.2...v2.14.3) - -Bug fixes - -* Fix operator matchers (`should` syntax) when `method` is redefined on target. - (Brandon Turner) -* Fix diffing of hashes with object based keys. (Jon Rowe) -* Fix operator matchers (`should` syntax) when operator is defined via - `method_missing` (Jon Rowe) - -### 2.14.2 / 2013-08-14 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.1...v2.14.2) - -Bug fixes - -* Fix `be_` matcher to not support operator chaining like the - `be` matcher does (e.g. `be == 5`). This led to some odd behaviors - since `be_ == anything` returned a `BeComparedTo` matcher - and was thus always truthy. This was a consequence of the implementation - (e.g. subclassing the basic `Be` matcher) and was not intended behavior. - (Myron Marston). -* Fix `change` matcher to compare using `==` in addition to `===`. This - is important for an expression like: - `expect {}.to change { a.class }.from(ClassA).to(ClassB)` because - `SomeClass === SomeClass` returns false. (Myron Marston) - -### 2.14.1 / 2013-08-08 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.0...2.14.1) - -Bug fixes - -* Ensure diff output uses the same encoding as the encoding of - the string being diff'd to prevent `Encoding::UndefinedConversionError` - errors (Jon Rowe). - -### 2.14.0 / 2013-07-06 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.14.0.rc1...v2.14.0) - -Bug fixes - -* Values that are not matchers use `#inspect`, rather than `#description` for - documentation output (Andy Lindeman, Sam Phippen). -* Make `expect(a).to be_within(x).percent_of(y)` work with negative y - (Katsuhiko Nishimra). -* Make the `be_predicate` matcher work as expected used with `expect{...}.to - change...` (Sam Phippen). - -### 2.14.0.rc1 / 2013-05-27 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.13.0...v2.14.0.rc1) - -Enhancements - -* Enhance `yield_control` so that you can specify an exact or relative - number of times: `expect { }.to yield_control.exactly(3).times`, - `expect { }.to yield_control.at_least(2).times`, etc (Bartek - Borkowski). -* Make the differ that is used when an expectation fails better handle arrays - by splitting each element of the array onto its own line. (Sam Phippen) -* Accept duck-typed strings that respond to `:to_str` as expectation messages. - (Toby Ovod-Everett) - -Bug fixes - -* Fix differ to not raise errors when dealing with differently-encoded - strings (Jon Rowe). -* Fix `expect(something).to be_within(x).percent_of(y)` where x and y are both - integers (Sam Phippen). -* Fix `have` matcher to handle the fact that on ruby 2.0, - `Enumerator#size` may return nil (Kenta Murata). -* Fix `expect { raise s }.to raise_error(s)` where s is an error instance - on ruby 2.0 (Sam Phippen). -* Fix `expect(object).to raise_error` passing. This now warns the user and - fails the spec (tomykaira). - -Deprecations - -* Deprecate `expect { }.not_to raise_error(SpecificErrorClass)` or - `expect { }.not_to raise_error("some specific message")`. Using - these was prone to hiding failures as they would allow _any other - error_ to pass. (Sam Phippen and David Chelimsky) - -### 2.13.0 / 2013-02-23 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.12.1...v2.13.0) - -Enhancements - -* Add support for percent deltas to `be_within` matcher: - `expect(value).to be_within(10).percent_of(expected)` - (Myron Marston). -* Add support to `include` matcher to allow it to be given a list - of matchers as the expecteds to match against (Luke Redpath). - -Bug fixes - -* Fix `change` matcher so that it dups strings in order to handle - mutated strings (Myron Marston). -* Fix `should be =~ /some regex/` / `expect(...).to be =~ /some regex/`. - Previously, these either failed with a confusing `undefined method - matches?' for false:FalseClass` error or were no-ops that didn't - actually verify anything (Myron Marston). -* Add compatibility for diff-lcs 1.2 and relax the version - constraint (Peter Goldstein). -* Fix DSL-generated matchers to allow multiple instances of the - same matcher in the same example to have different description - and failure messages based on the expected value (Myron Marston). -* Prevent `undefined method #split for Array` error when dumping - the diff of an array of multiline strings (Myron Marston). -* Don't blow up when comparing strings that are in an encoding - that is not ASCII compatible (Myron Marston). -* Remove confusing "Check the implementation of #==" message - printed for empty diffs (Myron Marston). - -### 2.12.1 / 2012-12-15 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.12.0...v2.12.1) - -Bug fixes - -* Improve the failure message for an expression like - `{}.should =~ {}`. (Myron Marston and Andy Lindeman) -* Provide a `match_regex` alias so that custom matchers - built using the matcher DSL can use it (since `match` - is a different method in that context). - (Steven Harman) - -### 2.12.0 / 2012-11-12 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.11.3...v2.12.0) - -Enhancements - -* Colorize diffs if the `--color` option is configured. (Alex Coplan) -* Include backtraces in unexpected errors handled by `raise_error` - matcher (Myron Marston) -* Print a warning when users accidentally pass a non-string argument - as an expectation message (Sam Phippen) -* `=~` and `match_array` matchers output a more useful error message when - the actual value is not an array (or an object that responds to `#to_ary`) - (Sam Phippen) - -Bug fixes - -* Fix `include` matcher so that `expect({}).to include(:a => nil)` - fails as it should (Sam Phippen). -* Fix `be_an_instance_of` matcher so that `Class#to_s` is used in the - description rather than `Class#inspect`, since some classes (like - `ActiveRecord::Base`) define a long, verbose `#inspect`. - (Tom Stuart) - -### 2.11.3 / 2012-09-04 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.11.2...v2.11.3) - -Bug fixes - -* Fix (and deprecate) `expect { }.should` syntax so that it works even - though it was never a documented or intended syntax. It worked as a - consequence of the implementation of `expect` in RSpec 2.10 and - earlier. (Myron Marston) -* Ensure #== is defined on built in matchers so that they can be composed. - For example: - - expect { - user.emailed! - }.to change { user.last_emailed_at }.to be_within(1.second).of(Time.zone.now) - -### 2.11.2 / 2012-07-25 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.11.1...v2.11.2) - -Bug fixes - -* Define `should` and `should_not` on `Object` rather than `BasicObject` - on MacRuby. On MacRuby, `BasicObject` is defined but is not the root - of the object hierarchy. (Gabriel Gilder) - -### 2.11.1 / 2012-07-08 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.11.0...v2.11.1) - -Bug fixes - -* Constrain `actual` in `be_within` matcher to values that respond to `-` instead - of requiring a specific type. - * `Time`, for example, is a legit alternative. - -### 2.11.0 / 2012-07-07 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.10.0...v2.11.0) - -Enhancements - -* Expand `expect` syntax so that it supports expections on bare values - in addition to blocks (Myron Marston). -* Add configuration options to control available expectation syntaxes - (Myron Marston): - * `RSpec.configuration.expect_with(:rspec) { |c| c.syntax = :expect }` - * `RSpec.configuration.expect_with(:rspec) { |c| c.syntax = :should }` - * `RSpec.configuration.expect_with(:rspec) { |c| c.syntax = [:should, :expect] }` - * `RSpec.configuration.add_should_and_should_not_to Delegator` - -Bug fixes - -* Allow only `Numeric` values to be the "actual" in the `be_within` matcher. - This prevents confusing error messages. (Su Zhang @zhangsu) -* Define `should` and `should_not` on `BasicObject` rather than `Kernel` - on 1.9. This makes `should` and `should_not` work properly with - `BasicObject`-subclassed proxy objects like `Delegator`. (Myron - Marston) - -### 2.10.0 / 2012-05-03 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.9.1...v2.10.0) - -Enhancements - -* Add new `start_with` and `end_with` matchers (Jeremy Wadsack) -* Add new matchers for specifying yields (Myron Marston): - * `expect {...}.to yield_control` - * `expect {...}.to yield_with_args(1, 2, 3)` - * `expect {...}.to yield_with_no_args` - * `expect {...}.to yield_successive_args(1, 2, 3)` -* `match_unless_raises` takes multiple exception args - -Bug fixes - -* Fix `be_within` matcher to be inclusive of delta. -* Fix message-specific specs to pass on Rubinius (John Firebaugh) - -### 2.9.1 / 2012-04-03 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.9.0...v2.9.1) - -Bug fixes - -* Provide a helpful message if the diff between two objects is empty. -* Fix bug diffing single strings with multiline strings. -* Fix for error with using custom matchers inside other custom matchers - (mirasrael) -* Fix using execution context methods in nested DSL matchers (mirasrael) - -### 2.9.0 / 2012-03-17 -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.8.0...v2.9.0) - -Enhancements - -* Move built-in matcher classes to RSpec::Matchers::BuiltIn to reduce pollution - of RSpec::Matchers (which is included in every example). -* Autoload files with matcher classes to improve load time. - -Bug fixes - -* Align `respond_to?` and `method_missing` in DSL-defined matchers. -* Clear out user-defined instance variables between invocations of DSL-defined - matchers. -* Dup the instance of a DSL generated matcher so its state is not changed by - subsequent invocations. -* Treat expected args consistently across positive and negative expectations - (thanks to Ralf Kistner for the heads up) - -### 2.8.0 / 2012-01-04 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.8.0.rc2...v2.8.0) - -Enhancements - -* Better diff output for Hash (Philippe Creux) -* Eliminate Ruby warnings (Olek Janiszewski) - -### 2.8.0.rc2 / 2011-12-19 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.8.0.rc1...v2.8.0.rc2) - -No changes for this release. Just releasing with the other rspec gems. - -### 2.8.0.rc1 / 2011-11-06 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.7.0...v2.8.0.rc1) - -Enhancements - -* Use classes for the built-in matchers (they're faster). -* Eliminate Ruby warnings (Matijs van Zuijlen) - -### 2.7.0 / 2011-10-16 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.6.0...v2.7.0) - -Enhancements - -* `HaveMatcher` converts argument using `to_i` (Alex Bepple & Pat Maddox) -* Improved failure message for the `have_xxx` matcher (Myron Marston) -* `HaveMatcher` supports `count` (Matthew Bellantoni) -* Change matcher dups `Enumerable` before the action, supporting custom - `Enumerable` types like `CollectionProxy` in Rails (David Chelimsky) - -Bug fixes - -* Fix typo in `have(n).xyz` documentation (Jean Boussier) -* fix `safe_sort` for ruby 1.9.2 (`Kernel` now defines `<=>` for Object) (Peter - van Hardenberg) - -### 2.6.0 / 2011-05-12 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.5.0...v2.6.0) - -Enhancements - -* `change` matcher accepts regexps (Robert Davis) -* better descriptions for `have_xxx` matchers (Magnus Bergmark) -* `range.should cover(*values)` (Anders Furseth) - -Bug fixes - -* Removed non-ascii characters that were choking rcov (Geoffrey Byers) -* change matcher dups arrays and hashes so their before/after states can be - compared correctly. -* Fix the order of inclusion of RSpec::Matchers in Test::Unit::TestCase and - MiniTest::Unit::TestCase to prevent a SystemStackError (Myron Marston) - -### 2.5.0 / 2011-02-05 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.4.0...v2.5.0) - -Enhancements - -* `should exist` works with `exist?` or `exists?` (Myron Marston) -* `expect { ... }.not_to do_something` (in addition to `to_not`) - -Documentation - -* improved docs for raise_error matcher (James Almond) - -### 2.4.0 / 2011-01-02 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.3.0...v2.4.0) - -No functional changes in this release, which was made to align with the -rspec-core-2.4.0 release. - -Enhancements - -* improved RDoc for change matcher (Jo Liss) - -### 2.3.0 / 2010-12-12 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.2.1...v2.3.0) - -Enhancements - -* diff strings when include matcher fails (Mike Sassak) - -### 2.2.0 / 2010-11-28 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.1.0...v2.2.0) - -### 2.1.0 / 2010-11-07 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.0.1...v2.1.0) - -Enhancements - -* `be_within(delta).of(expected)` matcher (Myron Marston) -* Lots of new Cucumber features (Myron Marston) -* Raise error if you try `should != expected` on Ruby-1.9 (Myron Marston) -* Improved failure messages from `throw_symbol` (Myron Marston) - -Bug fixes - -* Eliminate hard dependency on `RSpec::Core` (Myron Marston) -* `have_matcher` - use pluralize only when ActiveSupport inflections are indeed - defined (Josep M Bach) -* throw_symbol matcher no longer swallows exceptions (Myron Marston) -* fix matcher chaining to avoid name collisions (Myron Marston) - -### 2.0.0 / 2010-10-10 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.0.0.rc...v2.0.0) - -Enhancements - -* Add match_for_should_not method to matcher DSL (Myron Marston) - -Bug fixes - -* `respond_to` matcher works correctly with `should_not` with multiple methods - (Myron Marston) -* `include` matcher works correctly with `should_not` with multiple values - (Myron Marston) - -### 2.0.0.rc / 2010-10-05 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.0.0.beta.22...v2.0.0.rc) - -Enhancements - -* `require 'rspec/expectations'` in a T::U or MiniUnit suite (Josep M. Bach) - -Bug fixes - -* change by 0 passes/fails correctly (Len Smith) -* Add description to satisfy matcher - -### 2.0.0.beta.22 / 2010-09-12 - -[Full Changelog](http://github.com/rspec/rspec-expectations/compare/v2.0.0.beta.20...v2.0.0.beta.22) - -Enhancements - -* diffing improvements - * diff multiline strings - * don't diff single line strings - * don't diff numbers (silly) - * diff regexp + multiline string - -Bug fixes - * `should[_not]` change now handles boolean values correctly diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/License.txt b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/License.txt deleted file mode 100644 index 91cfc94..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/License.txt +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 David Chelimsky, Myron Marston -Copyright (c) 2006 David Chelimsky, The RSpec Development Team -Copyright (c) 2005 Steven Baker - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/README.md b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/README.md deleted file mode 100644 index cd47ab7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/README.md +++ /dev/null @@ -1,278 +0,0 @@ -# RSpec Expectations [![Build Status](https://secure.travis-ci.org/rspec/rspec-expectations.png?branch=master)](http://travis-ci.org/rspec/rspec-expectations) [![Code Climate](https://codeclimate.com/github/rspec/rspec-expectations.png)](https://codeclimate.com/github/rspec/rspec-expectations) - -RSpec::Expectations lets you express expected outcomes on an object in an -example. - - expect(account.balance).to eq(Money.new(37.42, :USD)) - -## Install - -If you want to use rspec-expectations with rspec, just install the rspec gem -and RubyGems will also install rspec-expectations for you (along with -rspec-core and rspec-mocks): - - gem install rspec - -If you want to use rspec-expectations with another tool, like Test::Unit, -Minitest, or Cucumber, you can install it directly: - - gem install rspec-expectations - -## Basic usage - -Here's an example using rspec-core: - -```ruby -RSpec.describe Order do - it "sums the prices of the items in its line items" do - order = Order.new - order.add_entry(LineItem.new(:item => Item.new( - :price => Money.new(1.11, :USD) - ))) - order.add_entry(LineItem.new(:item => Item.new( - :price => Money.new(2.22, :USD), - :quantity => 2 - ))) - expect(order.total).to eq(Money.new(5.55, :USD)) - end -end -``` - -The `describe` and `it` methods come from rspec-core. The `Order`, `LineItem`, `Item` and `Money` classes would be from _your_ code. The last line of the example -expresses an expected outcome. If `order.total == Money.new(5.55, :USD)`, then -the example passes. If not, it fails with a message like: - - expected: # - got: # - -## Built-in matchers - -### Equivalence - -```ruby -expect(actual).to eq(expected) # passes if actual == expected -expect(actual).to eql(expected) # passes if actual.eql?(expected) -``` - -Note: The new `expect` syntax no longer supports the `==` matcher. - -### Identity - -```ruby -expect(actual).to be(expected) # passes if actual.equal?(expected) -expect(actual).to equal(expected) # passes if actual.equal?(expected) -``` - -### Comparisons - -```ruby -expect(actual).to be > expected -expect(actual).to be >= expected -expect(actual).to be <= expected -expect(actual).to be < expected -expect(actual).to be_within(delta).of(expected) -``` - -### Regular expressions - -```ruby -expect(actual).to match(/expression/) -``` - -Note: The new `expect` syntax no longer supports the `=~` matcher. - -### Types/classes - -```ruby -expect(actual).to be_an_instance_of(expected) # passes if actual.class == expected -expect(actual).to be_a(expected) # passes if actual.is_a?(expected) -expect(actual).to be_an(expected) # an alias for be_a -expect(actual).to be_a_kind_of(expected) # another alias -``` - -### Truthiness - -```ruby -expect(actual).to be_truthy # passes if actual is truthy (not nil or false) -expect(actual).to be true # passes if actual == true -expect(actual).to be_falsy # passes if actual is falsy (nil or false) -expect(actual).to be false # passes if actual == false -expect(actual).to be_nil # passes if actual is nil -``` - -### Expecting errors - -```ruby -expect { ... }.to raise_error -expect { ... }.to raise_error(ErrorClass) -expect { ... }.to raise_error("message") -expect { ... }.to raise_error(ErrorClass, "message") -``` - -### Expecting throws - -```ruby -expect { ... }.to throw_symbol -expect { ... }.to throw_symbol(:symbol) -expect { ... }.to throw_symbol(:symbol, 'value') -``` - -### Yielding - -```ruby -expect { |b| 5.tap(&b) }.to yield_control # passes regardless of yielded args - -expect { |b| yield_if_true(true, &b) }.to yield_with_no_args # passes only if no args are yielded - -expect { |b| 5.tap(&b) }.to yield_with_args(5) -expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum) -expect { |b| "a string".tap(&b) }.to yield_with_args(/str/) - -expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3) -expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2]) -``` - -### Predicate matchers - -```ruby -expect(actual).to be_xxx # passes if actual.xxx? -expect(actual).to have_xxx(:arg) # passes if actual.has_xxx?(:arg) -``` - -### Ranges (Ruby >= 1.9 only) - -```ruby -expect(1..10).to cover(3) -``` - -### Collection membership - -```ruby -expect(actual).to include(expected) -expect(actual).to start_with(expected) -expect(actual).to end_with(expected) - -expect(actual).to contain_exactly(individual, items) -# ...which is the same as: -expect(actual).to match_array(expected_array) -``` - -#### Examples - -```ruby -expect([1, 2, 3]).to include(1) -expect([1, 2, 3]).to include(1, 2) -expect([1, 2, 3]).to start_with(1) -expect([1, 2, 3]).to start_with(1, 2) -expect([1, 2, 3]).to end_with(3) -expect([1, 2, 3]).to end_with(2, 3) -expect({:a => 'b'}).to include(:a => 'b') -expect("this string").to include("is str") -expect("this string").to start_with("this") -expect("this string").to end_with("ring") -expect([1, 2, 3]).to contain_exactly(2, 3, 1) -expect([1, 2, 3]).to match_array([3, 2, 1]) -``` - -## `should` syntax - -In addition to the `expect` syntax, rspec-expectations continues to support the -`should` syntax: - -```ruby -actual.should eq expected -actual.should be > 3 -[1, 2, 3].should_not include 4 -``` - -See [detailed information on the `should` syntax and its usage.](https://github.com/rspec/rspec-expectations/blob/master/Should.md) - -## Compound Matcher Expressions - -You can also create compound matcher expressions using `and` or `or`: - -``` ruby -expect(alphabet).to start_with("a").and end_with("z") -expect(stoplight.color).to eq("red").or eq("green").or eq("yellow") -``` - -## Composing Matchers - -Many of the built-in matchers are designed to take matchers as -arguments, to allow you to flexibly specify only the essential -aspects of an object or data structure. In addition, all of the -built-in matchers have one or more aliases that provide better -phrasing for when they are used as arguments to another matcher. - -### Examples - -```ruby -expect { k += 1.05 }.to change { k }.by( a_value_within(0.1).of(1.0) ) - -expect { s = "barn" }.to change { s } - .from( a_string_matching(/foo/) ) - .to( a_string_matching(/bar/) ) - -expect(["barn", 2.45]).to contain_exactly( - a_value_within(0.1).of(2.5), - a_string_starting_with("bar") -) - -expect(["barn", "food", 2.45]).to end_with( - a_string_matching("foo"), - a_value > 2 -) - -expect(["barn", 2.45]).to include( a_string_starting_with("bar") ) - -expect(:a => "food", :b => "good").to include(:a => a_string_matching(/foo/)) - -hash = { - :a => { - :b => ["foo", 5], - :c => { :d => 2.05 } - } -} - -expect(hash).to match( - :a => { - :b => a_collection_containing_exactly( - a_string_starting_with("f"), - an_instance_of(Fixnum) - ), - :c => { :d => (a_value < 3) } - } -) - -expect { |probe| - [1, 2, 3].each(&probe) -}.to yield_successive_args( a_value < 2, 2, a_value > 2 ) -``` - -## Usage outside rspec-core - -You always need to load `rspec/expectations` even if you only want to use one part of the library: - -```ruby -require 'rspec/expectations' -``` - -Then simply include `RSpec::Matchers` in any class: - -```ruby -class MyClass - include RSpec::Matchers - - def do_something(arg) - expect(arg).to be > 0 - # do other stuff - end -end -``` - -## Also see - -* [http://github.com/rspec/rspec](http://github.com/rspec/rspec) -* [http://github.com/rspec/rspec-core](http://github.com/rspec/rspec-core) -* [http://github.com/rspec/rspec-mocks](http://github.com/rspec/rspec-mocks) -* [http://github.com/rspec/rspec-collection_matchers](https://github.com/rspec/rspec-collection_matchers) diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations.rb deleted file mode 100644 index 950b0f8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations.rb +++ /dev/null @@ -1,68 +0,0 @@ -require 'rspec/support' -RSpec::Support.require_rspec_support "caller_filter" -RSpec::Support.require_rspec_support "warnings" - -require 'rspec/matchers' - -RSpec::Support.define_optimized_require_for_rspec(:expectations) { |f| require_relative(f) } - -%w[ - expectation_target - configuration - fail_with - handler - version -].each { |file| RSpec::Support.require_rspec_expectations(file) } - -module RSpec - # RSpec::Expectations provides a simple, readable API to express - # the expected outcomes in a code example. To express an expected - # outcome, wrap an object or block in `expect`, call `to` or `to_not` - # (aliased as `not_to`) and pass it a matcher object: - # - # expect(order.total).to eq(Money.new(5.55, :USD)) - # expect(list).to include(user) - # expect(message).not_to match(/foo/) - # expect { do_something }.to raise_error - # - # The last form (the block form) is needed to match against ruby constructs - # that are not objects, but can only be observed when executing a block - # of code. This includes raising errors, throwing symbols, yielding, - # and changing values. - # - # When `expect(...).to` is invoked with a matcher, it turns around - # and calls `matcher.matches?()`. For example, - # in the expression: - # - # expect(order.total).to eq(Money.new(5.55, :USD)) - # - # ...`eq(Money.new(5.55, :USD))` returns a matcher object, and it results - # in the equivalent of `eq.matches?(order.total)`. If `matches?` returns - # `true`, the expectation is met and execution continues. If `false`, then - # the spec fails with the message returned by `eq.failure_message`. - # - # Given the expression: - # - # expect(order.entries).not_to include(entry) - # - # ...the `not_to` method (also available as `to_not`) invokes the equivalent of - # `include.matches?(order.entries)`, but it interprets `false` as success, and - # `true` as a failure, using the message generated by - # `eq.failure_message_when_negated`. - # - # rspec-expectations ships with a standard set of useful matchers, and writing - # your own matchers is quite simple. - # - # See [RSpec::Matchers](../RSpec/Matchers) for more information about the - # built-in matchers that ship with rspec-expectations, and how to write your - # own custom matchers. - module Expectations - # Exception raised when an expectation fails. - # - # @note We subclass Exception so that in a stub implementation if - # the user sets an expectation, it can't be caught in their - # code by a bare `rescue`. - # @api public - ExpectationNotMetError = Class.new(::Exception) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/configuration.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/configuration.rb deleted file mode 100644 index 84c9e7f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/configuration.rb +++ /dev/null @@ -1,135 +0,0 @@ -RSpec::Support.require_rspec_expectations "syntax" - -module RSpec - module Expectations - # Provides configuration options for rspec-expectations. - # If you are using rspec-core, you can access this via a - # block passed to `RSpec::Core::Configuration#expect_with`. - # Otherwise, you can access it via RSpec::Expectations.configuration. - # - # @example - # RSpec.configure do |rspec| - # rspec.expect_with :rspec do |c| - # # c is the config object - # end - # end - # - # # or - # - # RSpec::Expectations.configuration - class Configuration - # Configures the supported syntax. - # @param [Array, Symbol] values the syntaxes to enable - # @example - # RSpec.configure do |rspec| - # rspec.expect_with :rspec do |c| - # c.syntax = :should - # # or - # c.syntax = :expect - # # or - # c.syntax = [:should, :expect] - # end - # end - def syntax=(values) - if Array(values).include?(:expect) - Expectations::Syntax.enable_expect - else - Expectations::Syntax.disable_expect - end - - if Array(values).include?(:should) - Expectations::Syntax.enable_should - else - Expectations::Syntax.disable_should - end - end - - # The list of configured syntaxes. - # @return [Array] the list of configured syntaxes. - # @example - # unless RSpec::Matchers.configuration.syntax.include?(:expect) - # raise "this RSpec extension gem requires the rspec-expectations `:expect` syntax" - # end - def syntax - syntaxes = [] - syntaxes << :should if Expectations::Syntax.should_enabled? - syntaxes << :expect if Expectations::Syntax.expect_enabled? - syntaxes - end - - if ::RSpec.respond_to?(:configuration) - def color? - ::RSpec.configuration.color_enabled? - end - else - # Indicates whether or not diffs should be colored. - # Delegates to rspec-core's color option if rspec-core - # is loaded; otherwise you can set it here. - attr_writer :color - - # Indicates whether or not diffs should be colored. - # Delegates to rspec-core's color option if rspec-core - # is loaded; otherwise you can set it here. - def color? - @color - end - end - - # Adds `should` and `should_not` to the given classes - # or modules. This can be used to ensure `should` works - # properly on things like proxy objects (particular - # `Delegator`-subclassed objects on 1.8). - # - # @param [Array] modules the list of classes or modules - # to add `should` and `should_not` to. - def add_should_and_should_not_to(*modules) - modules.each do |mod| - Expectations::Syntax.enable_should(mod) - end - end - - # Sets or gets the backtrace formatter. The backtrace formatter should - # implement `#format_backtrace(Array)`. This is used - # to format backtraces of errors handled by the `raise_error` - # matcher. - # - # If you are using rspec-core, rspec-core's backtrace formatting - # will be used (including respecting the presence or absence of - # the `--backtrace` option). - # - # @!attribute [rw] backtrace_formatter - attr_writer :backtrace_formatter - def backtrace_formatter - @backtrace_formatter ||= if defined?(::RSpec.configuration.backtrace_formatter) - ::RSpec.configuration.backtrace_formatter - else - NullBacktraceFormatter - end - end - - # @private - def reset_syntaxes_to_default - self.syntax = [:should, :expect] - RSpec::Expectations::Syntax.warn_about_should! - end - - # @api private - # Null implementation of a backtrace formatter used by default - # when rspec-core is not loaded. Does no filtering. - NullBacktraceFormatter = Module.new do - def self.format_backtrace(backtrace) - backtrace - end - end - end - - # The configuration object. - # @return [RSpec::Expectations::Configuration] the configuration object - def self.configuration - @configuration ||= Configuration.new - end - - # set default syntax - configuration.reset_syntaxes_to_default - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/expectation_target.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/expectation_target.rb deleted file mode 100644 index cc74c19..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/expectation_target.rb +++ /dev/null @@ -1,119 +0,0 @@ -module RSpec - module Expectations - # Wraps the target of an expectation. - # - # @example - # expect(something) # => ExpectationTarget wrapping something - # expect { do_something } # => ExpectationTarget wrapping the block - # - # # used with `to` - # expect(actual).to eq(3) - # - # # with `not_to` - # expect(actual).not_to eq(3) - # - # @note `ExpectationTarget` is not intended to be instantiated - # directly by users. Use `expect` instead. - class ExpectationTarget - # @private - # Used as a sentinel value to be able to tell when the user - # did not pass an argument. We can't use `nil` for that because - # `nil` is a valid value to pass. - UndefinedValue = Module.new - - # @api private - def initialize(value) - @target = value - end - - # @private - def self.for(value, block) - if UndefinedValue.equal?(value) - unless block - raise ArgumentError, "You must pass either an argument or a block to `expect`." - end - BlockExpectationTarget.new(block) - elsif block - raise ArgumentError, "You cannot pass both an argument and a block to `expect`." - else - new(value) - end - end - - # Runs the given expectation, passing if `matcher` returns true. - # @example - # expect(value).to eq(5) - # expect { perform }.to raise_error - # @param [Matcher] - # matcher - # @param [String or Proc] message optional message to display when the expectation fails - # @return [Boolean] true if the expectation succeeds (else raises) - # @see RSpec::Matchers - def to(matcher=nil, message=nil, &block) - prevent_operator_matchers(:to) unless matcher - RSpec::Expectations::PositiveExpectationHandler.handle_matcher(@target, matcher, message, &block) - end - - # Runs the given expectation, passing if `matcher` returns false. - # @example - # expect(value).not_to eq(5) - # @param [Matcher] - # matcher - # @param [String or Proc] message optional message to display when the expectation fails - # @return [Boolean] false if the negative expectation succeeds (else raises) - # @see RSpec::Matchers - def not_to(matcher=nil, message=nil, &block) - prevent_operator_matchers(:not_to) unless matcher - RSpec::Expectations::NegativeExpectationHandler.handle_matcher(@target, matcher, message, &block) - end - alias to_not not_to - - private - - def prevent_operator_matchers(verb) - raise ArgumentError, "The expect syntax does not support operator matchers, " \ - "so you must pass a matcher to `##{verb}`." - end - end - - # @private - # Validates the provided matcher to ensure it supports block - # expectations, in order to avoid user confusion when they - # use a block thinking the expectation will be on the return - # value of the block rather than the block itself. - class BlockExpectationTarget < ExpectationTarget - def to(matcher, message=nil, &block) - enforce_block_expectation(matcher) - super - end - - def not_to(matcher, message=nil, &block) - enforce_block_expectation(matcher) - super - end - alias to_not not_to - - private - - def enforce_block_expectation(matcher) - return if supports_block_expectations?(matcher) - - raise ExpectationNotMetError, "You must pass an argument rather than " \ - "a block to use the provided matcher (#{description_of matcher}), or " \ - "the matcher must implement `supports_block_expectations?`." - end - - def supports_block_expectations?(matcher) - matcher.supports_block_expectations? - rescue NoMethodError - false - end - - def description_of(matcher) - matcher.description - rescue NoMethodError - matcher.inspect - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/fail_with.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/fail_with.rb deleted file mode 100644 index 057c309..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/fail_with.rb +++ /dev/null @@ -1,34 +0,0 @@ -RSpec::Support.require_rspec_support 'differ' - -module RSpec - module Expectations - class << self - # @private - def differ - RSpec::Support::Differ.new( - :object_preparer => lambda { |object| RSpec::Matchers::Composable.surface_descriptions_in(object) }, - :color => RSpec::Matchers.configuration.color? - ) - end - - # Raises an RSpec::Expectations::ExpectationNotMetError with message. - # @param [String] message - # @param [Object] expected - # @param [Object] actual - # - # Adds a diff to the failure message when `expected` and `actual` are - # both present. - def fail_with(message, expected=nil, actual=nil) - unless message - raise ArgumentError, "Failure message is nil. Does your matcher define the " \ - "appropriate failure_message[_when_negated] method to return a string?" - end - - diff = differ.diff(actual, expected) - message = "#{message}\nDiff:#{diff}" unless diff.empty? - - raise RSpec::Expectations::ExpectationNotMetError, message - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/handler.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/handler.rb deleted file mode 100644 index a4ac77a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/handler.rb +++ /dev/null @@ -1,161 +0,0 @@ -module RSpec - module Expectations - # @private - module ExpectationHelper - def self.check_message(msg) - unless msg.nil? || msg.respond_to?(:to_str) || msg.respond_to?(:call) - ::Kernel.warn [ - "WARNING: ignoring the provided expectation message argument (", - msg.inspect, - ") since it is not a string or a proc." - ].join - end - end - - # Returns an RSpec-3+ compatible matcher, wrapping a legacy one - # in an adapter if necessary. - # - # @private - def self.modern_matcher_from(matcher) - LegacyMacherAdapter::RSpec2.wrap(matcher) || - LegacyMacherAdapter::RSpec1.wrap(matcher) || matcher - end - - def self.setup(handler, matcher, message) - check_message(message) - ::RSpec::Matchers.last_expectation_handler = handler - ::RSpec::Matchers.last_matcher = modern_matcher_from(matcher) - end - - def self.handle_failure(matcher, message, failure_message_method) - message = message.call if message.respond_to?(:call) - message ||= matcher.__send__(failure_message_method) - - if matcher.respond_to?(:diffable?) && matcher.diffable? - ::RSpec::Expectations.fail_with message, matcher.expected, matcher.actual - else - ::RSpec::Expectations.fail_with message - end - end - end - - # @private - class PositiveExpectationHandler - def self.handle_matcher(actual, initial_matcher, message=nil, &block) - matcher = ExpectationHelper.setup(self, initial_matcher, message) - - return ::RSpec::Matchers::BuiltIn::PositiveOperatorMatcher.new(actual) unless initial_matcher - matcher.matches?(actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message) - end - - def self.verb - "should" - end - - def self.should_method - :should - end - - def self.opposite_should_method - :should_not - end - end - - # @private - class NegativeExpectationHandler - def self.handle_matcher(actual, initial_matcher, message=nil, &block) - matcher = ExpectationHelper.setup(self, initial_matcher, message) - - return ::RSpec::Matchers::BuiltIn::NegativeOperatorMatcher.new(actual) unless initial_matcher - !(does_not_match?(matcher, actual, &block) || ExpectationHelper.handle_failure(matcher, message, :failure_message_when_negated)) - end - - def self.does_not_match?(matcher, actual, &block) - if matcher.respond_to?(:does_not_match?) - matcher.does_not_match?(actual, &block) - else - !matcher.matches?(actual, &block) - end - end - - def self.verb - "should not" - end - - def self.should_method - :should_not - end - - def self.opposite_should_method - :should - end - end - - # Wraps a matcher written against one of the legacy protocols in - # order to present the current protocol. - # - # @private - class LegacyMacherAdapter < Matchers::MatcherDelegator - def initialize(matcher) - super - ::RSpec.warn_deprecation(<<-EOS.gsub(/^\s+\|/, ''), :type => "legacy_matcher") - |#{matcher.class.name || matcher.inspect} implements a legacy RSpec matcher - |protocol. For the current protocol you should expose the failure messages - |via the `failure_message` and `failure_message_when_negated` methods. - |(Used from #{CallerFilter.first_non_rspec_line}) - EOS - end - - def self.wrap(matcher) - new(matcher) if interface_matches?(matcher) - end - - # Starting in RSpec 1.2 (and continuing through all 2.x releases), - # the failure message protocol was: - # * `failure_message_for_should` - # * `failure_message_for_should_not` - # @private - class RSpec2 < self - def failure_message - base_matcher.failure_message_for_should - end - - def failure_message_when_negated - base_matcher.failure_message_for_should_not - end - - def self.interface_matches?(matcher) - ( - !matcher.respond_to?(:failure_message) && - matcher.respond_to?(:failure_message_for_should) - ) || ( - !matcher.respond_to?(:failure_message_when_negated) && - matcher.respond_to?(:failure_message_for_should_not) - ) - end - end - - # Before RSpec 1.2, the failure message protocol was: - # * `failure_message` - # * `negative_failure_message` - # @private - class RSpec1 < self - def failure_message - base_matcher.failure_message - end - - def failure_message_when_negated - base_matcher.negative_failure_message - end - - # Note: `failure_message` is part of the RSpec 3 protocol - # (paired with `failure_message_when_negated`), so we don't check - # for `failure_message` here. - def self.interface_matches?(matcher) - !matcher.respond_to?(:failure_message_when_negated) && - matcher.respond_to?(:negative_failure_message) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/minitest_integration.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/minitest_integration.rb deleted file mode 100644 index 8b99269..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/minitest_integration.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'rspec/expectations' - -Minitest::Test.class_eval do - include ::RSpec::Matchers - - def expect(*a, &b) - assert(true) # so each expectation gets counted in minitest's assertion stats - super - end -end - -module RSpec - module Expectations - remove_const :ExpectationNotMetError - ExpectationNotMetError = ::Minitest::Assertion - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/syntax.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/syntax.rb deleted file mode 100644 index eaf07a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/syntax.rb +++ /dev/null @@ -1,132 +0,0 @@ -module RSpec - module Expectations - # @api private - # Provides methods for enabling and disabling the available - # syntaxes provided by rspec-expectations. - module Syntax - module_function - - # @api private - # Determines where we add `should` and `should_not`. - def default_should_host - @default_should_host ||= ::Object.ancestors.last - end - - # @api private - # Instructs rspec-expectations to warn on first usage of `should` or `should_not`. - # Enabled by default. This is largely here to facilitate testing. - def warn_about_should! - @warn_about_should = true - end - - # @api private - # Generates a deprecation warning for the given method if no warning - # has already been issued. - def warn_about_should_unless_configured(method_name) - return unless @warn_about_should - - RSpec.deprecate( - "Using `#{method_name}` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax", - :replacement => "the new `:expect` syntax or explicitly enable `:should`" - ) - - @warn_about_should = false - end - - # @api private - # Enables the `should` syntax. - def enable_should(syntax_host=default_should_host) - @warn_about_should = false if syntax_host == default_should_host - return if should_enabled?(syntax_host) - - syntax_host.module_exec do - def should(matcher=nil, message=nil, &block) - ::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__) - ::RSpec::Expectations::PositiveExpectationHandler.handle_matcher(self, matcher, message, &block) - end - - def should_not(matcher=nil, message=nil, &block) - ::RSpec::Expectations::Syntax.warn_about_should_unless_configured(__method__) - ::RSpec::Expectations::NegativeExpectationHandler.handle_matcher(self, matcher, message, &block) - end - end - end - - # @api private - # Disables the `should` syntax. - def disable_should(syntax_host=default_should_host) - return unless should_enabled?(syntax_host) - - syntax_host.module_exec do - undef should - undef should_not - end - end - - # @api private - # Enables the `expect` syntax. - def enable_expect(syntax_host=::RSpec::Matchers) - return if expect_enabled?(syntax_host) - - syntax_host.module_exec do - def expect(value=::RSpec::Expectations::ExpectationTarget::UndefinedValue, &block) - ::RSpec::Expectations::ExpectationTarget.for(value, block) - end - end - end - - # @api private - # Disables the `expect` syntax. - def disable_expect(syntax_host=::RSpec::Matchers) - return unless expect_enabled?(syntax_host) - - syntax_host.module_exec do - undef expect - end - end - - # @api private - # Indicates whether or not the `should` syntax is enabled. - def should_enabled?(syntax_host=default_should_host) - syntax_host.method_defined?(:should) - end - - # @api private - # Indicates whether or not the `expect` syntax is enabled. - def expect_enabled?(syntax_host=::RSpec::Matchers) - syntax_host.method_defined?(:expect) - end - end - end -end - -if defined?(BasicObject) - # The legacy `:should` syntax adds the following methods directly to - # `BasicObject` so that they are available off of any object. Note, however, - # that this syntax does not always play nice with delegate/proxy objects. - # We recommend you use the non-monkeypatching `:expect` syntax instead. - class BasicObject - # @method should - # Passes if `matcher` returns true. Available on every `Object`. - # @example - # actual.should eq expected - # actual.should match /expression/ - # @param [Matcher] - # matcher - # @param [String] message optional message to display when the expectation fails - # @return [Boolean] true if the expectation succeeds (else raises) - # @note This is only available when you have enabled the `:should` syntax. - # @see RSpec::Matchers - - # @method should_not - # Passes if `matcher` returns false. Available on every `Object`. - # @example - # actual.should_not eq expected - # @param [Matcher] - # matcher - # @param [String] message optional message to display when the expectation fails - # @return [Boolean] false if the negative expectation succeeds (else raises) - # @note This is only available when you have enabled the `:should` syntax. - # @see RSpec::Matchers - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/version.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/version.rb deleted file mode 100644 index 9548a5a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/expectations/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -module RSpec - module Expectations - # @private - module Version - STRING = '3.0.3' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers.rb deleted file mode 100644 index b122083..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers.rb +++ /dev/null @@ -1,921 +0,0 @@ -require 'rspec/support' -RSpec::Support.define_optimized_require_for_rspec(:matchers) { |f| require_relative(f) } - -%w[ - pretty - composable - built_in - generated_descriptions - dsl - matcher_delegator - aliased_matcher -].each { |file| RSpec::Support.require_rspec_matchers(file) } - -# RSpec's top level namespace. All of rspec-expectations is contained -# in the `RSpec::Expectations` and `RSpec::Matchers` namespaces. -module RSpec - # RSpec::Matchers provides a number of useful matchers we use to define - # expectations. A matcher is any object that responds to the following: - # - # matches?(actual) - # failure_message - # - # These methods are also part of the matcher protocol, but are optional: - # - # does_not_match?(actual) - # failure_message_when_negated - # description - # supports_block_expectations? - # - # ## Predicates - # - # In addition to matchers that are defined explicitly, RSpec will create - # custom matchers on the fly for any arbitrary predicate, giving your specs a - # much more natural language feel. - # - # A Ruby predicate is a method that ends with a "?" and returns true or false. - # Common examples are `empty?`, `nil?`, and `instance_of?`. - # - # All you need to do is write `expect(..).to be_` followed by the predicate - # without the question mark, and RSpec will figure it out from there. - # For example: - # - # expect([]).to be_empty # => [].empty?() | passes - # expect([]).not_to be_empty # => [].empty?() | fails - # - # In addtion to prefixing the predicate matchers with "be_", you can also use "be_a_" - # and "be_an_", making your specs read much more naturally: - # - # expect("a string").to be_an_instance_of(String) # =>"a string".instance_of?(String) # passes - # - # expect(3).to be_a_kind_of(Fixnum) # => 3.kind_of?(Numeric) | passes - # expect(3).to be_a_kind_of(Numeric) # => 3.kind_of?(Numeric) | passes - # expect(3).to be_an_instance_of(Fixnum) # => 3.instance_of?(Fixnum) | passes - # expect(3).not_to be_an_instance_of(Numeric) # => 3.instance_of?(Numeric) | fails - # - # RSpec will also create custom matchers for predicates like `has_key?`. To - # use this feature, just state that the object should have_key(:key) and RSpec will - # call has_key?(:key) on the target. For example: - # - # expect(:a => "A").to have_key(:a) - # expect(:a => "A").to have_key(:b) # fails - # - # You can use this feature to invoke any predicate that begins with "has_", whether it is - # part of the Ruby libraries (like `Hash#has_key?`) or a method you wrote on your own class. - # - # Note that RSpec does not provide composable aliases for these dynamic predicate - # matchers. You can easily define your own aliases, though: - # - # RSpec::Matchers.alias_matcher :a_user_who_is_an_admin, :be_an_admin - # expect(user_list).to include(a_user_who_is_an_admin) - # - # ## Custom Matchers - # - # When you find that none of the stock matchers provide a natural feeling - # expectation, you can very easily write your own using RSpec's matcher DSL - # or writing one from scratch. - # - # ### Matcher DSL - # - # Imagine that you are writing a game in which players can be in various - # zones on a virtual board. To specify that bob should be in zone 4, you - # could say: - # - # expect(bob.current_zone).to eql(Zone.new("4")) - # - # But you might find it more expressive to say: - # - # expect(bob).to be_in_zone("4") - # - # and/or - # - # expect(bob).not_to be_in_zone("3") - # - # You can create such a matcher like so: - # - # RSpec::Matchers.define :be_in_zone do |zone| - # match do |player| - # player.in_zone?(zone) - # end - # end - # - # This will generate a be_in_zone method that returns a matcher - # with logical default messages for failures. You can override the failure - # messages and the generated description as follows: - # - # RSpec::Matchers.define :be_in_zone do |zone| - # match do |player| - # player.in_zone?(zone) - # end - # - # failure_message do |player| - # # generate and return the appropriate string. - # end - # - # failure_message_when_negated do |player| - # # generate and return the appropriate string. - # end - # - # description do - # # generate and return the appropriate string. - # end - # end - # - # Each of the message-generation methods has access to the block arguments - # passed to the create method (in this case, zone). The - # failure message methods (failure_message and - # failure_message_when_negated) are passed the actual value (the - # receiver of expect(..) or expect(..).not_to). - # - # ### Custom Matcher from scratch - # - # You could also write a custom matcher from scratch, as follows: - # - # class BeInZone - # def initialize(expected) - # @expected = expected - # end - # - # def matches?(target) - # @target = target - # @target.current_zone.eql?(Zone.new(@expected)) - # end - # - # def failure_message - # "expected #{@target.inspect} to be in Zone #{@expected}" - # end - # - # def failure_message_when_negated - # "expected #{@target.inspect} not to be in Zone #{@expected}" - # end - # end - # - # ... and a method like this: - # - # def be_in_zone(expected) - # BeInZone.new(expected) - # end - # - # And then expose the method to your specs. This is normally done - # by including the method and the class in a module, which is then - # included in your spec: - # - # module CustomGameMatchers - # class BeInZone - # # ... - # end - # - # def be_in_zone(expected) - # # ... - # end - # end - # - # describe "Player behaviour" do - # include CustomGameMatchers - # # ... - # end - # - # or you can include in globally in a spec_helper.rb file required - # from your spec file(s): - # - # RSpec::configure do |config| - # config.include(CustomGameMatchers) - # end - # - # ### Making custom matchers composable - # - # RSpec's built-in matchers are designed to be composed, in expressions like: - # - # expect(["barn", 2.45]).to contain_exactly( - # a_value_within(0.1).of(2.5), - # a_string_starting_with("bar") - # ) - # - # Custom matchers can easily participate in composed matcher expressions like these. - # Include {RSpec::Matchers::Composable} in your custom matcher to make it support - # being composed (matchers defined using the DSL have this included automatically). - # Within your matcher's `matches?` method (or the `match` block, if using the DSL), - # use `values_match?(expected, actual)` rather than `expected == actual`. - # Under the covers, `values_match?` is able to match arbitrary - # nested data structures containing a mix of both matchers and non-matcher objects. - # It uses `===` and `==` to perform the matching, considering the values to - # match if either returns `true`. The `Composable` mixin also provides some helper - # methods for surfacing the matcher descriptions within your matcher's description - # or failure messages. - # - # RSpec's built-in matchers each have a number of aliases that rephrase the matcher - # from a verb phrase (such as `be_within`) to a noun phrase (such as `a_value_within`), - # which reads better when the matcher is passed as an argument in a composed matcher - # expressions, and also uses the noun-phrase wording in the matcher's `description`, - # for readable failure messages. You can alias your custom matchers in similar fashion - # using {RSpec::Matchers.alias_matcher}. - module Matchers - # @method expect - # Supports `expect(actual).to matcher` syntax by wrapping `actual` in an - # `ExpectationTarget`. - # @example - # expect(actual).to eq(expected) - # expect(actual).not_to eq(expected) - # @return [ExpectationTarget] - # @see ExpectationTarget#to - # @see ExpectationTarget#not_to - - # Defines a matcher alias. The returned matcher's `description` will be overriden - # to reflect the phrasing of the new name, which will be used in failure messages - # when passed as an argument to another matcher in a composed matcher expression. - # - # @param new_name [Symbol] the new name for the matcher - # @param old_name [Symbol] the original name for the matcher - # @yield [String] optional block that, when given is used to define the overriden - # description. The yielded arg is the original description. If no block is - # provided, a default description override is used based on the old and - # new names. - # - # @example - # - # RSpec::Matchers.alias_matcher :a_list_that_sums_to, :sum_to - # sum_to(3).description # => "sum to 3" - # a_list_that_sums_to(3).description # => "a list that sums to 3" - # - # @example - # - # RSpec::Matchers.alias_matcher :a_list_sorted_by, :be_sorted_by do |description| - # description.sub("be sorted by", "a list sorted by") - # end - # - # be_sorted_by(:age).description # => "be sorted by age" - # a_list_sorted_by(:age).description # => "a list sorted by age" - # - # @!macro [attach] alias_matcher - # @!parse - # alias $1 $2 - def self.alias_matcher(new_name, old_name, &description_override) - description_override ||= lambda do |old_desc| - old_desc.gsub(Pretty.split_words(old_name), Pretty.split_words(new_name)) - end - - define_method(new_name) do |*args, &block| - matcher = __send__(old_name, *args, &block) - AliasedMatcher.new(matcher, description_override) - end - end - - # Passes if actual is truthy (anything but false or nil) - def be_truthy - BuiltIn::BeTruthy.new - end - alias_matcher :a_truthy_value, :be_truthy - - # Passes if actual is falsey (false or nil) - def be_falsey - BuiltIn::BeFalsey.new - end - alias_matcher :be_falsy, :be_falsey - alias_matcher :a_falsey_value, :be_falsey - alias_matcher :a_falsy_value, :be_falsey - - # Passes if actual is nil - def be_nil - BuiltIn::BeNil.new - end - alias_matcher :a_nil_value, :be_nil - - # @example - # expect(actual).to be_truthy - # expect(actual).to be_falsey - # expect(actual).to be_nil - # expect(actual).to be_[arbitrary_predicate](*args) - # expect(actual).not_to be_nil - # expect(actual).not_to be_[arbitrary_predicate](*args) - # - # Given true, false, or nil, will pass if actual value is true, false or - # nil (respectively). Given no args means the caller should satisfy an if - # condition (to be or not to be). - # - # Predicates are any Ruby method that ends in a "?" and returns true or - # false. Given be_ followed by arbitrary_predicate (without the "?"), - # RSpec will match convert that into a query against the target object. - # - # The arbitrary_predicate feature will handle any predicate prefixed with - # "be_an_" (e.g. be_an_instance_of), "be_a_" (e.g. be_a_kind_of) or "be_" - # (e.g. be_empty), letting you choose the prefix that best suits the - # predicate. - def be(*args) - args.empty? ? Matchers::BuiltIn::Be.new : equal(*args) - end - alias_matcher :a_value, :be - - # passes if target.kind_of?(klass) - def be_a(klass) - be_a_kind_of(klass) - end - alias_method :be_an, :be_a - - # Passes if actual.instance_of?(expected) - # - # @example - # - # expect(5).to be_an_instance_of(Fixnum) - # expect(5).not_to be_an_instance_of(Numeric) - # expect(5).not_to be_an_instance_of(Float) - def be_an_instance_of(expected) - BuiltIn::BeAnInstanceOf.new(expected) - end - alias_method :be_instance_of, :be_an_instance_of - alias_matcher :an_instance_of, :be_an_instance_of - - # Passes if actual.kind_of?(expected) - # - # @example - # - # expect(5).to be_a_kind_of(Fixnum) - # expect(5).to be_a_kind_of(Numeric) - # expect(5).not_to be_a_kind_of(Float) - def be_a_kind_of(expected) - BuiltIn::BeAKindOf.new(expected) - end - alias_method :be_kind_of, :be_a_kind_of - alias_matcher :a_kind_of, :be_a_kind_of - - # Passes if actual.between?(min, max). Works with any Comparable object, - # including String, Symbol, Time, or Numeric (Fixnum, Bignum, Integer, - # Float, Complex, and Rational). - # - # By default, `be_between` is inclusive (i.e. passes when given either the max or min value), - # but you can make it `exclusive` by chaining that off the matcher. - # - # @example - # - # expect(5).to be_between(1, 10) - # expect(11).not_to be_between(1, 10) - # expect(10).not_to be_between(1, 10).exclusive - def be_between(min, max) - BuiltIn::BeBetween.new(min, max) - end - alias_matcher :a_value_between, :be_between - - # Passes if actual == expected +/- delta - # - # @example - # - # expect(result).to be_within(0.5).of(3.0) - # expect(result).not_to be_within(0.5).of(3.0) - def be_within(delta) - BuiltIn::BeWithin.new(delta) - end - alias_matcher :a_value_within, :be_within - alias_matcher :within, :be_within - - # Applied to a proc, specifies that its execution will cause some value to - # change. - # - # @param [Object] receiver - # @param [Symbol] message the message to send the receiver - # - # You can either pass receiver and message, or a block, - # but not both. - # - # When passing a block, it must use the `{ ... }` format, not - # do/end, as `{ ... }` binds to the `change` method, whereas do/end - # would errantly bind to the `expect(..).to` or `expect(...).not_to` method. - # - # You can chain any of the following off of the end to specify details - # about the change: - # - # * `by` - # * `by_at_least` - # * `by_at_most` - # * `from` - # * `to` - # - # @example - # - # expect { - # team.add_player(player) - # }.to change(roster, :count) - # - # expect { - # team.add_player(player) - # }.to change(roster, :count).by(1) - # - # expect { - # team.add_player(player) - # }.to change(roster, :count).by_at_least(1) - # - # expect { - # team.add_player(player) - # }.to change(roster, :count).by_at_most(1) - # - # string = "string" - # expect { - # string.reverse! - # }.to change { string }.from("string").to("gnirts") - # - # string = "string" - # expect { - # string - # }.not_to change { string }.from("string") - # - # expect { - # person.happy_birthday - # }.to change(person, :birthday).from(32).to(33) - # - # expect { - # employee.develop_great_new_social_networking_app - # }.to change(employee, :title).from("Mail Clerk").to("CEO") - # - # expect { - # doctor.leave_office - # }.to change(doctor, :sign).from(/is in/).to(/is out/) - # - # user = User.new(:type => "admin") - # expect { - # user.symbolize_type - # }.to change(user, :type).from(String).to(Symbol) - # - # == Notes - # - # Evaluates `receiver.message` or `block` before and after it - # evaluates the block passed to `expect`. - # - # `expect( ... ).not_to change` supports the form that specifies `from` - # (which specifies what you expect the starting, unchanged value to be) - # but does not support forms with subsequent calls to `by`, `by_at_least`, - # `by_at_most` or `to`. - def change(receiver=nil, message=nil, &block) - BuiltIn::Change.new(receiver, message, &block) - end - alias_matcher :a_block_changing, :change - alias_matcher :changing, :change - - # Passes if actual contains all of the expected regardless of order. - # This works for collections. Pass in multiple args and it will only - # pass if all args are found in collection. - # - # @note This is also available using the `=~` operator with `should`, - # but `=~` is not supported with `expect`. - # - # @note This matcher only supports positive expectations. - # `expect(...).not_to contain_exactly(other_array)` is not supported. - # - # @example - # - # expect([1, 2, 3]).to contain_exactly(1, 2, 3) - # expect([1, 2, 3]).to contain_exactly(1, 3, 2) - # - # @see #match_array - def contain_exactly(*items) - BuiltIn::ContainExactly.new(items) - end - alias_matcher :a_collection_containing_exactly, :contain_exactly - alias_matcher :containing_exactly, :contain_exactly - - # Passes if actual covers expected. This works for - # Ranges. You can also pass in multiple args - # and it will only pass if all args are found in Range. - # - # @example - # expect(1..10).to cover(5) - # expect(1..10).to cover(4, 6) - # expect(1..10).to cover(4, 6, 11) # fails - # expect(1..10).not_to cover(11) - # expect(1..10).not_to cover(5) # fails - # - # ### Warning:: Ruby >= 1.9 only - def cover(*values) - BuiltIn::Cover.new(*values) - end - alias_matcher :a_range_covering, :cover - alias_matcher :covering, :cover - - # Matches if the actual value ends with the expected value(s). In the case - # of a string, matches against the last `expected.length` characters of the - # actual string. In the case of an array, matches against the last - # `expected.length` elements of the actual array. - # - # @example - # - # expect("this string").to end_with "string" - # expect([0, 1, 2, 3, 4]).to end_with 4 - # expect([0, 2, 3, 4, 4]).to end_with 3, 4 - def end_with(*expected) - BuiltIn::EndWith.new(*expected) - end - alias_matcher :a_collection_ending_with, :end_with - alias_matcher :a_string_ending_with, :end_with - alias_matcher :ending_with, :end_with - - # Passes if actual == expected. - # - # See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more - # information about equality in Ruby. - # - # @example - # - # expect(5).to eq(5) - # expect(5).not_to eq(3) - def eq(expected) - BuiltIn::Eq.new(expected) - end - alias_matcher :an_object_eq_to, :eq - alias_matcher :eq_to, :eq - - # Passes if `actual.eql?(expected)` - # - # See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more - # information about equality in Ruby. - # - # @example - # - # expect(5).to eql(5) - # expect(5).not_to eql(3) - def eql(expected) - BuiltIn::Eql.new(expected) - end - alias_matcher :an_object_eql_to, :eql - alias_matcher :eql_to, :eql - - # Passes if actual.equal?(expected) (object identity). - # - # See http://www.ruby-doc.org/core/classes/Object.html#M001057 for more - # information about equality in Ruby. - # - # @example - # - # expect(5).to equal(5) # Fixnums are equal - # expect("5").not_to equal("5") # Strings that look the same are not the same object - def equal(expected) - BuiltIn::Equal.new(expected) - end - alias_matcher :an_object_equal_to, :equal - alias_matcher :equal_to, :equal - - # Passes if `actual.exist?` or `actual.exists?` - # - # @example - # expect(File).to exist("path/to/file") - def exist(*args) - BuiltIn::Exist.new(*args) - end - alias_matcher :an_object_existing, :exist - alias_matcher :existing, :exist - - # Passes if actual includes expected. This works for - # collections and Strings. You can also pass in multiple args - # and it will only pass if all args are found in collection. - # - # @example - # - # expect([1,2,3]).to include(3) - # expect([1,2,3]).to include(2,3) - # expect([1,2,3]).to include(2,3,4) # fails - # expect([1,2,3]).not_to include(4) - # expect("spread").to include("read") - # expect("spread").not_to include("red") - def include(*expected) - BuiltIn::Include.new(*expected) - end - alias_matcher :a_collection_including, :include - alias_matcher :a_string_including, :include - alias_matcher :a_hash_including, :include - alias_matcher :including, :include - - # Passes if actual all expected objects pass. This works for - # any enumerable object. - # - # @example - # - # expect([1, 3, 5]).to all be_odd - # expect([1, 3, 6]).to all be_odd # fails - # - # @note The negative form `not_to all` is not supported. Instead - # use `not_to include` or pass a negative form of a matcher - # as the argument (e.g. `all exclude(:foo)`). - # - # @note You can also use this with compound matchers as well. - # - # @example - # expect([1, 3, 5]).to all( be_odd.and be_an(Integer) ) - def all(expected) - BuiltIn::All.new(expected) - end - - # Given a `Regexp` or `String`, passes if `actual.match(pattern)` - # Given an arbitrary nested data structure (e.g. arrays and hashes), - # matches if `expected === actual` || `actual == expected` for each - # pair of elements. - # - # @example - # - # expect(email).to match(/^([^\s]+)((?:[-a-z0-9]+\.)+[a-z]{2,})$/i) - # expect(email).to match("@example.com") - # - # @example - # - # hash = { - # :a => { - # :b => ["foo", 5], - # :c => { :d => 2.05 } - # } - # } - # - # expect(hash).to match( - # :a => { - # :b => a_collection_containing_exactly( - # a_string_starting_with("f"), - # an_instance_of(Fixnum) - # ), - # :c => { :d => (a_value < 3) } - # } - # ) - # - # @note The `match_regex` alias is deprecated and is not recommended for use. - # It was added in 2.12.1 to facilitate its use from within custom - # matchers (due to how the custom matcher DSL was evaluated in 2.x, - # `match` could not be used there), but is no longer needed in 3.x. - def match(expected) - BuiltIn::Match.new(expected) - end - alias_matcher :match_regex, :match - alias_matcher :an_object_matching, :match - alias_matcher :a_string_matching, :match - alias_matcher :matching, :match - - # An alternate form of `contain_exactly` that accepts - # the expected contents as a single array arg rather - # that splatted out as individual items. - # - # @example - # - # expect(results).to contain_exactly(1, 2) - # # is identical to: - # expect(results).to match_array([1, 2]) - # - # @see #contain_exactly - def match_array(items) - contain_exactly(*items) - end - - # With no arg, passes if the block outputs `to_stdout` or `to_stderr`. - # With a string, passes if the blocks outputs that specific string `to_stdout` or `to_stderr`. - # With a regexp or matcher, passes if the blocks outputs a string `to_stdout` or `to_stderr` that matches. - # - # @example - # - # expect { print 'foo' }.to output.to_stdout - # expect { print 'foo' }.to output('foo').to_stdout - # expect { print 'foo' }.to output(/foo/).to_stdout - # - # expect { do_something }.to_not output.to_stdout - # - # expect { warn('foo') }.to output.to_stderr - # expect { warn('foo') }.to output('foo').to_stderr - # expect { warn('foo') }.to output(/foo/).to_stderr - # - # expect { do_something }.to_not output.to_stderr - # - # @note This matcher works by temporarily replacing `$stdout` or `$stderr`, - # so it's not able to intercept stream output that explicitly uses `STDOUT`/`STDERR` - # or that uses a reference to `$stdout`/`$stderr` that was stored before the - # matcher is used. - def output(expected=nil) - BuiltIn::Output.new(expected) - end - alias_matcher :a_block_outputting, :output - - # With no args, matches if any error is raised. - # With a named error, matches only if that specific error is raised. - # With a named error and messsage specified as a String, matches only if both match. - # With a named error and messsage specified as a Regexp, matches only if both match. - # Pass an optional block to perform extra verifications on the exception matched - # - # @example - # - # expect { do_something_risky }.to raise_error - # expect { do_something_risky }.to raise_error(PoorRiskDecisionError) - # expect { do_something_risky }.to raise_error(PoorRiskDecisionError) { |error| expect(error.data).to eq 42 } - # expect { do_something_risky }.to raise_error(PoorRiskDecisionError, "that was too risky") - # expect { do_something_risky }.to raise_error(PoorRiskDecisionError, /oo ri/) - # - # expect { do_something_risky }.not_to raise_error - def raise_error(error=Exception, message=nil, &block) - BuiltIn::RaiseError.new(error, message, &block) - end - alias_method :raise_exception, :raise_error - - alias_matcher :a_block_raising, :raise_error do |desc| - desc.sub("raise", "a block raising") - end - - alias_matcher :raising, :raise_error do |desc| - desc.sub("raise", "raising") - end - - # Matches if the target object responds to all of the names - # provided. Names can be Strings or Symbols. - # - # @example - # - # expect("string").to respond_to(:length) - # - def respond_to(*names) - BuiltIn::RespondTo.new(*names) - end - alias_matcher :an_object_responding_to, :respond_to - alias_matcher :responding_to, :respond_to - - # Passes if the submitted block returns true. Yields target to the - # block. - # - # Generally speaking, this should be thought of as a last resort when - # you can't find any other way to specify the behaviour you wish to - # specify. - # - # If you do find yourself in such a situation, you could always write - # a custom matcher, which would likely make your specs more expressive. - # - # @example - # - # expect(5).to satisfy { |n| n > 3 } - def satisfy(&block) - BuiltIn::Satisfy.new(&block) - end - alias_matcher :an_object_satisfying, :satisfy - alias_matcher :satisfying, :satisfy - - # Matches if the actual value starts with the expected value(s). In the - # case of a string, matches against the first `expected.length` characters - # of the actual string. In the case of an array, matches against the first - # `expected.length` elements of the actual array. - # - # @example - # - # expect("this string").to start_with "this s" - # expect([0, 1, 2, 3, 4]).to start_with 0 - # expect([0, 2, 3, 4, 4]).to start_with 0, 1 - def start_with(*expected) - BuiltIn::StartWith.new(*expected) - end - alias_matcher :a_collection_starting_with, :start_with - alias_matcher :a_string_starting_with, :start_with - alias_matcher :starting_with, :start_with - - # Given no argument, matches if a proc throws any Symbol. - # - # Given a Symbol, matches if the given proc throws the specified Symbol. - # - # Given a Symbol and an arg, matches if the given proc throws the - # specified Symbol with the specified arg. - # - # @example - # - # expect { do_something_risky }.to throw_symbol - # expect { do_something_risky }.to throw_symbol(:that_was_risky) - # expect { do_something_risky }.to throw_symbol(:that_was_risky, 'culprit') - # - # expect { do_something_risky }.not_to throw_symbol - # expect { do_something_risky }.not_to throw_symbol(:that_was_risky) - # expect { do_something_risky }.not_to throw_symbol(:that_was_risky, 'culprit') - def throw_symbol(expected_symbol=nil, expected_arg=nil) - BuiltIn::ThrowSymbol.new(expected_symbol, expected_arg) - end - - alias_matcher :a_block_throwing, :throw_symbol do |desc| - desc.sub("throw", "a block throwing") - end - - alias_matcher :throwing, :throw_symbol do |desc| - desc.sub("throw", "throwing") - end - - # Passes if the method called in the expect block yields, regardless - # of whether or not arguments are yielded. - # - # @example - # - # expect { |b| 5.tap(&b) }.to yield_control - # expect { |b| "a".to_sym(&b) }.not_to yield_control - # - # @note Your expect block must accept a parameter and pass it on to - # the method-under-test as a block. - # @note This matcher is not designed for use with methods that yield - # multiple times. - def yield_control - BuiltIn::YieldControl.new - end - alias_matcher :a_block_yielding_control, :yield_control - alias_matcher :yielding_control, :yield_control - - # Passes if the method called in the expect block yields with - # no arguments. Fails if it does not yield, or yields with arguments. - # - # @example - # - # expect { |b| User.transaction(&b) }.to yield_with_no_args - # expect { |b| 5.tap(&b) }.not_to yield_with_no_args # because it yields with `5` - # expect { |b| "a".to_sym(&b) }.not_to yield_with_no_args # because it does not yield - # - # @note Your expect block must accept a parameter and pass it on to - # the method-under-test as a block. - # @note This matcher is not designed for use with methods that yield - # multiple times. - def yield_with_no_args - BuiltIn::YieldWithNoArgs.new - end - alias_matcher :a_block_yielding_with_no_args, :yield_with_no_args - alias_matcher :yielding_with_no_args, :yield_with_no_args - - # Given no arguments, matches if the method called in the expect - # block yields with arguments (regardless of what they are or how - # many there are). - # - # Given arguments, matches if the method called in the expect block - # yields with arguments that match the given arguments. - # - # Argument matching is done using `===` (the case match operator) - # and `==`. If the expected and actual arguments match with either - # operator, the matcher will pass. - # - # @example - # - # expect { |b| 5.tap(&b) }.to yield_with_args # because #tap yields an arg - # expect { |b| 5.tap(&b) }.to yield_with_args(5) # because 5 == 5 - # expect { |b| 5.tap(&b) }.to yield_with_args(Fixnum) # because Fixnum === 5 - # expect { |b| File.open("f.txt", &b) }.to yield_with_args(/txt/) # because /txt/ === "f.txt" - # - # expect { |b| User.transaction(&b) }.not_to yield_with_args # because it yields no args - # expect { |b| 5.tap(&b) }.not_to yield_with_args(1, 2, 3) - # - # @note Your expect block must accept a parameter and pass it on to - # the method-under-test as a block. - # @note This matcher is not designed for use with methods that yield - # multiple times. - def yield_with_args(*args) - BuiltIn::YieldWithArgs.new(*args) - end - alias_matcher :a_block_yielding_with_args, :yield_with_args - alias_matcher :yielding_with_args, :yield_with_args - - # Designed for use with methods that repeatedly yield (such as - # iterators). Passes if the method called in the expect block yields - # multiple times with arguments matching those given. - # - # Argument matching is done using `===` (the case match operator) - # and `==`. If the expected and actual arguments match with either - # operator, the matcher will pass. - # - # @example - # - # expect { |b| [1, 2, 3].each(&b) }.to yield_successive_args(1, 2, 3) - # expect { |b| { :a => 1, :b => 2 }.each(&b) }.to yield_successive_args([:a, 1], [:b, 2]) - # expect { |b| [1, 2, 3].each(&b) }.not_to yield_successive_args(1, 2) - # - # @note Your expect block must accept a parameter and pass it on to - # the method-under-test as a block. - def yield_successive_args(*args) - BuiltIn::YieldSuccessiveArgs.new(*args) - end - alias_matcher :a_block_yielding_successive_args, :yield_successive_args - alias_matcher :yielding_successive_args, :yield_successive_args - - # Delegates to {RSpec::Expectations.configuration}. - # This is here because rspec-core's `expect_with` option - # looks for a `configuration` method on the mixin - # (`RSpec::Matchers`) to yield to a block. - # @return [RSpec::Expectations::Configuration] the configuration object - def self.configuration - Expectations.configuration - end - - private - - BE_PREDICATE_REGEX = /^(be_(?:an?_)?)(.*)/ - HAS_REGEX = /^(?:have_)(.*)/ - - def method_missing(method, *args, &block) - case method.to_s - when BE_PREDICATE_REGEX - BuiltIn::BePredicate.new(method, *args, &block) - when HAS_REGEX - BuiltIn::Has.new(method, *args, &block) - else - super - end - end - - # @api private - def self.is_a_matcher?(obj) - return true if ::RSpec::Matchers::BuiltIn::BaseMatcher === obj - return false if obj.respond_to?(:i_respond_to_everything_so_im_not_really_a_matcher) - return false unless obj.respond_to?(:matches?) - - obj.respond_to?(:failure_message) || - obj.respond_to?(:failure_message_for_should) # support legacy matchers - end - - # @api private - def self.is_a_describable_matcher?(obj) - is_a_matcher?(obj) && obj.respond_to?(:description) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/aliased_matcher.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/aliased_matcher.rb deleted file mode 100644 index 1fed4c0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/aliased_matcher.rb +++ /dev/null @@ -1,41 +0,0 @@ -module RSpec - module Matchers - # Decorator that wraps a matcher and overrides `description` - # using the provided block in order to support an alias - # of a matcher. This is intended for use when composing - # matchers, so that you can use an expression like - # `include( a_value_within(0.1).of(3) )` rather than - # `include( be_within(0.1).of(3) )`, and have the corresponding - # description read naturally. - # - # @api private - class AliasedMatcher < MatcherDelegator - def initialize(base_matcher, description_block) - @description_block = description_block - super(base_matcher) - end - - # Forward messages on to the wrapped matcher. - # Since many matchers provide a fluent interface - # (e.g. `a_value_within(0.1).of(3)`), we need to wrap - # the returned value if it responds to `description`, - # so that our override can be applied when it is eventually - # used. - def method_missing(*) - return_val = super - return return_val unless return_val.respond_to?(:description) - AliasedMatcher.new(return_val, @description_block) - end - - # Provides the description of the aliased matcher. Aliased matchers - # are designed to behave identically to the original matcher except - # for this method. The description is different to reflect the aliased - # name. - # - # @api private - def description - @description_block.call(super) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in.rb deleted file mode 100644 index cf257ae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in.rb +++ /dev/null @@ -1,51 +0,0 @@ -RSpec::Support.require_rspec_matchers "built_in/base_matcher" - -module RSpec - module Matchers - # Container module for all built-in matchers. The matcher classes are here - # (rather than directly under `RSpec::Matchers`) in order to prevent name - # collisions, since `RSpec::Matchers` gets included into the user's namespace. - # - # Autoloading is used to delay when the matcher classes get loaded, allowing - # rspec-matchers to boot faster, and avoiding loading matchers the user is - # not using. - module BuiltIn - autoload :BeAKindOf, 'rspec/matchers/built_in/be_kind_of' - autoload :BeAnInstanceOf, 'rspec/matchers/built_in/be_instance_of' - autoload :BeBetween, 'rspec/matchers/built_in/be_between' - autoload :Be, 'rspec/matchers/built_in/be' - autoload :BeComparedTo, 'rspec/matchers/built_in/be' - autoload :BeFalsey, 'rspec/matchers/built_in/be' - autoload :BeNil, 'rspec/matchers/built_in/be' - autoload :BePredicate, 'rspec/matchers/built_in/be' - autoload :BeTruthy, 'rspec/matchers/built_in/be' - autoload :BeWithin, 'rspec/matchers/built_in/be_within' - autoload :Change, 'rspec/matchers/built_in/change' - autoload :Compound, 'rspec/matchers/built_in/compound' - autoload :ContainExactly, 'rspec/matchers/built_in/contain_exactly' - autoload :Cover, 'rspec/matchers/built_in/cover' - autoload :EndWith, 'rspec/matchers/built_in/start_and_end_with' - autoload :Eq, 'rspec/matchers/built_in/eq' - autoload :Eql, 'rspec/matchers/built_in/eql' - autoload :Equal, 'rspec/matchers/built_in/equal' - autoload :Exist, 'rspec/matchers/built_in/exist' - autoload :Has, 'rspec/matchers/built_in/has' - autoload :Include, 'rspec/matchers/built_in/include' - autoload :All, 'rspec/matchers/built_in/all' - autoload :Match, 'rspec/matchers/built_in/match' - autoload :NegativeOperatorMatcher, 'rspec/matchers/built_in/operators' - autoload :OperatorMatcher, 'rspec/matchers/built_in/operators' - autoload :Output, 'rspec/matchers/built_in/output' - autoload :PositiveOperatorMatcher, 'rspec/matchers/built_in/operators' - autoload :RaiseError, 'rspec/matchers/built_in/raise_error' - autoload :RespondTo, 'rspec/matchers/built_in/respond_to' - autoload :Satisfy, 'rspec/matchers/built_in/satisfy' - autoload :StartWith, 'rspec/matchers/built_in/start_and_end_with' - autoload :ThrowSymbol, 'rspec/matchers/built_in/throw_symbol' - autoload :YieldControl, 'rspec/matchers/built_in/yield' - autoload :YieldSuccessiveArgs, 'rspec/matchers/built_in/yield' - autoload :YieldWithArgs, 'rspec/matchers/built_in/yield' - autoload :YieldWithNoArgs, 'rspec/matchers/built_in/yield' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/all.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/all.rb deleted file mode 100644 index 24c8011..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/all.rb +++ /dev/null @@ -1,76 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `all`. - # Not intended to be instantiated directly. - class All < BaseMatcher - # @private - attr_reader :matcher, :failed_objects - - def initialize(matcher) - @matcher = matcher - @failed_objects = {} - end - - # @private - def does_not_match?(_actual) - raise NotImplementedError, '`expect().not_to all( matcher )` is not supported.' - end - - # @api private - # @return [String] - def failure_message - all_messages = [improve_hash_formatting(super)] - failed_objects.each do |index, matcher_failure_message| - all_messages << failure_message_for_item(index, matcher_failure_message) - end - all_messages.join("\n\n") - end - - # @api private - # @return [String] - def description - described_items = surface_descriptions_in(matcher) - improve_hash_formatting "all#{to_sentence(described_items)}" - end - - private - - def match(_expected, _actual) - index_failed_objects - failed_objects.empty? - end - - def index_failed_objects - actual.each_with_index do |actual_item, index| - cloned_matcher = matcher.clone - matches = cloned_matcher.matches?(actual_item) - failed_objects[index] = cloned_matcher.failure_message unless matches - end - end - - def failure_message_for_item(index, failure_message) - failure_message = indent_multiline_message(add_new_line_if_needed(failure_message)) - indent_multiline_message("object at index #{index} failed to match:#{failure_message}") - end - - def add_new_line_if_needed(message) - message.start_with?("\n") ? message : "\n#{message}" - end - - def indent_multiline_message(message) - message = message.sub(/\n+\z/, '') - message.lines.map do |line| - line =~ /\S/ ? ' ' + line : line - end.join - end - - def initialize_copy(other) - @matcher = @matcher.clone - super - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/base_matcher.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/base_matcher.rb deleted file mode 100644 index 2207002..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/base_matcher.rb +++ /dev/null @@ -1,115 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # - # Used _internally_ as a base class for matchers that ship with - # rspec-expectations and rspec-rails. - # - # ### Warning: - # - # This class is for internal use, and subject to change without notice. We - # strongly recommend that you do not base your custom matchers on this - # class. If/when this changes, we will announce it and remove this warning. - class BaseMatcher - include RSpec::Matchers::Pretty - include RSpec::Matchers::Composable - - # @api private - # Used to detect when no arg is passed to `initialize`. - # `nil` cannot be used because it's a valid value to pass. - UNDEFINED = Object.new.freeze - - # @private - attr_reader :actual, :expected, :rescued_exception - - def initialize(expected=UNDEFINED) - @expected = expected unless UNDEFINED.equal?(expected) - end - - # @api private - # Indicates if the match is successful. Delegates to `match`, which - # should be defined on a subclass. Takes care of consistently - # initializing the `actual` attribute. - def matches?(actual) - @actual = actual - match(expected, actual) - end - - # @api private - # Used to wrap a block of code that will indicate failure by - # raising one of the named exceptions. - # - # This is used by rspec-rails for some of its matchers that - # wrap rails' assertions. - def match_unless_raises(*exceptions) - exceptions.unshift Exception if exceptions.empty? - begin - yield - true - rescue *exceptions => @rescued_exception - false - end - end - - # @api private - # Provides a good generic failure message. Based on `description`. - # When subclassing, if you are not satisfied with this failure message - # you often only need to override `description`. - # @return [String] - def failure_message - assert_ivars :@actual - "expected #{@actual.inspect} to #{description}" - end - - # @api private - # Provides a good generic negative failure message. Based on `description`. - # When subclassing, if you are not satisfied with this failure message - # you often only need to override `description`. - # @return [String] - def failure_message_when_negated - assert_ivars :@actual - "expected #{@actual.inspect} not to #{description}" - end - - # @api private - # Generates a "pretty" description using the logic in {Pretty}. - # @return [String] - def description - return name_to_sentence unless defined?(@expected) - "#{name_to_sentence}#{to_sentence @expected}" - end - - # @api private - # Matchers are not diffable by default. Override this to make your - # subclass diffable. - def diffable? - false - end - - # @api private - # Most matchers are value matchers (i.e. meant to work with `expect(value)`) - # rather than block matchers (i.e. meant to work with `expect { }`), so - # this defaults to false. Block matchers must override this to return true. - def supports_block_expectations? - false - end - - private - - def assert_ivars(*expected_ivars) - return unless (expected_ivars - present_ivars).any? - raise "#{self.class.name} needs to supply#{to_sentence expected_ivars}" - end - - if RUBY_VERSION.to_f < 1.9 - def present_ivars - instance_variables.map { |v| v.to_sym } - end - else - alias present_ivars instance_variables - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be.rb deleted file mode 100644 index 5339af1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be.rb +++ /dev/null @@ -1,277 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `be_truthy`. - # Not intended to be instantiated directly. - class BeTruthy < BaseMatcher - # @api private - # @return [String] - def failure_message - "expected: truthy value\n got: #{actual.inspect}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected: falsey value\n got: #{actual.inspect}" - end - - private - - def match(_, actual) - !!actual - end - end - - # @api private - # Provides the implementation for `be_falsey`. - # Not intended to be instantiated directly. - class BeFalsey < BaseMatcher - # @api private - # @return [String] - def failure_message - "expected: falsey value\n got: #{actual.inspect}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected: truthy value\n got: #{actual.inspect}" - end - - private - - def match(_, actual) - !actual - end - end - - # @api private - # Provides the implementation for `be_nil`. - # Not intended to be instantiated directly. - class BeNil < BaseMatcher - # @api private - # @return [String] - def failure_message - "expected: nil\n got: #{actual.inspect}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected: not nil\n got: nil" - end - - private - - def match(_, actual) - actual.nil? - end - end - - # @private - module BeHelpers - private - - def args_to_s - @args.empty? ? "" : parenthesize(inspected_args.join(', ')) - end - - def parenthesize(string) - "(#{string})" - end - - def inspected_args - @args.map { |a| a.inspect } - end - - def expected_to_sentence - split_words(@expected) - end - - def args_to_sentence - to_sentence(@args) - end - end - - # @api private - # Provides the implementation for `be`. - # Not intended to be instantiated directly. - class Be < BaseMatcher - include BeHelpers - - def initialize(*args) - @args = args - end - - # @api private - # @return [String] - def failure_message - "expected #{@actual.inspect} to evaluate to true" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected #{@actual.inspect} to evaluate to false" - end - - [:==, :<, :<=, :>=, :>, :===, :=~].each do |operator| - define_method operator do |operand| - BeComparedTo.new(operand, operator) - end - end - - private - - def match(_, actual) - !!actual - end - end - - # @api private - # Provides the implementation of `be value`. - # Not intended to be instantiated directly. - class BeComparedTo < BaseMatcher - include BeHelpers - - def initialize(operand, operator) - @expected, @operator = operand, operator - @args = [] - end - - def matches?(actual) - @actual = actual - @actual.__send__ @operator, @expected - end - - # @api private - # @return [String] - def failure_message - "expected: #{@operator} #{@expected.inspect}\n got: #{@operator.to_s.gsub(/./, ' ')} #{@actual.inspect}" - end - - # @api private - # @return [String] - def failure_message_when_negated - message = "`expect(#{@actual.inspect}).not_to be #{@operator} #{@expected.inspect}`" - if [:<, :>, :<=, :>=].include?(@operator) - message + " not only FAILED, it is a bit confusing." - else - message - end - end - - # @api private - # @return [String] - def description - "be #{@operator} #{expected_to_sentence}#{args_to_sentence}" - end - end - - # @api private - # Provides the implementation of `be_`. - # Not intended to be instantiated directly. - class BePredicate < BaseMatcher - include BeHelpers - - def initialize(*args, &block) - @expected = parse_expected(args.shift) - @args = args - @block = block - end - - def matches?(actual, &block) - @actual = actual - @block ||= block - predicate_accessible? && predicate_matches? - end - - def does_not_match?(actual, &block) - @actual = actual - @block ||= block - predicate_accessible? && !predicate_matches? - end - - # @api private - # @return [String] - def failure_message - failure_message_expecting(true) - end - - # @api private - # @return [String] - def failure_message_when_negated - failure_message_expecting(false) - end - - # @api private - # @return [String] - def description - "#{prefix_to_sentence}#{expected_to_sentence}#{args_to_sentence}" - end - - private - - def predicate_accessible? - !private_predicate? && predicate_exists? - end - - # support 1.8.7, evaluate once at load time for performance - if String === methods.first - def private_predicate? - @actual.private_methods.include? predicate.to_s - end - else - def private_predicate? - @actual.private_methods.include? predicate - end - end - - def predicate_exists? - actual.respond_to?(predicate) || actual.respond_to?(present_tense_predicate) - end - - def predicate_matches? - method_name = actual.respond_to?(predicate) ? predicate : present_tense_predicate - @predicate_matches = actual.__send__(method_name, *@args, &@block) - end - - def predicate - :"#{@expected}?" - end - - def present_tense_predicate - :"#{@expected}s?" - end - - def parse_expected(expected) - @prefix, expected = prefix_and_expected(expected) - expected - end - - def prefix_and_expected(symbol) - Matchers::BE_PREDICATE_REGEX.match(symbol.to_s).captures.compact - end - - def prefix_to_sentence - split_words(@prefix) - end - - def failure_message_expecting(value) - validity_message || - "expected `#{@actual.inspect}.#{predicate}#{args_to_s}` to return #{value}, got #{@predicate_matches.inspect}" - end - - def validity_message - if private_predicate? - "expected #{@actual} to respond to `#{predicate}` but `#{predicate}` is a private method" - elsif !predicate_exists? - "expected #{@actual} to respond to `#{predicate}`" - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_between.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_between.rb deleted file mode 100644 index 58c6219..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_between.rb +++ /dev/null @@ -1,77 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `be_between`. - # Not intended to be instantiated directly. - class BeBetween < BaseMatcher - def initialize(min, max) - @min, @max = min, max - inclusive - end - - # @api public - # Makes the between comparison inclusive. - # - # @example - # expect(3).to be_between(2, 3).inclusive - # - # @note The matcher is inclusive by default; this simply provides - # a way to be more explicit about it. - def inclusive - @less_than_operator = :<= - @greater_than_operator = :>= - @mode = :inclusive - self - end - - # @api public - # Makes the between comparison exclusive. - # - # @example - # expect(3).to be_between(2, 4).exclusive - def exclusive - @less_than_operator = :< - @greater_than_operator = :> - @mode = :exclusive - self - end - - # @api private - # @return [Boolean] - def matches?(actual) - @actual = actual - comparable? && compare - rescue ArgumentError - false - end - - # @api private - # @return [String] - def failure_message - "#{super}#{not_comparable_clause}" - end - - # @api private - # @return [String] - def description - "be between #{@min.inspect} and #{@max.inspect} (#{@mode})" - end - - private - - def comparable? - @actual.respond_to?(@less_than_operator) && @actual.respond_to?(@greater_than_operator) - end - - def not_comparable_clause - ", but it does not respond to `#{@less_than_operator}` and `#{@greater_than_operator}`" unless comparable? - end - - def compare - @actual.__send__(@greater_than_operator, @min) && @actual.__send__(@less_than_operator, @max) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_instance_of.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_instance_of.rb deleted file mode 100644 index c6968f1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_instance_of.rb +++ /dev/null @@ -1,22 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `be_an_instance_of`. - # Not intended to be instantiated directly. - class BeAnInstanceOf < BaseMatcher - # @api private - # @return [String] - def description - "be an instance of #{expected}" - end - - private - - def match(expected, actual) - actual.instance_of? expected - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_kind_of.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_kind_of.rb deleted file mode 100644 index eae9b26..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_kind_of.rb +++ /dev/null @@ -1,16 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `be_a_kind_of`. - # Not intended to be instantiated directly. - class BeAKindOf < BaseMatcher - private - - def match(expected, actual) - actual.kind_of? expected - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_within.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_within.rb deleted file mode 100644 index f33dc37..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/be_within.rb +++ /dev/null @@ -1,79 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `be_within`. - # Not intended to be instantiated directly. - class BeWithin - include Composable - - def initialize(delta) - @delta = delta - end - - # @api public - # Sets the expected value. - def of(expected) - @expected = expected - @tolerance = @delta - @unit = '' - self - end - - # @api public - # Sets the expected value, and makes the matcher do - # a percent comparison. - def percent_of(expected) - @expected = expected - @tolerance = @delta * @expected.abs / 100.0 - @unit = '%' - self - end - - # @private - def matches?(actual) - @actual = actual - raise needs_expected unless defined? @expected - numeric? && (@actual - @expected).abs <= @tolerance - end - - # @api private - # @return [String] - def failure_message - "expected #{@actual.inspect} to #{description}#{not_numeric_clause}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected #{@actual.inspect} not to #{description}" - end - - # @api private - # @return [String] - def description - "be within #{@delta}#{@unit} of #{@expected}" - end - - # @private - def supports_block_expectations? - false - end - - private - - def numeric? - @actual.respond_to?(:-) - end - - def needs_expected - ArgumentError.new "You must set an expected value using #of: be_within(#{@delta}).of(expected_value)" - end - - def not_numeric_clause - ", but it could not be treated as a numeric value" unless numeric? - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/change.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/change.rb deleted file mode 100644 index 45a9d97..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/change.rb +++ /dev/null @@ -1,342 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `change`. - # Not intended to be instantiated directly. - class Change - include Composable - - # @api public - # Specifies the delta of the expected change. - def by(expected_delta) - ChangeRelatively.new(@change_details, expected_delta, :by) do |actual_delta| - values_match?(expected_delta, actual_delta) - end - end - - # @api public - # Specifies a minimum delta of the expected change. - def by_at_least(minimum) - ChangeRelatively.new(@change_details, minimum, :by_at_least) do |actual_delta| - actual_delta >= minimum - end - end - - # @api public - # Specifies a maximum delta of the expected change. - def by_at_most(maximum) - ChangeRelatively.new(@change_details, maximum, :by_at_most) do |actual_delta| - actual_delta <= maximum - end - end - - # @api public - # Specifies the new value you expect. - def to(value) - ChangeToValue.new(@change_details, value) - end - - # @api public - # Specifies the original value. - def from(value) - ChangeFromValue.new(@change_details, value) - end - - # @private - def matches?(event_proc) - @event_proc = event_proc - return false unless Proc === event_proc - raise_block_syntax_error if block_given? - @change_details.perform_change(event_proc) - @change_details.changed? - end - - def does_not_match?(event_proc) - raise_block_syntax_error if block_given? - !matches?(event_proc) && Proc === event_proc - end - - # @api private - # @return [String] - def failure_message - "expected #{@change_details.message} to have changed, but #{positive_failure_reason}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected #{@change_details.message} not to have changed, but #{negative_failure_reason}" - end - - # @api private - # @return [String] - def description - "change #{@change_details.message}" - end - - # @private - def supports_block_expectations? - true - end - - private - - def initialize(receiver=nil, message=nil, &block) - @change_details = ChangeDetails.new(receiver, message, &block) - end - - def raise_block_syntax_error - raise SyntaxError, "The block passed to the `change` matcher must " \ - "use `{ ... }` instead of do/end" - end - - def positive_failure_reason - return "was not given a block" unless Proc === @event_proc - "is still #{description_of @change_details.actual_before}" - end - - def negative_failure_reason - return "was not given a block" unless Proc === @event_proc - "did change from #{description_of @change_details.actual_before} to #{description_of @change_details.actual_after}" - end - end - - # Used to specify a relative change. - # @api private - class ChangeRelatively - include Composable - - def initialize(change_details, expected_delta, relativity, &comparer) - @change_details = change_details - @expected_delta = expected_delta - @relativity = relativity - @comparer = comparer - end - - # @private - def failure_message - "expected #{@change_details.message} to have changed #{@relativity.to_s.gsub("_", " ")} #{description_of @expected_delta}, but #{failure_reason}" - end - - # @private - def matches?(event_proc) - @event_proc = event_proc - return false unless Proc === event_proc - @change_details.perform_change(event_proc) - @comparer.call(@change_details.actual_delta) - end - - # @private - def does_not_match?(_event_proc) - raise NotImplementedError, "`expect { }.not_to change { }.#{@relativity}()` is not supported" - end - - # @private - def description - "change #{@change_details.message} #{@relativity.to_s.gsub("_", " ")} #{description_of @expected_delta}" - end - - # @private - def supports_block_expectations? - true - end - - private - - def failure_reason - return "was not given a block" unless Proc === @event_proc - "was changed by #{description_of @change_details.actual_delta}" - end - end - - # @api private - # Base class for specifying a change from and/or to specific values. - class SpecificValuesChange - include Composable - # @private - MATCH_ANYTHING = ::Object.ancestors.last - - def initialize(change_details, from, to) - @change_details = change_details - @expected_before = from - @expected_after = to - end - - # @private - def matches?(event_proc) - @event_proc = event_proc - return false unless Proc === event_proc - @change_details.perform_change(event_proc) - @change_details.changed? && matches_before? && matches_after? - end - - # @private - def description - "change #{@change_details.message} #{change_description}" - end - - # @private - def failure_message - return not_given_a_block_failure unless Proc === @event_proc - return before_value_failure unless matches_before? - return did_not_change_failure unless @change_details.changed? - after_value_failure - end - - # @private - def supports_block_expectations? - true - end - - private - - def matches_before? - values_match?(@expected_before, @change_details.actual_before) - end - - def matches_after? - values_match?(@expected_after, @change_details.actual_after) - end - - def before_value_failure - "expected #{@change_details.message} to have initially been #{description_of @expected_before}, but was #{description_of @change_details.actual_before}" - end - - def after_value_failure - "expected #{@change_details.message} to have changed to #{description_of @expected_after}, but is now #{description_of @change_details.actual_after}" - end - - def did_not_change_failure - "expected #{@change_details.message} to have changed #{change_description}, but did not change" - end - - def did_change_failure - "expected #{@change_details.message} not to have changed, but did change from #{description_of @change_details.actual_before} to #{description_of @change_details.actual_after}" - end - - def not_given_a_block_failure - "expected #{@change_details.message} to have changed #{change_description}, but was not given a block" - end - end - - # @api private - # Used to specify a change from a specific value - # (and, optionally, to a specific value). - class ChangeFromValue < SpecificValuesChange - def initialize(change_details, expected_before) - @description_suffix = nil - super(change_details, expected_before, MATCH_ANYTHING) - end - - # @api public - # Specifies the new value you expect. - def to(value) - @expected_after = value - @description_suffix = " to #{description_of value}" - self - end - - # @private - def does_not_match?(event_proc) - if @description_suffix - raise NotImplementedError, "`expect { }.not_to change { }.to()` is not supported" - end - - @event_proc = event_proc - return false unless Proc === event_proc - @change_details.perform_change(event_proc) - !@change_details.changed? && matches_before? - end - - # @private - def failure_message_when_negated - return not_given_a_block_failure unless Proc === @event_proc - return before_value_failure unless matches_before? - did_change_failure - end - - private - - def change_description - "from #{description_of @expected_before}#{@description_suffix}" - end - end - - # @api private - # Used to specify a change to a specific value - # (and, optionally, from a specific value). - class ChangeToValue < SpecificValuesChange - def initialize(change_details, expected_after) - @description_suffix = nil - super(change_details, MATCH_ANYTHING, expected_after) - end - - # @api public - # Specifies the original value. - def from(value) - @expected_before = value - @description_suffix = " from #{description_of value}" - self - end - - # @private - def does_not_match?(_event_proc) - raise NotImplementedError, "`expect { }.not_to change { }.to()` is not supported" - end - - private - - def change_description - "to #{description_of @expected_after}#{@description_suffix}" - end - end - - # @private - # Encapsulates the details of the before/after values. - class ChangeDetails - attr_reader :message, :actual_before, :actual_after - - def initialize(receiver=nil, message=nil, &block) - if receiver && !message - raise( - ArgumentError, - "`change` requires either an object and message " \ - "(`change(obj, :msg)`) or a block (`change { }`). " \ - "You passed an object but no message." - ) - end - @message = message ? "##{message}" : "result" - @value_proc = block || lambda { receiver.__send__(message) } - end - - def perform_change(event_proc) - @actual_before = evaluate_value_proc - event_proc.call - @actual_after = evaluate_value_proc - end - - def changed? - @actual_before != @actual_after - end - - def actual_delta - @actual_after - @actual_before - end - - private - - def evaluate_value_proc - case val = @value_proc.call - when IO # enumerable, but we don't want to dup it. - val - when Enumerable, String - val.dup - else - val - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/compound.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/compound.rb deleted file mode 100644 index a9e4f39..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/compound.rb +++ /dev/null @@ -1,119 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Base class for `and` and `or` compound matchers. - class Compound < BaseMatcher - # @private - attr_reader :matcher_1, :matcher_2 - - def initialize(matcher_1, matcher_2) - @matcher_1 = matcher_1 - @matcher_2 = matcher_2 - end - - # @private - def does_not_match?(_actual) - raise NotImplementedError, "`expect(...).not_to " \ - "matcher.#{conjunction} matcher` is not supported" - end - - # @api private - # @return [String] - def description - singleline_message(matcher_1.description, matcher_2.description) - end - - private - - def initialize_copy(other) - @matcher_1 = @matcher_1.clone - @matcher_2 = @matcher_2.clone - super - end - - def indent_multiline_message(message) - message.lines.map do |line| - line =~ /\S/ ? ' ' + line : line - end.join - end - - def compound_failure_message - message_1 = matcher_1.failure_message - message_2 = matcher_2.failure_message - - if multiline?(message_1) || multiline?(message_2) - multiline_message(message_1, message_2) - else - singleline_message(message_1, message_2) - end - end - - def multiline_message(message_1, message_2) - [ - indent_multiline_message(message_1.sub(/\n+\z/, '')), - "...#{conjunction}:", - indent_multiline_message(message_2.sub(/\A\n+/, '')) - ].join("\n\n") - end - - def multiline?(message) - message.lines.count > 1 - end - - def singleline_message(message_1, message_2) - [message_1, conjunction, message_2].join(' ') - end - - # @api public - # Matcher used to represent a compound `and` expectation. - class And < self - # @api private - # @return [String] - def failure_message - if @matcher_1_matches - matcher_2.failure_message - elsif @matcher_2_matches - matcher_1.failure_message - else - compound_failure_message - end - end - - private - - def match(_expected, actual) - @matcher_1_matches = matcher_1.matches?(actual) - @matcher_2_matches = matcher_2.matches?(actual) - - @matcher_1_matches && @matcher_2_matches - end - - def conjunction - "and" - end - end - - # @api public - # Matcher used to represent a compound `or` expectation. - class Or < self - # @api private - # @return [String] - def failure_message - compound_failure_message - end - - private - - def match(_expected, actual) - matcher_1.matches?(actual) || matcher_2.matches?(actual) - end - - def conjunction - "or" - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/contain_exactly.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/contain_exactly.rb deleted file mode 100644 index ccc83f7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/contain_exactly.rb +++ /dev/null @@ -1,249 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `contain_exactly` and `match_array`. - # Not intended to be instantiated directly. - class ContainExactly < BaseMatcher - # @api private - # @return [String] - def failure_message - if Array === actual - message = "expected collection contained: #{safe_sort(surface_descriptions_in expected).inspect}\n" - message += "actual collection contained: #{safe_sort(actual).inspect}\n" - message += "the missing elements were: #{safe_sort(surface_descriptions_in missing_items).inspect}\n" unless missing_items.empty? - message += "the extra elements were: #{safe_sort(extra_items).inspect}\n" unless extra_items.empty? - message - else - "expected a collection that can be converted to an array with " \ - "`#to_ary` or `#to_a`, but got #{actual.inspect}" - end - end - - # @api private - # @return [String] - def failure_message_when_negated - "`contain_exactly` does not support negation" - end - - # @api private - # @return [String] - def description - "contain exactly#{to_sentence(surface_descriptions_in expected)}" - end - - private - - def match(_expected, _actual) - return false unless convert_actual_to_an_array - match_when_sorted? || (extra_items.empty? && missing_items.empty?) - end - - # This cannot always work (e.g. when dealing with unsortable items, - # or matchers as expected items), but it's practically free compared to - # the slowness of the full matching algorithm, and in common cases this - # works, so it's worth a try. - def match_when_sorted? - values_match?(safe_sort(expected), safe_sort(actual)) - end - - def convert_actual_to_an_array - if actual.respond_to?(:to_ary) - @actual = actual.to_ary - elsif enumerable?(actual) && actual.respond_to?(:to_a) - @actual = actual.to_a - else - return false - end - end - - def safe_sort(array) - array.sort rescue array - end - - def missing_items - @missing_items ||= best_solution.unmatched_expected_indexes.map do |index| - expected[index] - end - end - - def extra_items - @extra_items ||= best_solution.unmatched_actual_indexes.map do |index| - actual[index] - end - end - - def best_solution - @best_solution ||= pairings_maximizer.find_best_solution - end - - def pairings_maximizer - @pairings_maximizer ||= begin - expected_matches = Hash[Array.new(expected.size) { |i| [i, []] }] - actual_matches = Hash[Array.new(actual.size) { |i| [i, []] }] - - expected.each_with_index do |e, ei| - actual.each_with_index do |a, ai| - next unless values_match?(e, a) - - expected_matches[ei] << ai - actual_matches[ai] << ei - end - end - - PairingsMaximizer.new(expected_matches, actual_matches) - end - end - - # Once we started supporting composing matchers, the algorithm for this matcher got - # much more complicated. Consider this expression: - # - # expect(["fool", "food"]).to contain_exactly(/foo/, /fool/) - # - # This should pass (because we can pair /fool/ with "fool" and /foo/ with "food"), but - # the original algorithm used by this matcher would pair the first elements it could - # (/foo/ with "fool"), which would leave /fool/ and "food" unmatched. When we have - # an expected element which is a matcher that matches a superset of actual items - # compared to another expected element matcher, we need to consider every possible pairing. - # - # This class is designed to maximize the number of actual/expected pairings -- or, - # conversely, to minimize the number of unpaired items. It's essentially a brute - # force solution, but with a few heuristics applied to reduce the size of the - # problem space: - # - # * Any items which match none of the items in the other list are immediately - # placed into the `unmatched_expected_indexes` or `unmatched_actual_indexes` array. - # The extra items and missing items in the matcher failure message are derived - # from these arrays. - # * Any items which reciprocally match only each other are paired up and not - # considered further. - # - # What's left is only the items which match multiple items from the other list - # (or vice versa). From here, it performs a brute-force depth-first search, - # looking for a solution which pairs all elements in both lists, or, barring that, - # that produces the fewest unmatched items. - # - # @private - class PairingsMaximizer - Solution = Struct.new(:unmatched_expected_indexes, :unmatched_actual_indexes, - :indeterminate_expected_indexes, :indeterminate_actual_indexes) do - def worse_than?(other) - unmatched_item_count > other.unmatched_item_count - end - - def candidate? - indeterminate_expected_indexes.empty? && - indeterminate_actual_indexes.empty? - end - - def ideal? - candidate? && ( - unmatched_expected_indexes.empty? || - unmatched_actual_indexes.empty? - ) - end - - def unmatched_item_count - unmatched_expected_indexes.count + unmatched_actual_indexes.count - end - - def +(derived_candidate_solution) - self.class.new( - unmatched_expected_indexes + derived_candidate_solution.unmatched_expected_indexes, - unmatched_actual_indexes + derived_candidate_solution.unmatched_actual_indexes, - # Ignore the indeterminate indexes: by the time we get here, - # we've dealt with all indeterminates. - [], [] - ) - end - end - - attr_reader :expected_to_actual_matched_indexes, :actual_to_expected_matched_indexes, :solution - - def initialize(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes) - @expected_to_actual_matched_indexes = expected_to_actual_matched_indexes - @actual_to_expected_matched_indexes = actual_to_expected_matched_indexes - - unmatched_expected_indexes, indeterminate_expected_indexes = - categorize_indexes(expected_to_actual_matched_indexes, actual_to_expected_matched_indexes) - - unmatched_actual_indexes, indeterminate_actual_indexes = - categorize_indexes(actual_to_expected_matched_indexes, expected_to_actual_matched_indexes) - - @solution = Solution.new(unmatched_expected_indexes, unmatched_actual_indexes, - indeterminate_expected_indexes, indeterminate_actual_indexes) - end - - def find_best_solution - return solution if solution.candidate? - best_solution_so_far = NullSolution - - expected_index = solution.indeterminate_expected_indexes.first - actuals = expected_to_actual_matched_indexes[expected_index] - - actuals.each do |actual_index| - solution = best_solution_for_pairing(expected_index, actual_index) - return solution if solution.ideal? - best_solution_so_far = solution if best_solution_so_far.worse_than?(solution) - end - - best_solution_so_far - end - - private - - # @private - # Starting solution that is worse than any other real solution. - NullSolution = Class.new do - def self.worse_than?(_other) - true - end - end - - def categorize_indexes(indexes_to_categorize, other_indexes) - unmatched = [] - indeterminate = [] - - indexes_to_categorize.each_pair do |index, matches| - if matches.empty? - unmatched << index - elsif !reciprocal_single_match?(matches, index, other_indexes) - indeterminate << index - end - end - - return unmatched, indeterminate - end - - def reciprocal_single_match?(matches, index, other_list) - return false unless matches.one? - other_list[matches.first] == [index] - end - - def best_solution_for_pairing(expected_index, actual_index) - modified_expecteds = apply_pairing_to( - solution.indeterminate_expected_indexes, - expected_to_actual_matched_indexes, actual_index) - - modified_expecteds.delete(expected_index) - - modified_actuals = apply_pairing_to( - solution.indeterminate_actual_indexes, - actual_to_expected_matched_indexes, expected_index) - - modified_actuals.delete(actual_index) - - solution + self.class.new(modified_expecteds, modified_actuals).find_best_solution - end - - def apply_pairing_to(indeterminates, original_matches, other_list_index) - indeterminates.inject({}) do |accum, index| - accum[index] = original_matches[index] - [other_list_index] - accum - end - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/cover.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/cover.rb deleted file mode 100644 index 47474a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/cover.rb +++ /dev/null @@ -1,24 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `cover`. - # Not intended to be instantiated directly. - class Cover < BaseMatcher - def initialize(*expected) - @expected = expected - end - - def matches?(range) - @actual = range - @expected.all? { |e| range.cover?(e) } - end - - def does_not_match?(range) - @actual = range - expected.none? { |e| range.cover?(e) } - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/eq.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/eq.rb deleted file mode 100644 index 67bc22a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/eq.rb +++ /dev/null @@ -1,75 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `eq`. - # Not intended to be instantiated directly. - class Eq < BaseMatcher - # @api private - # @return [String] - def failure_message - "\nexpected: #{format_object(expected)}\n got: #{format_object(actual)}\n\n(compared using ==)\n" - end - - # @api private - # @return [String] - def failure_message_when_negated - "\nexpected: value != #{format_object(expected)}\n got: #{format_object(actual)}\n\n(compared using ==)\n" - end - - # @api private - # @return [String] - def description - "#{name_to_sentence} #{@expected.inspect}" - end - - # @api private - # @return [Boolean] - def diffable? - true - end - - private - - def match(expected, actual) - actual == expected - end - - def format_object(object) - if Time === object - format_time(object) - elsif defined?(DateTime) && DateTime === object - format_date_time(object) - elsif defined?(BigDecimal) && BigDecimal === object - "#{object.to_s 'F'} (#{object.inspect})" - else - object.inspect - end - end - - TIME_FORMAT = "%Y-%m-%d %H:%M:%S" - - if Time.method_defined?(:nsec) - def format_time(time) - time.strftime("#{TIME_FORMAT}.#{"%09d" % time.nsec} %z") - end - else # for 1.8.7 - def format_time(time) - time.strftime("#{TIME_FORMAT}.#{"%06d" % time.usec} %z") - end - end - - DATE_TIME_FORMAT = "%a, %d %b %Y %H:%M:%S.%N %z" - # ActiveSupport sometimes overrides inspect. If `ActiveSupport` is - # defined use a custom format string that includes more time precision. - def format_date_time(date_time) - if defined?(ActiveSupport) - date_time.strftime(DATE_TIME_FORMAT) - else - date_time.inspect - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/eql.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/eql.rb deleted file mode 100644 index 4aee572..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/eql.rb +++ /dev/null @@ -1,34 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `eql`. - # Not intended to be instantiated directly. - class Eql < BaseMatcher - # @api private - # @return [String] - def failure_message - "\nexpected: #{expected.inspect}\n got: #{actual.inspect}\n\n(compared using eql?)\n" - end - - # @api private - # @return [String] - def failure_message_when_negated - "\nexpected: value != #{expected.inspect}\n got: #{actual.inspect}\n\n(compared using eql?)\n" - end - - # @api private - # @return [Boolean] - def diffable? - true - end - - private - - def match(expected, actual) - actual.eql? expected - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/equal.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/equal.rb deleted file mode 100644 index e2e02d0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/equal.rb +++ /dev/null @@ -1,81 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `equal`. - # Not intended to be instantiated directly. - class Equal < BaseMatcher - # @api private - # @return [String] - def failure_message - if expected_is_a_literal_singleton? - simple_failure_message - else - detailed_failure_message - end - end - - # @api private - # @return [String] - def failure_message_when_negated - <<-MESSAGE - -expected not #{inspect_object(actual)} - got #{inspect_object(expected)} - -Compared using equal?, which compares object identity. - -MESSAGE - end - - # @api private - # @return [Boolean] - def diffable? - !expected_is_a_literal_singleton? - end - - private - - def match(expected, actual) - actual.equal? expected - end - - LITERAL_SINGLETONS = [true, false, nil] - - def expected_is_a_literal_singleton? - LITERAL_SINGLETONS.include?(expected) - end - - def actual_inspected - if LITERAL_SINGLETONS.include?(actual) - actual.inspect - else - inspect_object(actual) - end - end - - def simple_failure_message - "\nexpected #{expected.inspect}\n got #{actual_inspected}\n" - end - - def detailed_failure_message - <<-MESSAGE - -expected #{inspect_object(expected)} - got #{inspect_object(actual)} - -Compared using equal?, which compares object identity, -but expected and actual are not the same object. Use -`expect(actual).to eq(expected)` if you don't care about -object identity in this example. - -MESSAGE - end - - def inspect_object(o) - "#<#{o.class}:#{o.object_id}> => #{o.inspect}" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/exist.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/exist.rb deleted file mode 100644 index 2884fab..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/exist.rb +++ /dev/null @@ -1,86 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `exist`. - # Not intended to be instantiated directly. - class Exist < BaseMatcher - def initialize(*expected) - @expected = expected - end - - # @api private - # @return [Boolean] - def matches?(actual) - @actual = actual - @test = ExistenceTest.new @actual, @expected - @test.valid_test? && @test.actual_exists? - end - - # @api private - # @return [Boolean] - def does_not_match?(actual) - @actual = actual - @test = ExistenceTest.new @actual, @expected - @test.valid_test? && !@test.actual_exists? - end - - # @api private - # @return [String] - def failure_message - "expected #{@actual.inspect} to exist#{@test.validity_message}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected #{@actual.inspect} not to exist#{@test.validity_message}" - end - - # @api private - # Simple class for memoizing actual/expected for this matcher - # and examining the match - class ExistenceTest < Struct.new(:actual, :expected) - # @api private - # @return [Boolean] - def valid_test? - uniq_truthy_values.size == 1 - end - - # @api private - # @return [Boolean] - def actual_exists? - existence_values.first - end - - # @api private - # @return [String] - def validity_message - case uniq_truthy_values.size - when 0 - " but it does not respond to either `exist?` or `exists?`" - when 2 - " but `exist?` and `exists?` returned different values:\n\n"\ - " exist?: #{existence_values.first}\n"\ - "exists?: #{existence_values.last}" - end - end - - private - - def uniq_truthy_values - @uniq_truthy_values ||= existence_values.map { |v| !!v }.uniq - end - - def existence_values - @existence_values ||= predicates.map { |p| actual.__send__(p, *expected) } - end - - def predicates - @predicates ||= [:exist?, :exists?].select { |p| actual.respond_to?(p) } - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/has.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/has.rb deleted file mode 100644 index 38fe226..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/has.rb +++ /dev/null @@ -1,104 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `has_`. - # Not intended to be instantiated directly. - class Has - include Composable - - def initialize(method_name, *args, &block) - @method_name, @args, @block = method_name, args, block - end - - # @private - def matches?(actual, &block) - @actual = actual - @block ||= block - predicate_accessible? && predicate_matches? - end - - # @private - def does_not_match?(actual, &block) - @actual = actual - @block ||= block - predicate_accessible? && !predicate_matches? - end - - # @api private - # @return [String] - def failure_message - validity_message || "expected ##{predicate}#{failure_message_args_description} to return true, got false" - end - - # @api private - # @return [String] - def failure_message_when_negated - validity_message || "expected ##{predicate}#{failure_message_args_description} to return false, got true" - end - - # @api private - # @return [String] - def description - [method_description, args_description].compact.join(' ') - end - - # @private - def supports_block_expectations? - false - end - - private - - def predicate_accessible? - !private_predicate? && predicate_exists? - end - - # support 1.8.7, evaluate once at load time for performance - if String === methods.first - def private_predicate? - @actual.private_methods.include? predicate.to_s - end - else - def private_predicate? - @actual.private_methods.include? predicate - end - end - - def predicate_exists? - @actual.respond_to? predicate - end - - def predicate_matches? - @actual.__send__(predicate, *@args, &@block) - end - - def predicate - @predicate ||= :"has_#{@method_name.to_s.match(Matchers::HAS_REGEX).captures.first}?" - end - - def method_description - @method_name.to_s.gsub('_', ' ') - end - - def args_description - return nil if @args.empty? - @args.map { |arg| arg.inspect }.join(', ') - end - - def failure_message_args_description - desc = args_description - "(#{desc})" if desc - end - - def validity_message - if private_predicate? - "expected #{@actual} to respond to `#{predicate}` but `#{predicate}` is a private method" - elsif !predicate_exists? - "expected #{@actual} to respond to `#{predicate}`" - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/include.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/include.rb deleted file mode 100644 index 86af7a3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/include.rb +++ /dev/null @@ -1,105 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `include`. - # Not intended to be instantiated directly. - class Include < BaseMatcher - def initialize(*expected) - @expected = expected - end - - # @api private - # @return [Boolean] - def matches?(actual) - @actual = actual - perform_match(:all?, :all?) - end - - # @api private - # @return [Boolean] - def does_not_match?(actual) - @actual = actual - perform_match(:none?, :any?) - end - - # @api private - # @return [String] - def description - described_items = surface_descriptions_in(expected) - improve_hash_formatting "include#{to_sentence(described_items)}" - end - - # @api private - # @return [String] - def failure_message - improve_hash_formatting(super) + invalid_type_message - end - - # @api private - # @return [String] - def failure_message_when_negated - improve_hash_formatting(super) + invalid_type_message - end - - # @api private - # @return [Boolean] - def diffable? - true - end - - private - - def invalid_type_message - return '' if actual.respond_to?(:include?) - ", but it does not respond to `include?`" - end - - def perform_match(predicate, hash_subset_predicate) - return false unless actual.respond_to?(:include?) - - expected.__send__(predicate) do |expected_item| - if comparing_hash_to_a_subset?(expected_item) - expected_item.__send__(hash_subset_predicate) do |(key, value)| - actual_hash_includes?(key, value) - end - elsif comparing_hash_keys?(expected_item) - actual_hash_has_key?(expected_item) - else - actual_collection_includes?(expected_item) - end - end - end - - def comparing_hash_to_a_subset?(expected_item) - actual.is_a?(Hash) && expected_item.is_a?(Hash) - end - - def actual_hash_includes?(expected_key, expected_value) - actual_value = actual.fetch(expected_key) { return false } - values_match?(expected_value, actual_value) - end - - def comparing_hash_keys?(expected_item) - actual.is_a?(Hash) && !expected_item.is_a?(Hash) - end - - def actual_hash_has_key?(expected_key) - # We check `key?` first for perf: - # `key?` is O(1), but `any?` is O(N). - actual.key?(expected_key) || - actual.keys.any? { |key| values_match?(expected_key, key) } - end - - def actual_collection_includes?(expected_item) - return true if actual.include?(expected_item) - - # String lacks an `any?` method... - return false unless actual.respond_to?(:any?) - - actual.any? { |value| values_match?(expected_item, value) } - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/match.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/match.rb deleted file mode 100644 index 9e44e8d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/match.rb +++ /dev/null @@ -1,29 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `match`. - # Not intended to be instantiated directly. - class Match < BaseMatcher - # @api private - # @return [String] - def description - "match #{surface_descriptions_in(expected).inspect}" - end - - # @api private - # @return [Boolean] - def diffable? - true - end - - private - - def match(expected, actual) - return true if values_match?(expected, actual) - actual.match(expected) if actual.respond_to?(:match) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/operators.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/operators.rb deleted file mode 100644 index eada4b5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/operators.rb +++ /dev/null @@ -1,119 +0,0 @@ -require 'rspec/support' - -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for operator matchers. - # Not intended to be instantiated directly. - # Only available for use with `should`. - class OperatorMatcher - class << self - # @private - def registry - @registry ||= {} - end - - # @private - def register(klass, operator, matcher) - registry[klass] ||= {} - registry[klass][operator] = matcher - end - - # @private - def unregister(klass, operator) - registry[klass] && registry[klass].delete(operator) - end - - # @private - def get(klass, operator) - klass.ancestors.each do |ancestor| - matcher = registry[ancestor] && registry[ancestor][operator] - return matcher if matcher - end - - nil - end - end - - register Enumerable, '=~', BuiltIn::ContainExactly - - def initialize(actual) - @actual = actual - end - - # @private - def self.use_custom_matcher_or_delegate(operator) - define_method(operator) do |expected| - if !has_non_generic_implementation_of?(operator) && (matcher = OperatorMatcher.get(@actual.class, operator)) - @actual.__send__(::RSpec::Matchers.last_expectation_handler.should_method, matcher.new(expected)) - else - eval_match(@actual, operator, expected) - end - end - - negative_operator = operator.sub(/^=/, '!') - if negative_operator != operator && respond_to?(negative_operator) - define_method(negative_operator) do |_expected| - opposite_should = ::RSpec::Matchers.last_expectation_handler.opposite_should_method - raise "RSpec does not support `#{::RSpec::Matchers.last_expectation_handler.should_method} #{negative_operator} expected`. " \ - "Use `#{opposite_should} #{operator} expected` instead." - end - end - end - - ['==', '===', '=~', '>', '>=', '<', '<='].each do |operator| - use_custom_matcher_or_delegate operator - end - - # @private - def fail_with_message(message) - RSpec::Expectations.fail_with(message, @expected, @actual) - end - - # @api private - # @return [String] - def description - "#{@operator} #{@expected.inspect}" - end - - private - - def has_non_generic_implementation_of?(op) - Support.method_handle_for(@actual, op).owner != ::Kernel - rescue NameError - false - end - - def eval_match(actual, operator, expected) - ::RSpec::Matchers.last_matcher = self - @operator, @expected = operator, expected - __delegate_operator(actual, operator, expected) - end - end - - # @private - # Handles operator matcher for `should`. - class PositiveOperatorMatcher < OperatorMatcher - def __delegate_operator(actual, operator, expected) - if actual.__send__(operator, expected) - true - elsif ['==', '===', '=~'].include?(operator) - fail_with_message("expected: #{expected.inspect}\n got: #{actual.inspect} (using #{operator})") - else - fail_with_message("expected: #{operator} #{expected.inspect}\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}") - end - end - end - - # @private - # Handles operator matcher for `should_not`. - class NegativeOperatorMatcher < OperatorMatcher - def __delegate_operator(actual, operator, expected) - return false unless actual.__send__(operator, expected) - fail_with_message("expected not: #{operator} #{expected.inspect}\n got: #{operator.gsub(/./, ' ')} #{actual.inspect}") - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/output.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/output.rb deleted file mode 100644 index 542840b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/output.rb +++ /dev/null @@ -1,150 +0,0 @@ -require 'stringio' - -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `output`. - # Not intended to be instantiated directly. - class Output < BaseMatcher - def initialize(expected) - @expected = expected - @stream_capturer = NullCapture - end - - def matches?(block) - @block = block - return false unless Proc === block - @actual = @stream_capturer.capture(block) - @expected ? values_match?(@expected, @actual) : captured? - end - - def does_not_match?(block) - !matches?(block) && Proc === block - end - - # @api public - # Tells the matcher to match against stdout. - def to_stdout - @stream_capturer = CaptureStdout - self - end - - # @api public - # Tells the matcher to match against stderr. - def to_stderr - @stream_capturer = CaptureStderr - self - end - - # @api private - # @return [String] - def failure_message - "expected block to #{description}, but #{positive_failure_reason}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected block to not #{description}, but #{negative_failure_reason}" - end - - # @api private - # @return [String] - def description - if @expected - "output #{description_of @expected} to #{@stream_capturer.name}" - else - "output to #{@stream_capturer.name}" - end - end - - # @api private - # @return [Boolean] - def diffable? - true - end - - # @api private - # Indicates this matcher matches against a block. - # @return [True] - def supports_block_expectations? - true - end - - private - - def captured? - @actual.length > 0 - end - - def positive_failure_reason - return "was not a block" unless Proc === @block - return "output #{actual_output_description}" if @expected - "did not" - end - - def negative_failure_reason - return "was not a block" unless Proc === @block - "output #{actual_output_description}" - end - - def actual_output_description - return "nothing" unless captured? - @actual.inspect - end - end - - # @private - module NullCapture - def self.name - "some stream" - end - - def self.capture(_block) - raise "You must chain `to_stdout` or `to_stderr` off of the `output(...)` matcher." - end - end - - # @private - module CaptureStdout - def self.name - 'stdout' - end - - def self.capture(block) - captured_stream = StringIO.new - - original_stream = $stdout - $stdout = captured_stream - - block.call - - captured_stream.string - ensure - $stdout = original_stream - end - end - - # @private - module CaptureStderr - def self.name - 'stderr' - end - - def self.capture(block) - captured_stream = StringIO.new - - original_stream = $stderr - $stderr = captured_stream - - block.call - - captured_stream.string - ensure - $stderr = original_stream - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/raise_error.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/raise_error.rb deleted file mode 100644 index a93f9ba..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/raise_error.rb +++ /dev/null @@ -1,168 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `raise_error`. - # Not intended to be instantiated directly. - class RaiseError - include Composable - - def initialize(expected_error_or_message=Exception, expected_message=nil, &block) - @block = block - @actual_error = nil - case expected_error_or_message - when String, Regexp - @expected_error, @expected_message = Exception, expected_error_or_message - else - @expected_error, @expected_message = expected_error_or_message, expected_message - end - end - - # @api public - # Specifies the expected error message. - def with_message(expected_message) - raise_message_already_set if @expected_message - @expected_message = expected_message - self - end - - # rubocop:disable MethodLength - # @private - def matches?(given_proc, negative_expectation=false, &block) - @given_proc = given_proc - @block ||= block - @raised_expected_error = false - @with_expected_message = false - @eval_block = false - @eval_block_passed = false - - return false unless Proc === given_proc - - begin - given_proc.call - rescue Exception => @actual_error - if values_match?(@expected_error, @actual_error) - @raised_expected_error = true - @with_expected_message = verify_message - end - end - - unless negative_expectation - eval_block if @raised_expected_error && @with_expected_message && @block - end - - expectation_matched? - end - # rubocop:enable MethodLength - - # @private - def does_not_match?(given_proc) - prevent_invalid_expectations - !matches?(given_proc, :negative_expectation) && Proc === given_proc - end - - # @private - def supports_block_expectations? - true - end - - # @api private - # @return [String] - def failure_message - @eval_block ? @actual_error.message : "expected #{expected_error}#{given_error}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected no #{expected_error}#{given_error}" - end - - # @api private - # @return [String] - def description - "raise #{expected_error}" - end - - private - - def expectation_matched? - error_and_message_match? && block_matches? - end - - def error_and_message_match? - @raised_expected_error && @with_expected_message - end - - def block_matches? - @eval_block ? @eval_block_passed : true - end - - def eval_block - @eval_block = true - begin - @block[@actual_error] - @eval_block_passed = true - rescue Exception => err - @actual_error = err - end - end - - def verify_message - return true if @expected_message.nil? - values_match?(@expected_message, @actual_error.message) - end - - def prevent_invalid_expectations - what_to_raise = if expecting_specific_exception? && @expected_message - "`expect { }.not_to raise_error(SpecificErrorClass, message)`" - elsif expecting_specific_exception? - "`expect { }.not_to raise_error(SpecificErrorClass)`" - elsif @expected_message - "`expect { }.not_to raise_error(message)`" - end - - return unless what_to_raise - - specific_class_error = ArgumentError.new("#{what_to_raise} is not valid, use `expect { }.not_to raise_error` (with no args) instead") - raise specific_class_error - end - - def expected_error - case @expected_message - when nil - description_of(@expected_error) - when Regexp - "#{@expected_error} with message matching #{@expected_message.inspect}" - else - "#{@expected_error} with #{description_of @expected_message}" - end - end - - def format_backtrace(backtrace) - formatter = Matchers.configuration.backtrace_formatter - formatter.format_backtrace(backtrace) - end - - def given_error - return " but was not given a block" unless Proc === @given_proc - return " but nothing was raised" unless @actual_error - - backtrace = format_backtrace(@actual_error.backtrace) - [ - ", got #{@actual_error.inspect} with backtrace:", - *backtrace - ].join("\n # ") - end - - def expecting_specific_exception? - @expected_error != Exception - end - - def raise_message_already_set - raise "`expect { }.to raise_error(message).with_message(message)` is not valid. The matcher only allows the expected message to be specified once" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/respond_to.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/respond_to.rb deleted file mode 100644 index 77d5b7f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/respond_to.rb +++ /dev/null @@ -1,98 +0,0 @@ -RSpec::Support.require_rspec_support "method_signature_verifier" - -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `respond_to`. - # Not intended to be instantiated directly. - class RespondTo - include Composable - - def initialize(*names) - @names = names - @expected_arity = nil - end - - # @api public - # Specifies the number of expected arguments. - # - # @example - # expect(obj).to respond_to(:message).with(3).arguments - def with(n) - @expected_arity = n - self - end - - # @api public - # No-op. Intended to be used as syntactic sugar when using `with`. - # - # @example - # expect(obj).to respond_to(:message).with(3).arguments - def argument - self - end - alias :arguments :argument - - # @private - def matches?(actual) - find_failing_method_names(actual, :reject).empty? - end - - # @private - def does_not_match?(actual) - find_failing_method_names(actual, :select).empty? - end - - # @api private - # @return [String] - def failure_message - "expected #{@actual.inspect} to respond to #{@failing_method_names.map { |name| name.inspect }.join(', ')}#{with_arity}" - end - - # @api private - # @return [String] - def failure_message_when_negated - failure_message.sub(/to respond to/, 'not to respond to') - end - - # @api private - # @return [String] - def description - "respond to #{pp_names}#{with_arity}" - end - - # @private - def supports_block_expectations? - false - end - - private - - def find_failing_method_names(actual, filter_method) - @actual = actual - @failing_method_names = @names.__send__(filter_method) do |name| - @actual.respond_to?(name) && matches_arity?(actual, name) - end - end - - def matches_arity?(actual, name) - return true unless @expected_arity - - signature = Support::MethodSignature.new(actual.method(name)) - Support::MethodSignatureVerifier.new(signature, Array.new(@expected_arity)).valid? - end - - def with_arity - return "" unless @expected_arity - " with #{@expected_arity} argument#{@expected_arity == 1 ? '' : 's'}" - end - - def pp_names - # Ruby 1.9 returns the same thing for array.to_s as array.inspect, so just use array.inspect here - @names.length == 1 ? "##{@names.first}" : @names.inspect - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/satisfy.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/satisfy.rb deleted file mode 100644 index 6df3c22..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/satisfy.rb +++ /dev/null @@ -1,46 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `satisfy`. - # Not intended to be instantiated directly. - class Satisfy - include Composable - - def initialize(&block) - @block = block - end - - # @private - def matches?(actual, &block) - @block = block if block - @actual = actual - @block.call(actual) - end - - # @api private - # @return [String] - def failure_message - "expected #{@actual} to satisfy block" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected #{@actual} not to satisfy block" - end - - # @api private - # @return [String] - def description - "satisfy block" - end - - # @private - def supports_block_expectations? - false - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/start_and_end_with.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/start_and_end_with.rb deleted file mode 100644 index a08c8e9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/start_and_end_with.rb +++ /dev/null @@ -1,82 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Base class for the `end_with` and `start_with` matchers. - # Not intended to be instantiated directly. - class StartAndEndWith < BaseMatcher - def initialize(*expected) - @actual_does_not_have_ordered_elements = false - @expected = expected.length == 1 ? expected.first : expected - end - - # @api private - # @return [String] - def failure_message - super.tap do |msg| - if @actual_does_not_have_ordered_elements - msg << ", but it does not have ordered elements" - elsif !actual.respond_to?(:[]) - msg << ", but it cannot be indexed using #[]" - end - end - end - - # @api private - # @return [String] - def description - return super unless Hash === expected - "#{name_to_sentence} #{surface_descriptions_in(expected).inspect}" - end - - private - - def match(expected, actual) - return false unless actual.respond_to?(:[]) - - begin - return subset_matches? if expected.respond_to?(:length) - element_matches? - rescue ArgumentError - @actual_does_not_have_ordered_elements = true - return false - end - end - - def actual_is_unordered - ArgumentError.new("#{actual.inspect} does not have ordered elements") - end - end - - # @api private - # Provides the implementation for `start_with`. - # Not intended to be instantiated directly. - class StartWith < StartAndEndWith - private - - def subset_matches? - values_match?(expected, actual[0, expected.length]) - end - - def element_matches? - values_match?(expected, actual[0]) - end - end - - # @api private - # Provides the implementation for `end_with`. - # Not intended to be instantiated directly. - class EndWith < StartAndEndWith - private - - def subset_matches? - values_match?(expected, actual[-expected.length, expected.length]) - end - - def element_matches? - values_match?(expected, actual[-1]) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/throw_symbol.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/throw_symbol.rb deleted file mode 100644 index 4089d60..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/throw_symbol.rb +++ /dev/null @@ -1,128 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @api private - # Provides the implementation for `throw_symbol`. - # Not intended to be instantiated directly. - class ThrowSymbol - include Composable - - def initialize(expected_symbol=nil, expected_arg=nil) - @expected_symbol = expected_symbol - @expected_arg = expected_arg - @caught_symbol = @caught_arg = nil - end - - # rubocop:disable MethodLength - # @private - def matches?(given_proc) - @block = given_proc - return false unless Proc === given_proc - - begin - if @expected_symbol.nil? - given_proc.call - else - @caught_arg = catch :proc_did_not_throw_anything do - catch @expected_symbol do - given_proc.call - throw :proc_did_not_throw_anything, :nothing_thrown - end - end - - if @caught_arg == :nothing_thrown - @caught_arg = nil - else - @caught_symbol = @expected_symbol - end - end - - # Ruby 1.8 uses NameError with `symbol' - # Ruby 1.9 uses ArgumentError with :symbol - rescue NameError, ArgumentError => e - unless (match_data = e.message.match(/uncaught throw (`|\:)([a-zA-Z0-9_]*)(')?/)) - other_exception = e - raise - end - @caught_symbol = match_data.captures[1].to_sym - rescue => other_exception - raise - ensure - # rubocop:disable EnsureReturn - unless other_exception - if @expected_symbol.nil? - return !!@caught_symbol - else - if @expected_arg.nil? - return @caught_symbol == @expected_symbol - else - return (@caught_symbol == @expected_symbol) && values_match?(@expected_arg, @caught_arg) - end - end - end - # rubocop:enable EnsureReturn - end - end - # rubocop:enable MethodLength - - def does_not_match?(given_proc) - !matches?(given_proc) && Proc === given_proc - end - - # @api private - # @return [String] - def failure_message - "expected #{expected} to be thrown, #{actual_result}" - end - - # @api private - # @return [String] - def failure_message_when_negated - "expected #{expected('no Symbol')}#{' not' if @expected_symbol} to be thrown, #{actual_result}" - end - - # @api private - # @return [String] - def description - "throw #{expected}" - end - - # @api private - # Indicates this matcher matches against a block. - # @return [True] - def supports_block_expectations? - true - end - - private - - def actual_result - return "but was not a block" unless Proc === @block - "got #{caught}" - end - - def expected(symbol_desc='a Symbol') - throw_description(@expected_symbol || symbol_desc, @expected_arg) - end - - def caught - throw_description(@caught_symbol || 'nothing', @caught_arg) - end - - def throw_description(symbol, arg) - symbol_description = symbol.is_a?(String) ? symbol : symbol.inspect - - arg_description = if arg - " with #{description_of arg}" - elsif @expected_arg && @caught_symbol == @expected_symbol - " with no argument" - else - "" - end - - symbol_description + arg_description - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/yield.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/yield.rb deleted file mode 100644 index 8922537..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/built_in/yield.rb +++ /dev/null @@ -1,402 +0,0 @@ -module RSpec - module Matchers - module BuiltIn - # @private - # Object that is yielded to `expect` when one of the - # yield matchers is used. Provides information about - # the yield behavior of the object-under-test. - class YieldProbe - def self.probe(block) - probe = new(block) - return probe unless probe.has_block? - probe.assert_valid_expect_block! - block.call(probe) - probe.assert_used! - probe - end - - attr_accessor :num_yields, :yielded_args - - def initialize(block) - @block = block - @used = false - self.num_yields, self.yielded_args = 0, [] - end - - def has_block? - Proc === @block - end - - def to_proc - @used = true - - probe = self - Proc.new do |*args| - probe.num_yields += 1 - probe.yielded_args << args - nil # to indicate the block does not return a meaningful value - end - end - - def single_yield_args - yielded_args.first - end - - def yielded_once?(matcher_name) - case num_yields - when 1 then true - when 0 then false - else - raise "The #{matcher_name} matcher is not designed to be used with a " \ - "method that yields multiple times. Use the yield_successive_args " \ - "matcher for that case." - end - end - - def successive_yield_args - yielded_args.map do |arg_array| - arg_array.size == 1 ? arg_array.first : arg_array - end - end - - def assert_used! - return if @used - raise "You must pass the argument yielded to your expect block on " \ - "to the method-under-test as a block. It acts as a probe that " \ - "allows the matcher to detect whether or not the method-under-test " \ - "yields, and, if so, how many times, and what the yielded arguments " \ - "are." - end - - def assert_valid_expect_block! - return if @block.arity == 1 - raise "Your expect block must accept an argument to be used with this " \ - "matcher. Pass the argument as a block on to the method you are testing." - end - end - - # @api private - # Provides the implementation for `yield_control`. - # Not intended to be instantiated directly. - class YieldControl < BaseMatcher - def initialize - @expectation_type = nil - @expected_yields_count = nil - end - - # @api public - # Specifies that the method is expected to yield once. - def once - exactly(1) - self - end - - # @api public - # Specifies that the method is expected to yield once. - def twice - exactly(2) - self - end - - # @api public - # Specifies that the method is expected to yield the given number of times. - def exactly(number) - set_expected_yields_count(:==, number) - self - end - - # @api public - # Specifies the maximum number of times the method is expected to yield - def at_most(number) - set_expected_yields_count(:<=, number) - self - end - - # @api public - # Specifies the minimum number of times the method is expected to yield - def at_least(number) - set_expected_yields_count(:>=, number) - self - end - - # @api public - # No-op. Provides syntactic sugar. - def times - self - end - - # @private - def matches?(block) - @probe = YieldProbe.probe(block) - return false unless @probe.has_block? - - if @expectation_type - @probe.num_yields.__send__(@expectation_type, @expected_yields_count) - else - @probe.yielded_once?(:yield_control) - end - end - - # @private - def does_not_match?(block) - !matches?(block) && @probe.has_block? - end - - # @api private - # @return [String] - def failure_message - 'expected given block to yield control' + failure_reason - end - - # @api private - # @return [String] - def failure_message_when_negated - 'expected given block not to yield control' + failure_reason - end - - # @private - def supports_block_expectations? - true - end - - private - - def set_expected_yields_count(relativity, n) - @expectation_type = relativity - @expected_yields_count = case n - when Numeric then n - when :once then 1 - when :twice then 2 - end - end - - def failure_reason - return " but was not a block" unless @probe.has_block? - return '' unless @expected_yields_count - " #{human_readable_expecation_type}#{human_readable_count}" - end - - def human_readable_expecation_type - case @expectation_type - when :<= then 'at most ' - when :>= then 'at least ' - else '' - end - end - - def human_readable_count - case @expected_yields_count - when 1 then "once" - when 2 then "twice" - else "#{@expected_yields_count} times" - end - end - end - - # @api private - # Provides the implementation for `yield_with_no_args`. - # Not intended to be instantiated directly. - class YieldWithNoArgs < BaseMatcher - # @private - def matches?(block) - @probe = YieldProbe.probe(block) - return false unless @probe.has_block? - @probe.yielded_once?(:yield_with_no_args) && @probe.single_yield_args.empty? - end - - # @private - def does_not_match?(block) - !matches?(block) && @probe.has_block? - end - - # @private - def failure_message - "expected given block to yield with no arguments, but #{positive_failure_reason}" - end - - # @private - def failure_message_when_negated - "expected given block not to yield with no arguments, but #{negative_failure_reason}" - end - - # @private - def supports_block_expectations? - true - end - - private - - def positive_failure_reason - return "was not a block" unless @probe.has_block? - return "did not yield" if @probe.num_yields.zero? - "yielded with arguments: #{@probe.single_yield_args.inspect}" - end - - def negative_failure_reason - return "was not a block" unless @probe.has_block? - "did" - end - end - - # @api private - # Provides the implementation for `yield_with_args`. - # Not intended to be instantiated directly. - class YieldWithArgs - include Composable - - def initialize(*args) - @expected = args - end - - # @private - def matches?(block) - @probe = YieldProbe.probe(block) - return false unless @probe.has_block? - @actual = @probe.single_yield_args - @probe.yielded_once?(:yield_with_args) && args_match? - end - - # @private - def does_not_match?(block) - !matches?(block) && @probe.has_block? - end - - # @private - def failure_message - "expected given block to yield with arguments, but #{positive_failure_reason}" - end - - # @private - def failure_message_when_negated - "expected given block not to yield with arguments, but #{negative_failure_reason}" - end - - # @private - def description - desc = "yield with args" - desc << "(#{expected_arg_description})" unless @expected.empty? - desc - end - - # @private - def supports_block_expectations? - true - end - - private - - def positive_failure_reason - return "was not a block" unless @probe.has_block? - return "did not yield" if @probe.num_yields.zero? - @positive_args_failure - end - - def expected_arg_description - @expected.map { |e| description_of e }.join(", ") - end - - def negative_failure_reason - if !@probe.has_block? - "was not a block" - elsif all_args_match? - "yielded with expected arguments" \ - "\nexpected not: #{surface_descriptions_in(@expected).inspect}" + - "\n got: #{@actual.inspect}" - else - "did" - end - end - - def args_match? - if @expected.empty? # expect {...}.to yield_with_args - @positive_args_failure = "yielded with no arguments" if @actual.empty? - return !@actual.empty? - end - - unless (match = all_args_match?) - @positive_args_failure = "yielded with unexpected arguments" \ - "\nexpected: #{surface_descriptions_in(@expected).inspect}" + - "\n got: #{@actual.inspect}" - end - - match - end - - def all_args_match? - values_match?(@expected, @actual) - end - end - - # @api private - # Provides the implementation for `yield_successive_args`. - # Not intended to be instantiated directly. - class YieldSuccessiveArgs - include Composable - - def initialize(*args) - @expected = args - end - - # @private - def matches?(block) - @probe = YieldProbe.probe(block) - return false unless @probe.has_block? - @actual = @probe.successive_yield_args - args_match? - end - - def does_not_match?(block) - !matches?(block) && @probe.has_block? - end - - # @private - def failure_message - "expected given block to yield successively with arguments, but #{positive_failure_reason}" - end - - # @private - def failure_message_when_negated - "expected given block not to yield successively with arguments, but #{negative_failure_reason}" - end - - # @private - def description - desc = "yield successive args" - desc << "(#{expected_arg_description})" - desc - end - - # @private - def supports_block_expectations? - true - end - - private - - def args_match? - values_match?(@expected, @actual) - end - - def expected_arg_description - @expected.map { |e| description_of e }.join(", ") - end - - def positive_failure_reason - return "was not a block" unless @probe.has_block? - - "yielded with unexpected arguments" \ - "\nexpected: #{surface_descriptions_in(@expected).inspect}" \ - "\n got: #{@actual.inspect}" - end - - def negative_failure_reason - return "was not a block" unless @probe.has_block? - - "yielded with expected arguments" \ - "\nexpected not: #{surface_descriptions_in(@expected).inspect}" \ - "\n got: #{@actual.inspect}" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/composable.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/composable.rb deleted file mode 100644 index 68e24bd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/composable.rb +++ /dev/null @@ -1,181 +0,0 @@ -RSpec::Support.require_rspec_support "fuzzy_matcher" - -module RSpec - module Matchers - # Mixin designed to support the composable matcher features - # of RSpec 3+. Mix it into your custom matcher classes to - # allow them to be used in a composable fashion. - # - # @api public - module Composable - # Creates a compound `and` expectation. The matcher will - # only pass if both sub-matchers pass. - # This can be chained together to form an arbitrarily long - # chain of matchers. - # - # @example - # expect(alphabet).to start_with("a").and end_with("z") - # expect(alphabet).to start_with("a") & end_with("z") - # - # @note The negative form (`expect(...).not_to matcher.and other`) - # is not supported at this time. - def and(matcher) - BuiltIn::Compound::And.new self, matcher - end - alias & and - - # Creates a compound `or` expectation. The matcher will - # pass if either sub-matcher passes. - # This can be chained together to form an arbitrarily long - # chain of matchers. - # - # @example - # expect(stoplight.color).to eq("red").or eq("green").or eq("yellow") - # expect(stoplight.color).to eq("red") | eq("green") | eq("yellow") - # - # @note The negative form (`expect(...).not_to matcher.or other`) - # is not supported at this time. - def or(matcher) - BuiltIn::Compound::Or.new self, matcher - end - alias | or - - # Delegates to `#matches?`. Allows matchers to be used in composable - # fashion and also supports using matchers in case statements. - def ===(value) - matches?(value) - end - - private - - # This provides a generic way to fuzzy-match an expected value against - # an actual value. It understands nested data structures (e.g. hashes - # and arrays) and is able to match against a matcher being used as - # the expected value or within the expected value at any level of - # nesting. - # - # Within a custom matcher you are encouraged to use this whenever your - # matcher needs to match two values, unless it needs more precise semantics. - # For example, the `eq` matcher _does not_ use this as it is meant to - # use `==` (and only `==`) for matching. - # - # @param expected [Object] what is expected - # @param actual [Object] the actual value - # - # @!visibility public - def values_match?(expected, actual) - expected = with_matchers_cloned(expected) - Support::FuzzyMatcher.values_match?(expected, actual) - end - - # Returns the description of the given object in a way that is - # aware of composed matchers. If the object is a matcher with - # a `description` method, returns the description; otherwise - # returns `object.inspect`. - # - # You are encouraged to use this in your custom matcher's - # `description`, `failure_message` or - # `failure_message_when_negated` implementation if you are - # supporting matcher arguments. - # - # @!visibility public - def description_of(object) - return object.description if Matchers.is_a_describable_matcher?(object) - object.inspect - end - - # Transforms the given data structue (typically a hash or array) - # into a new data structure that, when `#inspect` is called on it, - # will provide descriptions of any contained matchers rather than - # the normal `#inspect` output. - # - # You are encouraged to use this in your custom matcher's - # `description`, `failure_message` or - # `failure_message_when_negated` implementation if you are - # supporting any arguments which may be a data structure - # containing matchers. - # - # @!visibility public - def surface_descriptions_in(item) - if Matchers.is_a_describable_matcher?(item) - DescribableItem.new(item) - elsif Hash === item - Hash[surface_descriptions_in(item.to_a)] - elsif Struct === item - item.inspect - elsif enumerable?(item) - begin - item.map { |subitem| surface_descriptions_in(subitem) } - rescue IOError # STDOUT is enumerable but `map` raises an error - item.inspect - end - else - item - end - end - - # @private - # Historically, a single matcher instance was only checked - # against a single value. Given that the matcher was only - # used once, it's been common to memoize some intermediate - # calculation that is derived from the `actual` value in - # order to reuse that intermediate result in the failure - # message. - # - # This can cause a problem when using such a matcher as an - # argument to another matcher in a composed matcher expression, - # since the matcher instance may be checked against multiple - # values and produce invalid results due to the memoization. - # - # To deal with this, we clone any matchers in `expected` via - # this method when using `values_match?`, so that any memoization - # does not "leak" between checks. - def with_matchers_cloned(object) - if Matchers.is_a_matcher?(object) - object.clone - elsif Hash === object - Hash[with_matchers_cloned(object.to_a)] - elsif enumerable?(object) - begin - object.map { |subobject| with_matchers_cloned(subobject) } - rescue IOError # STDOUT is enumerable but `map` raises an error - object - end - else - object - end - end - - if String.ancestors.include?(Enumerable) # 1.8.7 - # Strings are not enumerable on 1.9, and on 1.8 they are an infinitely - # nested enumerable: since ruby lacks a character class, it yields - # 1-character strings, which are themselves enumerable, composed of a - # a single 1-character string, which is an enumerable, etc. - # - # @api private - def enumerable?(item) - return false if String === item - Enumerable === item - end - else - # @api private - def enumerable?(item) - Enumerable === item - end - end - module_function :surface_descriptions_in, :enumerable? - - # Wraps an item in order to surface its `description` via `inspect`. - # @api private - DescribableItem = Struct.new(:item) do - def inspect - "(#{item.description})" - end - - def pretty_print(pp) - pp.text "(#{item.description})" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/dsl.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/dsl.rb deleted file mode 100644 index 8a9a1af..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/dsl.rb +++ /dev/null @@ -1,379 +0,0 @@ -module RSpec - module Matchers - # Defines the custom matcher DSL. - module DSL - # Defines a custom matcher. - # @see RSpec::Matchers - def define(name, &declarations) - define_method name do |*expected| - RSpec::Matchers::DSL::Matcher.new(name, declarations, self, *expected) - end - end - alias_method :matcher, :define - - RSpec.configure { |c| c.extend self } if RSpec.respond_to?(:configure) - - # Contains the methods that are available from within the - # `RSpec::Matchers.define` DSL for creating custom matchers. - module Macros - # Stores the block that is used to determine whether this matcher passes - # or fails. The block should return a boolean value. When the matcher is - # passed to `expect(...).to` and the block returns `true`, then the expectation - # passes. Similarly, when the matcher is passed to `expect(...).not_to` and the - # block returns `false`, then the expectation passes. - # - # @example - # - # RSpec::Matchers.define :be_even do - # match do |actual| - # actual.even? - # end - # end - # - # expect(4).to be_even # passes - # expect(3).not_to be_even # passes - # expect(3).to be_even # fails - # expect(4).not_to be_even # fails - # - # @yield [Object] actual the actual value (i.e. the value wrapped by `expect`) - def match(&match_block) - define_user_override(:matches?, match_block) do |actual| - begin - @actual = actual - super(*actual_arg_for(match_block)) - rescue RSpec::Expectations::ExpectationNotMetError - false - end - end - end - - # Use this to define the block for a negative expectation (`expect(...).not_to`) - # when the positive and negative forms require different handling. This - # is rarely necessary, but can be helpful, for example, when specifying - # asynchronous processes that require different timeouts. - # - # @yield [Object] actual the actual value (i.e. the value wrapped by `expect`) - def match_when_negated(&match_block) - define_user_override(:does_not_match?, match_block) do |actual| - @actual = actual - super(*actual_arg_for(match_block)) - end - end - - # Use this instead of `match` when the block will raise an exception - # rather than returning false to indicate a failure. - # - # @example - # - # RSpec::Matchers.define :accept_as_valid do |candidate_address| - # match_unless_raises ValidationException do |validator| - # validator.validate(candidate_address) - # end - # end - # - # expect(email_validator).to accept_as_valid("person@company.com") - # - # @yield [Object] actual the actual object (i.e. the value wrapped by `expect`) - def match_unless_raises(expected_exception=Exception, &match_block) - define_user_override(:matches?, match_block) do |actual| - @actual = actual - begin - super(*actual_arg_for(match_block)) - rescue expected_exception => @rescued_exception - false - else - true - end - end - end - - # Customizes the failure messsage to use when this matcher is - # asked to positively match. Only use this when the message - # generated by default doesn't suit your needs. - # - # @example - # - # RSpec::Matchers.define :have_strength do |expected| - # match { your_match_logic } - # - # failure_message do |actual| - # "Expected strength of #{expected}, but had #{actual.strength}" - # end - # end - # - # @yield [Object] actual the actual object (i.e. the value wrapped by `expect`) - def failure_message(&definition) - define_user_override(__method__, definition) - end - - # Customize the failure messsage to use when this matcher is asked - # to negatively match. Only use this when the message generated by - # default doesn't suit your needs. - # - # @example - # - # RSpec::Matchers.define :have_strength do |expected| - # match { your_match_logic } - # - # failure_message_when_negated do |actual| - # "Expected not to have strength of #{expected}, but did" - # end - # end - # - # @yield [Object] actual the actual object (i.e. the value wrapped by `expect`) - def failure_message_when_negated(&definition) - define_user_override(__method__, definition) - end - - # Customize the description to use for one-liners. Only use this when - # the description generated by default doesn't suit your needs. - # - # @example - # - # RSpec::Matchers.define :qualify_for do |expected| - # match { your_match_logic } - # - # description do - # "qualify for #{expected}" - # end - # end - # - # @yield [Object] actual the actual object (i.e. the value wrapped by `expect`) - def description(&definition) - define_user_override(__method__, definition) - end - - # Tells the matcher to diff the actual and expected values in the failure - # message. - def diffable - define_method(:diffable?) { true } - end - - # Declares that the matcher can be used in a block expectation. - # Users will not be able to use your matcher in a block - # expectation without declaring this. - # (e.g. `expect { do_something }.to matcher`). - def supports_block_expectations - define_method(:supports_block_expectations?) { true } - end - - # Convenience for defining methods on this matcher to create a fluent - # interface. The trick about fluent interfaces is that each method must - # return self in order to chain methods together. `chain` handles that - # for you. - # - # @example - # - # RSpec::Matchers.define :have_errors_on do |key| - # chain :with do |message| - # @message = message - # end - # - # match do |actual| - # actual.errors[key] == @message - # end - # end - # - # expect(minor).to have_errors_on(:age).with("Not old enough to participate") - def chain(name, &definition) - define_user_override(name, definition) do |*args, &block| - super(*args, &block) - self - end - end - - private - - # Does the following: - # - # - Defines the named method usign a user-provided block - # in @user_method_defs, which is included as an ancestor - # in the singleton class in which we eval the `define` block. - # - Defines an overriden definition for the same method - # usign the provided `our_def` block. - # - Provides a default `our_def` block for the common case - # of needing to call the user's definition with `@actual` - # as an arg, but only if their block's arity can handle it. - # - # This compiles the user block into an actual method, allowing - # them to use normal method constructs like `return` - # (e.g. for a early guard statement), while allowing us to define - # an override that can provide the wrapped handling - # (e.g. assigning `@actual`, rescueing errors, etc) and - # can `super` to the user's definition. - def define_user_override(method_name, user_def, &our_def) - @user_method_defs.__send__(:define_method, method_name, &user_def) - our_def ||= lambda { super(*actual_arg_for(user_def)) } - define_method(method_name, &our_def) - end - - # Defines deprecated macro methods from RSpec 2 for backwards compatibility. - # @deprecated Use the methods from {Macros} instead. - module Deprecated - # @deprecated Use {Macros#match} instead. - def match_for_should(&definition) - RSpec.deprecate("`match_for_should`", :replacement => "`match`") - match(&definition) - end - - # @deprecated Use {Macros#match_when_negated} instead. - def match_for_should_not(&definition) - RSpec.deprecate("`match_for_should_not`", :replacement => "`match_when_negated`") - match_when_negated(&definition) - end - - # @deprecated Use {Macros#failure_message} instead. - def failure_message_for_should(&definition) - RSpec.deprecate("`failure_message_for_should`", :replacement => "`failure_message`") - failure_message(&definition) - end - - # @deprecated Use {Macros#failure_message_when_negated} instead. - def failure_message_for_should_not(&definition) - RSpec.deprecate("`failure_message_for_should_not`", :replacement => "`failure_message_when_negated`") - failure_message_when_negated(&definition) - end - end - end - - # Defines default implementations of the matcher - # protocol methods for custom matchers. You can - # override any of these using the {RSpec::Matchers::DSL::Macros Macros} methods - # from within an `RSpec::Matchers.define` block. - module DefaultImplementations - # @api private - # Used internally by objects returns by `should` and `should_not`. - def diffable? - false - end - - # The default description. - def description - "#{name_to_sentence}#{to_sentence expected}" - end - - # The default failure message for positive expectations. - def failure_message - "expected #{actual.inspect} to #{name_to_sentence}#{to_sentence expected}" - end - - # The default failure message for negative expectations. - def failure_message_when_negated - "expected #{actual.inspect} not to #{name_to_sentence}#{to_sentence expected}" - end - - # Matchers do not support block expectations by default. You - # must opt-in. - def supports_block_expectations? - false - end - end - - # The class used for custom matchers. The block passed to - # `RSpec::Matchers.define` will be evaluated in the context - # of the singleton class of an instance, and will have the - # {RSpec::Matchers::DSL::Macros Macros} methods available. - class Matcher - # Provides default implementations for the matcher protocol methods. - include DefaultImplementations - - # Allows expectation expressions to be used in the match block. - include RSpec::Matchers - - # Converts matcher name and expected args to an English expresion. - include RSpec::Matchers::Pretty - - # Supports the matcher composability features of RSpec 3+. - include Composable - - # Makes the macro methods available to an `RSpec::Matchers.define` block. - extend Macros - extend Macros::Deprecated - - # Exposes the value being matched against -- generally the object - # object wrapped by `expect`. - attr_reader :actual - - # Exposes the exception raised during the matching by `match_unless_raises`. - # Could be useful to extract details for a failure message. - attr_reader :rescued_exception - - # @api private - def initialize(name, declarations, matcher_execution_context, *expected) - @name = name - @actual = nil - @expected_as_array = expected - @matcher_execution_context = matcher_execution_context - - class << self - # See `Macros#define_user_override` above, for an explanation. - include(@user_method_defs = Module.new) - self - end.class_exec(*expected, &declarations) - end - - # Provides the expected value. This will return an array if - # multiple arguments were passed to the matcher; otherwise it - # will return a single value. - # @see #expected_as_array - def expected - if expected_as_array.size == 1 - expected_as_array[0] - else - expected_as_array - end - end - - # Returns the expected value as an an array. This exists primarily - # to aid in upgrading from RSpec 2.x, since in RSpec 2, `expected` - # always returned an array. - # @see #expected - attr_reader :expected_as_array - - # Adds the name (rather than a cryptic hex number) - # so we can identify an instance of - # the matcher in error messages (e.g. for `NoMethodError`) - def inspect - "#<#{self.class.name} #{name}>" - end - - if RUBY_VERSION.to_f >= 1.9 - # Indicates that this matcher responds to messages - # from the `@matcher_execution_context` as well. - # Also, supports getting a method object for such methods. - def respond_to_missing?(method, include_private=false) - super || @matcher_execution_context.respond_to?(method, include_private) - end - else # for 1.8.7 - # Indicates that this matcher responds to messages - # from the `@matcher_execution_context` as well. - def respond_to?(method, include_private=false) - super || @matcher_execution_context.respond_to?(method, include_private) - end - end - - private - - def actual_arg_for(block) - block.arity.zero? ? [] : [@actual] - end - - # Takes care of forwarding unhandled messages to the - # `@matcher_execution_context` (typically the current - # running `RSpec::Core::Example`). This is needed by - # rspec-rails so that it can define matchers that wrap - # Rails' test helper methods, but it's also a useful - # feature in its own right. - def method_missing(method, *args, &block) - if @matcher_execution_context.respond_to?(method) - @matcher_execution_context.__send__ method, *args, &block - else - super(method, *args, &block) - end - end - end - end - end -end - -RSpec::Matchers.extend RSpec::Matchers::DSL diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/generated_descriptions.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/generated_descriptions.rb deleted file mode 100644 index a17ce18..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/generated_descriptions.rb +++ /dev/null @@ -1,42 +0,0 @@ -module RSpec - module Matchers - class << self - # @private - attr_accessor :last_matcher, :last_expectation_handler - end - - # @api private - # Used by rspec-core to clear the state used to generate - # descriptions after an example. - def self.clear_generated_description - self.last_matcher = nil - self.last_expectation_handler = nil - end - - # @api private - # Generates an an example description based on the last expectation. - # Used by rspec-core's one-liner syntax. - def self.generated_description - return nil if last_expectation_handler.nil? - "#{last_expectation_handler.verb} #{last_description}" - end - - private - - def self.last_description - last_matcher.respond_to?(:description) ? last_matcher.description : <<-MESSAGE -When you call a matcher in an example without a String, like this: - -specify { expect(object).to matcher } - -or this: - -it { is_expected.to matcher } - -RSpec expects the matcher to have a #description method. You should either -add a String to the example this matcher is being used in, or give it a -description method. Then you won't have to suffer this lengthy warning again. -MESSAGE - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/matcher_delegator.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/matcher_delegator.rb deleted file mode 100644 index e7c8a3e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/matcher_delegator.rb +++ /dev/null @@ -1,36 +0,0 @@ -module RSpec - module Matchers - # Provides the necessary plumbing to wrap a matcher with a decorator. - # @private - class MatcherDelegator - attr_reader :base_matcher - - def initialize(base_matcher) - @base_matcher = base_matcher - end - - def method_missing(*args, &block) - base_matcher.__send__(*args, &block) - end - - if ::RUBY_VERSION.to_f > 1.8 - def respond_to_missing?(name, include_all=false) - super || base_matcher.respond_to?(name, include_all) - end - else - def respond_to?(name, include_all=false) - super || base_matcher.respond_to?(name, include_all) - end - end - - def initialize_copy(other) - @base_matcher = @base_matcher.clone - super - end - - # So `===` is delegated via `method_missing`. - undef === - undef == - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/pretty.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/pretty.rb deleted file mode 100644 index bd5c033..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-expectations-3.0.3/lib/rspec/matchers/pretty.rb +++ /dev/null @@ -1,77 +0,0 @@ -module RSpec - module Matchers - # @api private - # Contains logic to facilitate converting ruby symbols and - # objects to english phrases. - module Pretty - # @api private - # Converts a symbol into an english expression. - def split_words(sym) - sym.to_s.gsub(/_/, ' ') - end - module_function :split_words - - # @api private - # Converts a collection of objects into an english expression. - def to_sentence(words) - return " #{words.inspect}" unless words - words = Array(words).map { |w| to_word(w) } - case words.length - when 0 - "" - when 1 - " #{words[0]}" - when 2 - " #{words[0]} and #{words[1]}" - else - " #{words[0...-1].join(', ')}, and #{words[-1]}" - end - end - - # @api private - # Converts the given item to string suitable for use in a list expression. - def to_word(item) - is_matcher_with_description?(item) ? item.description : item.inspect - end - - # @private - # Provides an English expression for the matcher name. - def name_to_sentence - split_words(name) - end - - # @api private - # Provides a name for the matcher. - def name - defined?(@name) ? @name : underscore(self.class.name.split("::").last) - end - - # @private - # Borrowed from ActiveSupport - def underscore(camel_cased_word) - word = camel_cased_word.to_s.dup - word.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') - word.gsub!(/([a-z\d])([A-Z])/, '\1_\2') - word.tr!("-", "_") - word.downcase! - word - end - - private - - def is_matcher_with_description?(object) - RSpec::Matchers.is_a_matcher?(object) && object.respond_to?(:description) - end - - # `{ :a => 5, :b => 2 }.inspect` produces: - # {:a=>5, :b=>2} - # ...but it looks much better as: - # {:a => 5, :b => 2} - # - # This is idempotent and safe to run on a string multiple times. - def improve_hash_formatting(inspect_string) - inspect_string.gsub(/(\S)=>(\S)/, '\1 => \2') - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/.document b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/.document deleted file mode 100644 index 050e204..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/.document +++ /dev/null @@ -1,5 +0,0 @@ -lib/**/*.rb -- -README.md -License.txt -Changelog.md diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/.yardopts b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/.yardopts deleted file mode 100644 index 15f63ee..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/.yardopts +++ /dev/null @@ -1,6 +0,0 @@ ---exclude features ---no-private ---markup markdown -- -Changelog.md -License.txt diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/Changelog.md b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/Changelog.md deleted file mode 100644 index 72bf5b3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/Changelog.md +++ /dev/null @@ -1,752 +0,0 @@ -### 3.0.3 / 2014-07-21 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.2...v3.0.3) - -Bug Fixes: - -* `have_received` matcher will raise "does not implement" errors correctly when - used with verifying doubles and partial doubles. (Xavier Shay, #722) -* Make `double.as_null_object.dup` and `double.as_null_object.clone` - make the copies be null objects. (Myron Marston, #732) -* Don't inadvertently define `BasicObject` in 1.8.7. (Chris Griego, #739) - -### 3.0.2 / 2014-06-19 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.1...v3.0.2) - -Bug Fixes: - -* Fix edge case that triggered "can't add a new key into hash during - iteration" during mock verification. (Sam Phippen, Myron Marston, #711) -* Fix verifying doubles so that when they accidentally leak into another - example, they provide the same clear error message that normal doubles - do. (Myron Marston, #718) -* Make `ordered` work with exact receive counts. (Sam Phippen, #713) - -### 3.0.1 / 2014-06-07 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.0...v3.0.1) - -Bug Fixes: - -* Fix `receive_message_chain(...)` so that it supports `with` just like - `stub_chain` did. (Jon Rowe, #697) -* Fix regression in `expect_any_instance_of` so that it expects the - message on _any_ instance rather than on _every_ instance. - (Myron Marston, #699) - -### 3.0.0 / 2014-06-01 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.0.rc1...v3.0.0) - -Bug Fixes: - -* Fix module prepend detection to work properly on ruby 2.0 for a case - where a module is extended onto itself. (Myron Marston) -* Fix `transfer_nested_constants` option so that transferred constants - get properly reset at the end of the example. (Myron Marston) -* Fix `config.transfer_nested_constants = true` so that you don't - erroneously get errors when stubbing a constant that is not a module - or a class. (Myron Marston) -* Fix regression that caused `double(:class => SomeClass)` to later - trigger infinite recursion. (Myron Marston) -* Fix bug in `have_received(...).with(...).ordered` where it was not - taking the args into account when checking the order. (Myron Marston) -* Fix bug in `have_received(...).ordered` where it was wrongly - considering stubs when checking the order. (Myron Marston) -* Message expectation matchers now show descriptions from argument - matchers when their expectations aren't met. (Jon Rowe) -* Display warning when encountering `TypeError` during instance method - staging on 2.0.0-p195, suffers from https://bugs.ruby-lang.org/issues/8686 - too. (Cezar Halmagean). - -### 3.0.0.rc1 / 2014-05-18 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.0.beta2...v3.0.0.rc1) - -Breaking Changes for 3.0.0: - -* Remove `RSpec::Mocks::TestDouble.extend_onto`. (Myron Marston) -* Remove `RSpec::Mocks::ConstantStubber`. (Jon Rowe) -* Make monkey-patch of Marshal to support dumping of stubbed objects opt-in. - (Xavier Shay) - -Enhancements: - -* Instead of crashing when cleaning up stub methods on a frozen object, it now - issues a warning explaining that it's impossible to clean up the stubs. - (Justin Coyne and Sam Phippen) -* Add meaningful descriptions to `anything`, `duck_type` and `instance_of` argument - matchers. (Jon Rowe) - -Bug Fixes: - -* Fix regression introduced in 3.0.0.beta2 that caused - `double.as_null_object.to_str` to return the double rather - than a string. (Myron Marston) -* Fix bug in `expect(dbl).to receive_message_chain(:foo, :bar)` where it was - not setting an expectation for the last message in the chain. - (Jonathan del Strother) -* Allow verifying partial doubles to have private methods stubbed. (Xavier Shay) -* Fix bug with allowing/expecting messages on Class objects which have had - their singleton class prepended to. (Jon Rowe) -* Fix an issue with 1.8.7 not running implementation blocks on partial doubles. - (Maurício Linhares) -* Prevent `StackLevelTooDeep` errors when stubbing an `any_instance` method that's - accessed in `inspect` by providing our own inspect output. (Jon Rowe) -* Fix bug in `any_instance` logic that did not allow you to mock or stub - private methods if `verify_partial_doubles` was configured. (Oren Dobzinski) -* Include useful error message when trying to observe an unimplemented method - on an any instance. (Xavier Shay) -* Fix `and_call_original` to work properly when multiple classes in an - inheritance hierarchy have been stubbed with the same method. (Myron Marston) -* Fix `any_instance` so that it updates existing instances that have - already been stubbed. (Myron Marston) -* Fix verified doubles so that their class name is included in failure - messages. (Myron Marston) -* Fix `expect_any_instance_of` so that when the message is received - on an individual instance that has been directly stubbed, it still - satisfies the expectation. (Sam Phippen, Myron Marston) -* Explicitly disallow using `any_instance` to mock or stub a method - that is defined on a module prepended onto the class. This triggered - `SystemStackError` before and is very hard to support so we are not - supporting it at this time. (Myron Marston) - -### 3.0.0.beta2 / 2014-02-17 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v3.0.0.beta1...v3.0.0.beta2) - -Breaking Changes for 3.0.0: - -* Rename `RSpec::Mocks::Mock` to `RSpec::Mocks::Double`. (Myron Marston) -* Change how to integrate rspec-mocks in other test frameworks. You now - need to include `RSpec::Mocks::ExampleMethods` in your test context. - (Myron Marston) -* Prevent RSpec mocks' doubles and partial doubles from being used outside of - the per-test lifecycle (e.g. from a `before(:all)` hook). (Sam Phippen) -* Remove the `host` argument of `RSpec::Mocks.setup`. Instead - `RSpec::Mocks::ExampleMethods` should be included directly in the scope where - RSpec's mocking capabilities are used. (Sam Phippen) -* Make test doubles raise errors if you attempt to use them after they - get reset, to help surface issues when you accidentally retain - references to test doubles and attempt to reuse them in another - example. (Myron Marston) -* Remove support for `and_return { value }` and `and_return` without arguments. (Yuji Nakayama) - -Enhancements: - -* Add `receive_message_chain` which provides the functionality of the old - `stub_chain` for the new allow/expect syntax. Use it like so: `allow(...).to - receive_message_chain(:foo, :bar, :bazz)`. (Sam Phippen). -* Change argument matchers to use `===` as their primary matching - protocol, since their semantics mirror that of a case or rescue statement - (which uses `===` for matching). (Myron Marston) -* Add `RSpec::Mocks.with_temporary_scope`, which allows you to create - temporary rspec-mocks scopes in arbitrary places (such as a - `before(:all)` hook). (Myron Marston) -* Support keyword arguments when checking arity with verifying doubles. - (Xavier Shay) - -Bug Fixes: - -* Fix regression in 3.0.0.beta1 that caused `double("string_name" => :value)` - to stop working. (Xavier Shay) -* Fix the way rspec-mocks and rspec-core interact so that if users - define a `let` with the same name as one of the methods - from `RSpec::Mocks::ArgumentMatchers`, the user's `let` takes - precedence. (Michi Huber, Myron Marston) -* Fix verified doubles so that their methods match the visibility - (public, protected or private) of the interface they verify - against. (Myron Marston) -* Fix verified null object doubles so that they do not wrongly - report that they respond to anything. They only respond to methods - available on the interface they verify against. (Myron Marston) -* Fix deprecation warning for use of old `:should` syntax w/o explicit - config so that it no longer is silenced by an extension gem such - as rspec-rails when it calls `config.add_stub_and_should_receive_to`. - (Sam Phippen) -* Fix `expect` syntax so that it does not wrongly emit a "You're - overriding a previous implementation for this stub" warning when - you are not actually doing that. (Myron Marston) -* Fix `any_instance.unstub` when used on sub classes for whom the super - class has had `any_instance.stub` invoked on. (Jon Rowe) -* Fix regression in `stub_chain`/`receive_message_chain` that caused - it to raise an `ArgumentError` when passing args to the stubbed - methods. (Sam Phippen) -* Correct stub of undefined parent modules all the way down when stubbing a - nested constant. (Xavier Shay) -* Raise `VerifyingDoubleNotDefinedError` when a constant is not defined for - a verifying class double. (Maurício Linhares) -* Remove `Double#to_str`, which caused confusing `raise some_double` - behavior. (Maurício Linhares) - -### 3.0.0.beta1 / 2013-11-07 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.2...v3.0.0.beta1) - -Breaking Changes for 3.0.0: - -* Raise an explicit error if `should_not_receive(...).and_return` is used. (Sam - Phippen) -* Remove 1.8.6 workarounds. (Jon Rowe) -* Remove `stub!` and `unstub!`. (Sam Phippen) -* Remove `mock(name, methods)` and `stub(name, methods)`, leaving - `double(name, methods)` for creating test doubles. (Sam Phippen, Michi Huber) -* Remove `any_number_of_times` since `should_receive(:msg).any_number_of_times` - is really a stub in a mock's clothing. (Sam Phippen) -* Remove support for re-using the same null-object test double in multiple - examples. Test doubles are designed to only live for one example. - (Myron Marston) -* Make `at_least(0)` raise an error. (Sam Phippen) -* Remove support for `require 'spec/mocks'` which had been kept - in place for backwards compatibility with RSpec 1. (Myron Marston) -* Blocks provided to `with` are always used as implementation. (Xavier Shay) -* The config option (added in 2.99) to yield the receiver to - `any_instance` implementation blocks now defaults to "on". (Sam Phippen) - -Enhancements: - -* Allow the `have_received` matcher to use a block to set further expectations - on arguments. (Tim Cowlishaw) -* Provide `instance_double` and `class_double` to create verifying doubles, - ported from `rspec-fire`. (Xavier Shay) -* `as_null_object` on a verifying double only responds to defined methods. - (Xavier Shay) -* Provide `object_double` to create verified doubles of specific object - instances. (Xavier Shay) -* Provide `verify_partial_doubles` configuration that provides `object_double` - like verification behaviour on partial doubles. (Xavier Shay) -* Improved performance of double creation, particularly those with many - attributes. (Xavier Shay) -* Default value of `transfer_nested_constants` option for constant stubbing can - be configured. (Xavier Shay) -* Messages can be allowed or expected on in bulk via - `receive_messages(:message => :value)`. (Jon Rowe) -* `allow(Klass.any_instance)` and `expect(Klass.any_instance)` now print a - warning. This is usually a mistake, and users usually want - `allow_any_instance_of` or `expect_any_instance_of` instead. (Sam Phippen) -* `instance_double` and `class_double` raise `ArgumentError` if the underlying - module is loaded and the arity of the method being invoked does not match the - arity of the method as it is actually implemented. (Andy Lindeman) -* Spies can now check their invocation ordering is correct. (Jon Rowe) - -Deprecations: - -* Using the old `:should` syntax without explicitly configuring it - is deprecated. It will continue to work but will emit a deprecation - warning in RSpec 3 if you do not explicitly enable it. (Sam Phippen) - -Bug Fixes: - -* Fix `and_call_original` to handle a complex edge case involving - singleton class ancestors. (Marc-André Lafortune, Myron Marston) -* When generating an error message for unexpected arguments, - use `#inspect` rather than `#description` if `#description` - returns `nil` or `''` so that you still get a useful message. - (Nick DeLuca) - -### 2.99.2 / 2014-07-21 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.1...v2.99.2) - -Enhancements: - -* Warn about upcoming change to `#===` matching and `DateTime#===` behaviour. - (Jon Rowe, #735) - -### 2.99.1 / 2014-06-12 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0...v2.99.1) - -Bug Fixes: - -* Fix bug that caused errors at the end of each example - when a `double.as_null_object` had been frozen. (Yuji Nakayama, #698) - -Deprecations: - -* Deprecate freezing a test double. (Yuji Nakayama, #698) - -### 2.99.0 / 2014-06-01 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0.rc1...v2.99.0) - -No changes. Just taking it out of pre-release. - -### 2.99.0.rc1 / 2014-05-18 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0.beta2...v2.99.0.rc1) - -Deprecations: - -* Deprecate `RSpec::Mocks::TestDouble.extend_onto`. (Myron Marston) -* Deprecate `RSpec::Mocks::ConstantStubber`. (Jon Rowe) -* Deprecate `Marshal.dump` monkey-patch without opt-in. (Xavier Shay) - -### 2.99.0.beta2 / 2014-02-17 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.99.0.beta1...v2.99.0.beta2) - -Deprecations: - -* Deprecate `RSpec::Mocks::Mock` in favor of `RSpec::Mocks::Double`. - (Myron Marston) -* Deprecate the `host` argument of `RSpec::Mocks.setup`. Instead - `RSpec::Mocks::ExampleMethods` should be included directly in the scope where - RSpec's mocking capabilities are used. (Sam Phippen) -* Deprecate using any of rspec-mocks' features outside the per-test - lifecycle (e.g. from a `before(:all)` hook). (Myron Marston) -* Deprecate re-using a test double in another example. (Myron Marston) -* Deprecate `and_return { value }` and `and_return` without arguments. (Yuji Nakayama) - -### 2.99.0.beta1 / 2013-11-07 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.4...v2.99.0.beta1) - -Deprecations - -* Expecting to use lambdas or other strong arity implementations for stub - methods with mis-matched arity is deprecated and support for them will be - removed in 3.0. Either provide the right amount of arguments or use a weak - arity implementation (methods with splats or procs). (Jon Rowe) -* Using the same test double instance in multiple examples is deprecated. Test - doubles are only meant to live for one example. The mocks and stubs have - always been reset between examples; however, in 2.x the `as_null_object` - state was not reset and some users relied on this to have a null object - double that is used for many examples. This behavior will be removed in 3.0. - (Myron Marston) -* Print a detailed warning when an `any_instance` implementation block is used - when the new `yield_receiver_to_any_instance_implementation_blocks` config - option is not explicitly set, as RSpec 3.0 will default to enabling this new - feature. (Sam Phippen) - -Enhancements: - -* Add a config option to yield the receiver to `any_instance` implementation - blocks. (Sam Phippen) - -### 2.14.6 / 2014-02-20 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.5...v2.14.6) - -Bug Fixes: - -* Ensure `any_instance` method stubs and expectations are torn down regardless of - expectation failures. (Sam Phippen) - -### 2.14.5 / 2014-02-01 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.4...v2.14.5) - -Bug Fixes: - -* Fix regression that caused block implementations to not receive all - args on 1.8.7 if the block also receives a block, due to Proc#arity - reporting `1` no matter how many args the block receives if it - receives a block, too. (Myron Marston) - -### 2.14.4 / 2013-10-15 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.3...v2.14.4) - -Bug Fixes: - -* Fix issue where unstubing methods on "any instances" would not - remove stubs on existing instances (Jon Rowe) -* Fix issue with receive(:message) do ... end precedence preventing - the usage of modifications (`and_return` etc) (Jon Rowe) - -### 2.14.3 / 2013-08-08 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.2...v2.14.3) - -Bug Fixes: - -* Fix stubbing some instance methods for classes whose hierarchy includes - a prepended Module (Bradley Schaefer) - -### 2.14.2 / 2013-07-30 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.1...v2.14.2) - -Bug Fixes: - -* Fix `as_null_object` doubles so that they return `nil` from `to_ary` - (Jon Rowe). -* Fix regression in 2.14 that made `stub!` (with an implicit receiver) - return a test double rather than stub a method (Myron Marston). - -### 2.14.1 / 2013-07-07 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.0...v2.14.1) - -Bug Fixes: - -* Restore `double.as_null_object` behavior from 2.13 and earlier: a - double's nullness persisted between examples in earlier examples. - While this is not an intended use case (test doubles are meant to live - for only one example), we don't want to break behavior users rely - on in a minor relase. This will be deprecated in 2.99 and removed - in 3.0. (Myron Marston) - -### 2.14.0 / 2013-07-06 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.14.0.rc1...v2.14.0) - -Enhancements: - -* Document test spies in the readme. (Adarsh Pandit) -* Add an `array_including` matcher. (Sam Phippen) -* Add a syntax-agnostic API for mocking or stubbing a method. This is - intended for use by libraries such as rspec-rails that need to mock - or stub a method, and work regardless of the syntax the user has - configured (Paul Annesley, Myron Marston and Sam Phippen). - -Bug Fixes: - -* Fix `double` so that it sets up passed stubs correctly regardless of - the configured syntax (Paul Annesley). -* Allow a block implementation to be used in combination with - `and_yield`, `and_raise`, `and_return` or `and_throw`. This got fixed - in 2.13.1 but failed to get merged into master for the 2.14.0.rc1 - release (Myron Marston). -* `Marshal.dump` does not unnecessarily duplicate objects when rspec-mocks has - not been fully initialized. This could cause errors when using `spork` or - similar preloading gems (Andy Lindeman). - -### 2.14.0.rc1 / 2013-05-27 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.13.0...v2.14.0.rc1) - -Enhancements: - -* Refactor internals so that the mock proxy methods and state are held - outside of the mocked object rather than inside it. This paves the way - for future syntax enhancements and removes the need for some hacky - work arounds for `any_instance` dup'ing and `YAML` serialization, - among other things. Note that the code now relies upon `__id__` - returning a unique, consistent value for any object you want to - mock or stub (Myron Marston). -* Add support for test spies. This allows you to verify a message - was received afterwards using the `have_received` matcher. - Note that you must first stub the method or use a null double. - (Joe Ferris and Joël Quenneville) -* Make `at_least` and `at_most` style receive expectations print that they were - expecting at least or at most some number of calls, rather than just the - number of calls given in the expectation (Sam Phippen) -* Make `with` style receive expectations print the args they were expecting, and - the args that they got (Sam Phippen) -* Fix some warnings seen under ruby 2.0.0p0 (Sam Phippen). -* Add a new `:expect` syntax for message expectations - (Myron Marston and Sam Phippen). - -Bug fixes - -* Fix `any_instance` so that a frozen object can be `dup`'d when methods - have been stubbed on that type using `any_instance` (Jon Rowe). -* Fix `and_call_original` so that it properly raises an `ArgumentError` - when the wrong number of args are passed (Jon Rowe). -* Fix `double` on 1.9.2 so you can wrap them in an Array - using `Array(my_double)` (Jon Rowe). -* Fix `stub_const` and `hide_const` to handle constants that redefine `send` - (Sam Phippen). -* Fix `Marshal.dump` extension so that it correctly handles nil. - (Luke Imhoff, Jon Rowe) -* Fix isolation of `allow_message_expectations_on_nil` (Jon Rowe) -* Use inspect to format actual arguments on expectations in failure messages (#280, Ben Langfeld) -* Protect against improperly initialised test doubles (#293) (Joseph Shraibman and Jon Rowe) - -Deprecations - -* Deprecate `stub` and `mock` as aliases for `double`. `double` is the - best term for creating a test double, and it reduces confusion to - have only one term (Michi Huber). -* Deprecate `stub!` and `unstub!` in favor of `stub` and `unstub` - (Jon Rowe). -* Deprecate `at_least(0).times` and `any_number_of_times` (Michi Huber). - -### 2.13.1 / 2013-04-06 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.13.0...v2.13.1) - -Bug fixes - -* Allow a block implementation to be used in combination with - `and_yield`, `and_raise`, `and_return` or `and_throw` (Myron Marston). - -### 2.13.0 / 2013-02-23 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.12.2...v2.13.0) - -Bug fixes - -* Fix bug that caused weird behavior when a method that had - previously been stubbed with multiple return values (e.g. - `obj.stub(:foo).and_return(1, 2)`) was later mocked with a - single return value (e.g. `obj.should_receive(:foo).once.and_return(1)`). - (Myron Marston) -* Fix bug related to a mock expectation for a method that already had - multiple stubs with different `with` constraints. Previously, the - first stub was used, even though it may not have matched the passed - args. The fix defers this decision until the message is received so - that the proper stub response can be chosen based on the passed - arguments (Myron Marston). -* Do not call `nil?` extra times on a mocked object, in case `nil?` - itself is expected a set number of times (Myron Marston). -* Fix `missing_default_stub_error` message so array args are handled - properly (Myron Marston). -* Explicitly disallow `any_instance.unstub!` (Ryan Jones). -* Fix `any_instance` stubbing so that it works with `Delegator` - subclasses (Myron Marston). -* Fix `and_call_original` so that it works with `Delegator` subclasses - (Myron Marston). -* Fix `any_instance.should_not_receive` when `any_instance.should_receive` - is used on the same class in the same example. Previously it would - wrongly report a failure even when the message was not received - (Myron Marston). - -### 2.12.2 / 2013-01-27 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.12.1...v.2.12.2) - -Bug fixes - -* Fix `and_call_original` to work properly for methods defined - on a module extended onto an object instance (Myron Marston). -* Fix `stub_const` with an undefined constnat name to work properly - with constant strings that are prefixed with `::` -- and edge case - I missed in the bug fix in the 2.12.1 release (Myron Marston). -* Ensure method visibility on a partial mock is restored after reseting - method stubs, even on a singleton module (created via `extend self`) - when the method visibility differs between the instance and singleton - versions (Andy Lindeman). - -### 2.12.1 / 2012-12-21 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.12.0...v2.12.1) - -Bug fixes - -* Fix `any_instance` to support `and_call_original`. - (Myron Marston) -* Properly restore stubbed aliased methods on rubies - that report the incorrect owner (Myron Marston and Andy Lindeman). -* Fix `hide_const` and `stub_const` with a defined constnat name to - work properly with constant strings that are prefixed with `::` (Myron Marston). - -### 2.12.0 / 2012-11-12 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.11.3...v2.12.0) - -Enhancements - -* `and_raise` can accept an exception class and message, more closely - matching `Kernel#raise` (e.g., `foo.stub(:bar).and_raise(RuntimeError, "message")`) - (Bas Vodde) -* Add `and_call_original`, which will delegate the message to the - original method (Myron Marston). - -Deprecations: - -* Add deprecation warning when using `and_return` with `should_not_receive` - (Neha Kumari) - -### 2.11.3 / 2012-09-19 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.11.2...v2.11.3) - -Bug fixes - -* Fix `:transfer_nested_constants` option of `stub_const` so that it - doesn't blow up when there are inherited constants. (Myron Marston) -* `any_instance` stubs can be used on classes that override `Object#method`. - (Andy Lindeman) -* Methods stubbed with `any_instance` are unstubbed after the test finishes. - (Andy Lindeman) -* Fix confusing error message when calling a mocked class method an - extra time with the wrong arguments (Myron Marston). - -### 2.11.2 / 2012-08-11 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.11.1...v2.11.2) - -Bug fixes - -* Don't modify `dup` on classes that don't support `dup` (David Chelimsky) -* Fix `any_instance` so that it works properly with methods defined on - a superclass. (Daniel Eguzkiza) -* Fix `stub_const` so that it works properly for nested constants that - share a name with a top-level constant (e.g. "MyGem::Hash"). (Myron - Marston) - -### 2.11.1 / 2012-07-09 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.11.0...v2.11.1) - -Bug fixes - -* Fix `should_receive` so that when it is called on an `as_null_object` - double with no implementation, and there is a previous explicit stub - for the same method, the explicit stub remains (rather than being - overriden with the null object implementation--`return self`). (Myron Marston) - -### 2.11.0 / 2012-07-07 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.10.1...v2.11.0) - -Enhancements - -* Expose ArgumentListMatcher as a formal API - * supports use by 3rd party mock frameworks like Surrogate -* Add `stub_const` API to stub constants for the duration of an - example (Myron Marston). - -Bug fixes - -* Fix regression of edge case behavior. `double.should_receive(:foo) { a }` - was causing a NoMethodError when `double.stub(:foo).and_return(a, b)` - had been setup before (Myron Marston). -* Infinite loop generated by using `any_instance` and `dup`. (Sidu Ponnappa @kaiwren) -* `double.should_receive(:foo).at_least(:once).and_return(a)` always returns a - even if `:foo` is already stubbed. -* Prevent infinite loop when interpolating a null double into a string - as an integer (`"%i" % double.as_null_object`). (Myron Marston) -* Fix `should_receive` so that null object behavior (e.g. returning - self) is preserved if no implementation is given (Myron Marston). -* Fix `and_raise` so that it raises `RuntimeError` rather than - `Exception` by default, just like ruby does. (Andrew Marshall) - -### 2.10.1 / 2012-05-05 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.10.0...v2.10.1) - -Bug fixes - -* fix regression of edge case behavior - (https://github.com/rspec/rspec-mocks/issues/132) - * fixed failure of `object.should_receive(:message).at_least(0).times.and_return value` - * fixed failure of `object.should_not_receive(:message).and_return value` - -### 2.10.0 / 2012-05-03 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.9.0...v2.10.0) - -Bug fixes - -* fail fast when an `exactly` or `at_most` expectation is exceeded - -### 2.9.0 / 2012-03-17 -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.8.0...v2.9.0) - -Enhancements - -* Support order constraints across objects (preethiramdev) - -Bug fixes - -* Allow a `as_null_object` to be passed to `with` -* Pass proc to block passed to stub (Aubrey Rhodes) -* Initialize child message expectation args to match any args (#109 - - preethiramdev) - -### 2.8.0 / 2012-01-04 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.8.0.rc2...v2.8.0) - -No changes for this release. Just releasing with the other rspec gems. - -### 2.8.0.rc2 / 2011-12-19 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.8.0.rc1...v2.8.0.rc2) - -No changes for this release. Just releasing with the other rspec gems. - -### 2.8.0.rc1 / 2011-11-06 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.7.0...v2.8.0.rc1) - -Enhancements - -* Eliminate Ruby warnings (Matijs van Zuijlen) - -### 2.7.0 / 2011-10-16 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.6.0...v2.7.0) - -Enhancements - -* Use `__send__` rather than `send` (alextk) -* Add support for `any_instance.stub_chain` (Sidu Ponnappa) -* Add support for `any_instance` argument matching based on `with` (Sidu - Ponnappa and Andy Lindeman) - -Changes - -* Check for `failure_message_for_should` or `failure_message` instead of - `description` to detect a matcher (Tibor Claassen) - -Bug fixes - -* pass a hash to `any_instance.stub`. (Justin Ko) -* allow `to_ary` to be called without raising `NoMethodError` (Mikhail - Dieterle) -* `any_instance` properly restores private methods (Sidu Ponnappa) - -### 2.6.0 / 2011-05-12 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.5.0...v2.6.0) - -Enhancements - -* Add support for `any_instance.stub` and `any_instance.should_receive` (Sidu - Ponnappa and Andy Lindeman) - -Bug fixes - -* fix bug in which multiple chains with shared messages ending in hashes failed - to return the correct value - -### 2.5.0 / 2011-02-05 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.4.0...v2.5.0) - -Bug fixes - -* message expectation counts now work in combination with a stub (Damian - Nurzynski) -* fix failure message when message received with incorrect args (Josep M. - Bach) - -### 2.4.0 / 2011-01-02 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.3.0...v2.4.0) - -No functional changes in this release, which was made to align with the -rspec-core-2.4.0 release. - -### 2.3.0 / 2010-12-12 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.2.0...v2.3.0) - -Bug fixes - -* Fix our Marshal extension so that it does not interfere with objects that - have their own `@mock_proxy` instance variable. (Myron Marston) - -### 2.2.0 / 2010-11-28 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.1.0...v2.2.0) - -Enhancements - -* Added "rspec/mocks/standalone" for exploring the rspec-mocks in irb. - -Bug fix - -* Eliminate warning on splat args without parens (Gioele Barabucci) -* Fix bug where `obj.should_receive(:foo).with(stub.as_null_object)` would pass - with a false positive. - -### 2.1.0 / 2010-11-07 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.0.1...v2.1.0) - -Bug fixes - -* Fix serialization of stubbed object (Josep M Bach) - -### 2.0.0 / 2010-10-10 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.0.0.beta.22...v2.0.0) - -### 2.0.0.rc / 2010-10-05 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.0.0.beta.22...v2.0.0.rc) - -Enhancements - -* support passing a block to an expectation block (Nicolas Braem) - * `obj.should_receive(:msg) {|&block| ... }` - -Bug fixes - -* Fix YAML serialization of stub (Myron Marston) -* Fix rdoc rake task (Hans de Graaff) - -### 2.0.0.beta.22 / 2010-09-12 - -[Full Changelog](http://github.com/rspec/rspec-mocks/compare/v2.0.0.beta.20...v2.0.0.beta.22) - -Bug fixes - -* fixed regression that broke `obj.stub_chain(:a, :b => :c)` -* fixed regression that broke `obj.stub_chain(:a, :b) { :c }` -* `respond_to?` always returns true when using `as_null_object` diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/License.txt b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/License.txt deleted file mode 100644 index 91cfc94..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/License.txt +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 David Chelimsky, Myron Marston -Copyright (c) 2006 David Chelimsky, The RSpec Development Team -Copyright (c) 2005 Steven Baker - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/README.md b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/README.md deleted file mode 100644 index 036dca5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/README.md +++ /dev/null @@ -1,380 +0,0 @@ -# RSpec Mocks [![Build Status](https://secure.travis-ci.org/rspec/rspec-mocks.png?branch=master)](http://travis-ci.org/rspec/rspec-mocks) [![Code Climate](https://codeclimate.com/github/rspec/rspec-mocks.png)](https://codeclimate.com/github/rspec/rspec-mocks) [![Inline docs](http://inch-pages.github.io/github/rspec/rspec-mocks.png)](http://inch-pages.github.io/github/rspec/rspec-mocks) - -rspec-mocks is a test-double framework for rspec with support for method stubs, -fakes, and message expectations on generated test-doubles and real objects -alike. - -## Install - - gem install rspec # for rspec-core, rspec-expectations, rspec-mocks - gem install rspec-mocks # for rspec-mocks only - -## Test Doubles - -A test double is an object that stands in for another object in your system -during a code example. Use the `double` method, passing in an optional identifier, to create one: - -```ruby -book = double("book") -``` - -Most of the time you will want some confidence that your doubles resemble an -existing object in your system. Verifying doubles are provided for this -purpose. If the existing object is available, they will prevent you from adding -stubs and expectations for methods that do not exist or that have an invalid -number of parameters. - -```ruby -book = instance_double("Book", :pages => 250) -``` - -Verifying doubles have some clever tricks to enable you to both test in -isolation without your dependencies loaded while still being able to validate -them against real objects. More detail is available in [their -documentation](https://github.com/rspec/rspec-mocks/blob/master/features/verifying_doubles). - -## Method Stubs - -A method stub is an implementation that returns a pre-determined value. Method -stubs can be declared on test doubles or real objects using the same syntax. -rspec-mocks supports 3 forms for declaring method stubs: - -```ruby -allow(book).to receive(:title) { "The RSpec Book" } -allow(book).to receive(:title).and_return("The RSpec Book") -``` - -You can also use this shortcut, which creates a test double and declares a -method stub in one statement: - -```ruby -book = double("book", :title => "The RSpec Book") -``` - -The first argument is a name, which is used for documentation and appears in -failure messages. If you don't care about the name, you can leave it out, -making the combined instantiation/stub declaration very terse: - -```ruby -double(:foo => 'bar') -``` - -This is particularly nice when providing a list of test doubles to a method -that iterates through them: - -```ruby -order.calculate_total_price(double(:price => 1.99), double(:price => 2.99)) -``` - -## Consecutive return values - -When a stub might be invoked more than once, you can provide additional -arguments to `and_return`. The invocations cycle through the list. The last -value is returned for any subsequent invocations: - -```ruby -allow(die).to receive(:roll).and_return(1, 2, 3) -die.roll # => 1 -die.roll # => 2 -die.roll # => 3 -die.roll # => 3 -die.roll # => 3 -``` - -To return an array in a single invocation, declare an array: - -```ruby -allow(team).to receive(:players).and_return([double(:name => "David")]) -``` - -## Message Expectations - -A message expectation is an expectation that the test double will receive a -message some time before the example ends. If the message is received, the -expectation is satisfied. If not, the example fails. - -```ruby -validator = double("validator") -expect(validator).to receive(:validate) { "02134" } -zipcode = Zipcode.new("02134", validator) -zipcode.valid? -``` - -## Test Spies - -Verifies the given object received the expected message during the course of the -test. The method must have previously been stubbed in order for messages to be -verified. - -Stubbing and verifying messages received in this way implements the Test Spy -pattern. - -```ruby - invitation = double('invitation', :accept => true) - - user.accept_invitation(invitation) - - expect(invitation).to have_received(:accept) - - # You can also use other common message expectations. For example: - expect(invitation).to have_received(:accept).with(mailer) - expect(invitation).to have_received(:accept).twice - expect(invitation).to_not have_received(:accept).with(mailer) -``` - -## Nomenclature - -### Mock Objects and Test Stubs - -The names Mock Object and Test Stub suggest specialized Test Doubles. i.e. -a Test Stub is a Test Double that only supports method stubs, and a Mock -Object is a Test Double that supports message expectations and method -stubs. - -There is a lot of overlapping nomenclature here, and there are many -variations of these patterns (fakes, spies, etc). Keep in mind that most of -the time we're talking about method-level concepts that are variations of -method stubs and message expectations, and we're applying to them to _one_ -generic kind of object: a Test Double. - -### Test-Specific Extension - -a.k.a. Partial Double, a Test-Specific Extension is an extension of a -real object in a system that is instrumented with test-double like -behaviour in the context of a test. This technique is very common in Ruby -because we often see class objects acting as global namespaces for methods. -For example, in Rails: - -```ruby -person = double("person") -allow(Person).to receive(:find) { person } -``` - -In this case we're instrumenting Person to return the person object we've -defined whenever it receives the `find` message. We can also set a message -expectation so that the example fails if `find` is not called: - -```ruby -person = double("person") -expect(Person).to receive(:find) { person } -``` - -RSpec replaces the method we're stubbing or mocking with its own -test-double-like method. At the end of the example, RSpec verifies any message -expectations, and then restores the original methods. - -## Expecting Arguments - -```ruby -expect(double).to receive(:msg).with(*args) -expect(double).to_not receive(:msg).with(*args) -``` - -You can set multiple expectations for the same message if you need to: - -```ruby -expect(double).to receive(:msg).with("A", 1, 3) -expect(double).to receive(:msg).with("B", 2, 4) -``` - -## Argument Matchers - -Arguments that are passed to `with` are compared with actual arguments -received using ==. In cases in which you want to specify things about the -arguments rather than the arguments themselves, you can use any of the -matchers that ship with rspec-expectations. They don't all make syntactic -sense (they were primarily designed for use with RSpec::Expectations), but -you are free to create your own custom RSpec::Matchers. - -rspec-mocks also adds some keyword Symbols that you can use to -specify certain kinds of arguments: - -```ruby -expect(double).to receive(:msg).with(no_args()) -expect(double).to receive(:msg).with(any_args()) -expect(double).to receive(:msg).with(1, kind_of(Numeric), "b") #2nd argument can be any kind of Numeric -expect(double).to receive(:msg).with(1, boolean(), "b") #2nd argument can be true or false -expect(double).to receive(:msg).with(1, /abc/, "b") #2nd argument can be any String matching the submitted Regexp -expect(double).to receive(:msg).with(1, anything(), "b") #2nd argument can be anything at all -expect(double).to receive(:msg).with(1, duck_type(:abs, :div), "b") - #2nd argument can be object that responds to #abs and #div -``` - -## Receive Counts - -```ruby -expect(double).to receive(:msg).once -expect(double).to receive(:msg).twice -expect(double).to receive(:msg).exactly(n).times -expect(double).to receive(:msg).at_least(:once) -expect(double).to receive(:msg).at_least(:twice) -expect(double).to receive(:msg).at_least(n).times -expect(double).to receive(:msg).at_most(:once) -expect(double).to receive(:msg).at_most(:twice) -expect(double).to receive(:msg).at_most(n).times -expect(double).to receive(:msg).any_number_of_times -``` - -## Ordering - -```ruby -expect(double).to receive(:msg).ordered -expect(double).to receive(:other_msg).ordered - # This will fail if the messages are received out of order -``` - -This can include the same message with different arguments: - -```ruby -expect(double).to receive(:msg).with("A", 1, 3).ordered -expect(double).to receive(:msg).with("B", 2, 4).ordered -``` - -## Setting Responses - -Whether you are setting a message expectation or a method stub, you can -tell the object precisely how to respond. The most generic way is to pass -a block to `receive`: - -```ruby -expect(double).to receive(:msg) { value } -``` - -When the double receives the `msg` message, it evaluates the block and returns -the result. - -```ruby -expect(double).to receive(:msg).and_return(value) -expect(double).to receive(:msg).exactly(3).times.and_return(value1, value2, value3) - # returns value1 the first time, value2 the second, etc -expect(double).to receive(:msg).and_raise(error) - # error can be an instantiated object or a class - # if it is a class, it must be instantiable with no args -expect(double).to receive(:msg).and_throw(:msg) -expect(double).to receive(:msg).and_yield(values, to, yield) -expect(double).to receive(:msg).and_yield(values, to, yield).and_yield(some, other, values, this, time) - # for methods that yield to a block multiple times -``` - -Any of these responses can be applied to a stub as well - -```ruby -allow(double).to receive(:msg).and_return(value) -allow(double).to receive(:msg).and_return(value1, value2, value3) -allow(double).to receive(:msg).and_raise(error) -allow(double).to receive(:msg).and_throw(:msg) -allow(double).to receive(:msg).and_yield(values, to, yield) -allow(double).to receive(:msg).and_yield(values, to, yield).and_yield(some, other, values, this, time) -``` - -## Arbitrary Handling - -Once in a while you'll find that the available expectations don't solve the -particular problem you are trying to solve. Imagine that you expect the message -to come with an Array argument that has a specific length, but you don't care -what is in it. You could do this: - -```ruby -expect(double).to receive(:msg) do |arg| - expect(arg.size).to eq 7 -end -``` - -If the method being stubbed itself takes a block, and you need to yield to it -in some special way, you can use this: - -```ruby -expect(double).to receive(:msg) do |&arg| - begin - arg.call - ensure - # cleanup - end -end -``` - -## Delegating to the Original Implementation - -When working with a partial mock object, you may occasionally -want to set a message expecation without interfering with how -the object responds to the message. You can use `and_call_original` -to achieve this: - -```ruby -expect(Person).to receive(:find).and_call_original -Person.find # => executes the original find method and returns the result -``` - -## Combining Expectation Details - -Combining the message name with specific arguments, receive counts and responses -you can get quite a bit of detail in your expectations: - -```ruby -expect(double).to receive(:<<).with("illegal value").once.and_raise(ArgumentError) -``` - -While this is a good thing when you really need it, you probably don't really -need it! Take care to specify only the things that matter to the behavior of -your code. - -## Stubbing and Hiding Constants - -See the [mutating constants -README](https://github.com/rspec/rspec-mocks/blob/master/features/mutating_constants/README.md) -for info on this feature. - -## Use `before(:example)`, not `before(:context)` - -Stubs in `before(:context)` are not supported. The reason is that all stubs and mocks get cleared out after each example, so any stub that is set in `before(:context)` would work in the first example that happens to run in that group, but not for any others. - -Instead of `before(:context)`, use `before(:example)`. - -## Settings mocks or stubs on any instance of a class - -rspec-mocks provides two methods, `allow_any_instance_of` and -`expect_any_instance_of`, that will allow you to stub or mock any instance -of a class. They are used in place of `allow` or `expect`: - -```ruby -allow_any_instance_of(Widget).to receive(:name).and_return("Wibble") -expect_any_instance_of(Widget).to receive(:name).and_return("Wobble") -``` - -These methods add the appropriate stub or expectation to all instances of -`Widget`. - -This feature is sometimes useful when working with legacy code, though in -general we discourage its use for a number of reasons: - -* The `rspec-mocks` API is designed for individual object instances, but this - feature operates on entire classes of objects. As a result there are some - sematically confusing edge cases. For example in - `expect_any_instance_of(Widget).to receive(:name).twice` it isn't clear - whether each specific instance is expected to receive `name` twice, or if two - receives total are expected. (It's the former.) -* Using this feature is often a design smell. It may be - that your test is trying to do too much or that the object under test is too - complex. -* It is the most complicated feature of `rspec-mocks`, and has historically - received the most bug reports. (None of the core team actively use it, - which doesn't help.) - - -## Further Reading - -There are many different viewpoints about the meaning of mocks and stubs. If -you are interested in learning more, here is some recommended reading: - -* Mock Objects: http://www.mockobjects.com/ -* Endo-Testing: http://stalatest.googlecode.com/svn/trunk/Literatur/mockobjects.pdf -* Mock Roles, Not Objects: http://jmock.org/oopsla2004.pdf -* Test Double: http://www.martinfowler.com/bliki/TestDouble.html -* Test Double Patterns: http://xunitpatterns.com/Test%20Double%20Patterns.html -* Mocks aren't stubs: http://www.martinfowler.com/articles/mocksArentStubs.html - -## Also see - -* [http://github.com/rspec/rspec](http://github.com/rspec/rspec) -* [http://github.com/rspec/rspec-core](http://github.com/rspec/rspec-core) -* [http://github.com/rspec/rspec-expectations](http://github.com/rspec/rspec-expectations) diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks.rb deleted file mode 100644 index 17b2831..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks.rb +++ /dev/null @@ -1,126 +0,0 @@ -require 'rspec/support' -RSpec::Support.require_rspec_support 'caller_filter' -RSpec::Support.require_rspec_support 'warnings' -RSpec::Support.require_rspec_support 'ruby_features' - -RSpec::Support.define_optimized_require_for_rspec(:mocks) { |f| require_relative f } - -%w[ - instance_method_stasher - method_double - argument_matchers - example_methods - proxy - test_double - argument_list_matcher - message_expectation - order_group - error_generator - space - mutate_const - targets - syntax - configuration - verifying_double - version -].each { |name| RSpec::Support.require_rspec_mocks name } - -# Share the top-level RSpec namespace, because we are a core supported -# extension. -module RSpec - # Contains top-level utility methods. While this contains a few - # public methods, these are not generally meant to be called from - # a test or example. They exist primarily for integration with - # test frameworks (such as rspec-core). - module Mocks - # Performs per-test/example setup. This should be called before - # an test or example begins. - def self.setup - @space_stack << (@space = space.new_scope) - end - - # Verifies any message expectations that were set during the - # test or example. This should be called at the end of an example. - def self.verify - space.verify_all - end - - # Cleans up all test double state (including any methods that were - # redefined on partial doubles). This _must_ be called after - # each example, even if an error was raised during the example. - def self.teardown - space.reset_all - @space_stack.pop - @space = @space_stack.last || @root_space - end - - # Adds an allowance (stub) on `subject` - # - # @param subject the subject to which the message will be added - # @param message a symbol, representing the message that will be - # added. - # @param opts a hash of options, :expected_from is used to set the - # original call site - # @yield an optional implementation for the allowance - # - # @example Defines the implementation of `foo` on `bar`, using the passed block - # x = 0 - # RSpec::Mocks.allow_message(bar, :foo) { x += 1 } - def self.allow_message(subject, message, opts={}, &block) - space.proxy_for(subject).add_stub(message, opts, &block) - end - - # Sets a message expectation on `subject`. - # @param subject the subject on which the message will be expected - # @param message a symbol, representing the message that will be - # expected. - # @param opts a hash of options, :expected_from is used to set the - # original call site - # @yield an optional implementation for the expectation - # - # @example Expect the message `foo` to receive `bar`, then call it - # RSpec::Mocks.expect_message(bar, :foo) - # bar.foo - def self.expect_message(subject, message, opts={}, &block) - space.proxy_for(subject).add_message_expectation(message, opts, &block) - end - - # Call the passed block and verify mocks after it has executed. This allows - # mock usage in arbitrary places, such as a `before(:all)` hook. - def self.with_temporary_scope - setup - - begin - yield - verify - ensure - teardown - end - end - - class << self - # @private - attr_reader :space - end - @space_stack = [] - @root_space = @space = RSpec::Mocks::RootSpace.new - - # @private - IGNORED_BACKTRACE_LINE = 'this backtrace line is ignored' - - # To speed up boot time a bit, delay loading optional or rarely - # used features until their first use. - autoload :AnyInstance, "rspec/mocks/any_instance" - autoload :ExpectChain, "rspec/mocks/message_chain" - autoload :StubChain, "rspec/mocks/message_chain" - autoload :MarshalExtension, "rspec/mocks/marshal_extension" - - # Namespace for mock-related matchers. - module Matchers - autoload :HaveReceived, "rspec/mocks/matchers/have_received" - autoload :Receive, "rspec/mocks/matchers/receive" - autoload :ReceiveMessageChain, "rspec/mocks/matchers/receive_message_chain" - autoload :ReceiveMessages, "rspec/mocks/matchers/receive_messages" - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance.rb deleted file mode 100644 index bc912d8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance.rb +++ /dev/null @@ -1,10 +0,0 @@ -%w[ - any_instance/chain - any_instance/stub_chain - any_instance/stub_chain_chain - any_instance/expect_chain_chain - any_instance/expectation_chain - any_instance/message_chains - any_instance/recorder - any_instance/proxy -].each { |f| RSpec::Support.require_rspec_mocks(f) } diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/chain.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/chain.rb deleted file mode 100644 index 4bcc174..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/chain.rb +++ /dev/null @@ -1,109 +0,0 @@ -module RSpec - module Mocks - # @private - module AnyInstance - # @private - class Chain - def initialize(recorder, *args, &block) - @recorder = recorder - @expectation_args = args - @expectation_block = block - @argument_list_matcher = ArgumentListMatcher::MATCH_ALL - end - - # @private - # - # Provides convenience methods for recording customizations on message - # expectations. - module Customizations - # @macro [attach] record - # @method $1(*args, &block) - # Records the `$1` message for playback against an instance that - # invokes a method stubbed or mocked using `any_instance`. - # - # @see RSpec::Mocks::MessageExpectation#$1 - # - def self.record(method_name) - define_method(method_name) do |*args, &block| - record(method_name, *args, &block) - end - end - - record :and_return - record :and_raise - record :and_throw - record :and_yield - record :and_call_original - record :with - record :once - record :twice - record :any_number_of_times - record :exactly - record :times - record :never - record :at_least - record :at_most - end - - include Customizations - - # @private - def playback!(instance) - message_expectation = create_message_expectation_on(instance) - messages.inject(message_expectation) do |object, message| - object.__send__(*message.first, &message.last) - end - end - - # @private - def constrained_to_any_of?(*constraints) - constraints.any? do |constraint| - messages.any? do |message| - message.first.first == constraint - end - end - end - - # @private - def matches_args?(*args) - @argument_list_matcher.args_match?(*args) - end - - # @private - def expectation_fulfilled! - @expectation_fulfilled = true - end - - def never - ErrorGenerator.raise_double_negation_error("expect_any_instance_of(MyClass)") if negated? - super - end - - def with(*args, &block) - @argument_list_matcher = ArgumentListMatcher.new(*args) - super - end - - private - - def negated? - messages.any? { |(message, *_), _| message == :never } - end - - def messages - @messages ||= [] - end - - def last_message - messages.last.first.first unless messages.empty? - end - - def record(rspec_method_name, *args, &block) - verify_invocation_order(rspec_method_name, *args, &block) - messages << [args.unshift(rspec_method_name), block] - self - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/expect_chain_chain.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/expect_chain_chain.rb deleted file mode 100644 index 0d13402..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/expect_chain_chain.rb +++ /dev/null @@ -1,35 +0,0 @@ -module RSpec - module Mocks - module AnyInstance - # @private - class ExpectChainChain < StubChain - def initialize(*args) - super - @expectation_fulfilled = false - end - - def expectation_fulfilled? - @expectation_fulfilled - end - - def playback!(instance) - super.tap { @expectation_fulfilled = true } - end - - private - - def create_message_expectation_on(instance) - ::RSpec::Mocks::ExpectChain.expect_chain_on(instance, *@expectation_args, &@expectation_block) - end - - def invocation_order - @invocation_order ||= { - :and_return => [nil], - :and_raise => [nil], - :and_yield => [nil] - } - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/expectation_chain.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/expectation_chain.rb deleted file mode 100644 index 153f37b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/expectation_chain.rb +++ /dev/null @@ -1,49 +0,0 @@ -module RSpec - module Mocks - module AnyInstance - # @private - class ExpectationChain < Chain - def expectation_fulfilled? - @expectation_fulfilled || constrained_to_any_of?(:never, :any_number_of_times) - end - - def initialize(*args, &block) - @expectation_fulfilled = false - super - end - - private - - def verify_invocation_order(rspec_method_name, *args, &block) - end - end - - # @private - class PositiveExpectationChain < ExpectationChain - - private - - def create_message_expectation_on(instance) - proxy = ::RSpec::Mocks.space.proxy_for(instance) - method_name, opts = @expectation_args - opts = (opts || {}).merge(:expected_form => IGNORED_BACKTRACE_LINE) - - me = proxy.add_message_expectation(method_name, opts, &@expectation_block) - if RSpec::Mocks.configuration.yield_receiver_to_any_instance_implementation_blocks? - me.and_yield_receiver_to_implementation - end - - me - end - - def invocation_order - @invocation_order ||= { - :with => [nil], - :and_return => [:with, nil], - :and_raise => [:with, nil] - } - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/message_chains.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/message_chains.rb deleted file mode 100644 index 0670969..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/message_chains.rb +++ /dev/null @@ -1,84 +0,0 @@ -module RSpec - module Mocks - module AnyInstance - # @private - class MessageChains - def initialize - @chains_by_method_name = Hash.new { |h, k| h[k] = [] } - end - - # @private - def [](method_name) - @chains_by_method_name[method_name] - end - - # @private - def add(method_name, chain) - @chains_by_method_name[method_name] << chain - chain - end - - # @private - def remove_stub_chains_for!(method_name) - @chains_by_method_name[method_name].reject! do |chain| - StubChain === chain - end - end - - # @private - def has_expectation?(method_name) - @chains_by_method_name[method_name].find do |chain| - ExpectationChain === chain - end - end - - # @private - def each_unfulfilled_expectation_matching(method_name, *args) - @chains_by_method_name[method_name].each do |chain| - if !chain.expectation_fulfilled? && chain.matches_args?(*args) - yield chain - end - end - end - - # @private - def all_expectations_fulfilled? - @chains_by_method_name.all? do |method_name, chains| - chains.all? { |chain| chain.expectation_fulfilled? } - end - end - - # @private - def unfulfilled_expectations - @chains_by_method_name.map do |method_name, chains| - method_name.to_s if ExpectationChain === chains.last unless chains.last.expectation_fulfilled? - end.compact - end - - # @private - def received_expected_message!(method_name) - @chains_by_method_name[method_name].each do |chain| - chain.expectation_fulfilled! - end - end - - # @private - def playback!(instance, method_name) - raise_if_second_instance_to_receive_message(instance) - @chains_by_method_name[method_name].each do |chain| - chain.playback!(instance) - end - end - - private - - def raise_if_second_instance_to_receive_message(instance) - @instance_with_expectation ||= instance if ExpectationChain === instance - if ExpectationChain === instance && !@instance_with_expectation.equal?(instance) - raise RSpec::Mocks::MockExpectationError, "Exactly one instance should have received the following message(s) but didn't: #{unfulfilled_expectations.sort.join(', ')}" - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/proxy.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/proxy.rb deleted file mode 100644 index 5f7831c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/proxy.rb +++ /dev/null @@ -1,116 +0,0 @@ -module RSpec - module Mocks - module AnyInstance - # @private - # The `AnyInstance::Recorder` is responsible for redefining the klass's - # instance method in order to add any stubs/expectations the first time - # the method is called. It's not capable of updating a stub on an instance - # that's already been previously stubbed (either directly, or via - # `any_instance`). - # - # This proxy sits in front of the recorder and delegates both to it - # and to the `RSpec::Mocks::Proxy` for each already mocked or stubbed - # instance of the class, in order to propogates changes to the instances. - # - # Note that unlike `RSpec::Mocks::Proxy`, this proxy class is stateless - # and is not persisted in `RSpec::Mocks.space`. - # - # Proxying for the message expectation fluent interface (typically chained - # off of the return value of one of these methods) is provided by the - # `FluentInterfaceProxy` class below. - class Proxy - def initialize(recorder, target_proxies) - @recorder = recorder - @target_proxies = target_proxies - end - - def klass - @recorder.klass - end - - def stub(method_name_or_method_map, &block) - if Hash === method_name_or_method_map - method_name_or_method_map.each do |method_name, return_value| - stub(method_name).and_return(return_value) - end - else - perform_proxying(__method__, [method_name_or_method_map], block) do |proxy| - proxy.add_stub(method_name_or_method_map, &block) - end - end - end - - def unstub(method_name) - perform_proxying(__method__, [method_name], nil) do |proxy| - proxy.remove_stub_if_present(method_name) - end - end - - def stub_chain(*chain, &block) - perform_proxying(__method__, chain, block) do |proxy| - Mocks::StubChain.stub_chain_on(proxy.object, *chain, &block) - end - end - - def expect_chain(*chain, &block) - perform_proxying(__method__, chain, block) do |proxy| - Mocks::ExpectChain.expect_chain_on(proxy.object, *chain, &block) - end - end - - def should_receive(method_name, &block) - perform_proxying(__method__, [method_name], block) do |proxy| - # Yeah, this is a bit odd...but if we used `add_message_expectation` - # then it would act like `expect_every_instance_of(klass).to receive`. - # The any_instance recorder takes care of validating that an instance - # received the message. - proxy.add_stub(method_name, &block) - end - end - - def should_not_receive(method_name, &block) - perform_proxying(__method__, [method_name], block) do |proxy| - proxy.add_message_expectation(method_name, &block).never - end - end - - private - - def perform_proxying(method_name, args, block, &target_proxy_block) - recorder_value = @recorder.__send__(method_name, *args, &block) - proxy_values = @target_proxies.map(&target_proxy_block) - FluentInterfaceProxy.new([recorder_value] + proxy_values) - end - end - - # @private - # Delegates messages to each of the given targets in order to - # provide the fluent interface that is available off of message - # expectations when dealing with `any_instance`. - # - # `targets` will typically contain 1 of the `AnyInstance::Recorder` - # return values and N `MessageExpectation` instances (one per instance - # of the `any_instance` klass). - class FluentInterfaceProxy - def initialize(targets) - @targets = targets - end - - if RUBY_VERSION.to_f > 1.8 - def respond_to_missing?(method_name, include_private = false) - super || @targets.first.respond_to?(method_name, include_private) - end - else - def respond_to?(method_name, include_private = false) - super || @targets.first.respond_to?(method_name, include_private) - end - end - - def method_missing(*args, &block) - return_values = @targets.map { |t| t.__send__(*args, &block) } - FluentInterfaceProxy.new(return_values) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/recorder.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/recorder.rb deleted file mode 100644 index 17c91ef..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/recorder.rb +++ /dev/null @@ -1,265 +0,0 @@ -module RSpec - module Mocks - module AnyInstance - # Given a class `TheClass`, `TheClass.any_instance` returns a `Recorder`, - # which records stubs and message expectations for later playback on - # instances of `TheClass`. - # - # Further constraints are stored in instances of [Chain](Chain). - # - # @see AnyInstance - # @see Chain - class Recorder - # @private - attr_reader :message_chains, :stubs, :klass - - def initialize(klass) - @message_chains = MessageChains.new - @stubs = Hash.new { |hash,key| hash[key] = [] } - @observed_methods = [] - @played_methods = {} - @klass = klass - @expectation_set = false - end - - # Initializes the recording a stub to be played back against any - # instance of this object that invokes the submitted method. - # - # @see Methods#stub - def stub(method_name, &block) - observe!(method_name) - message_chains.add(method_name, StubChain.new(self, method_name, &block)) - end - - # Initializes the recording a stub chain to be played back against any - # instance of this object that invokes the method matching the first - # argument. - # - # @see Methods#stub_chain - def stub_chain(*method_names_and_optional_return_values, &block) - normalize_chain(*method_names_and_optional_return_values) do |method_name, args| - observe!(method_name) - message_chains.add(method_name, StubChainChain.new(self, *args, &block)) - end - end - - # @private - def expect_chain(*method_names_and_optional_return_values, &block) - @expectation_set = true - normalize_chain(*method_names_and_optional_return_values) do |method_name, args| - observe!(method_name) - message_chains.add(method_name, ExpectChainChain.new(self, *args, &block)) - end - end - - # Initializes the recording a message expectation to be played back - # against any instance of this object that invokes the submitted - # method. - # - # @see Methods#should_receive - def should_receive(method_name, &block) - @expectation_set = true - observe!(method_name) - message_chains.add(method_name, PositiveExpectationChain.new(self, method_name, &block)) - end - - # The opposite of `should_receive` - # - # @see Methods#should_not_receive - def should_not_receive(method_name, &block) - should_receive(method_name, &block).never - end - - # Removes any previously recorded stubs, stub_chains or message - # expectations that use `method_name`. - # - # @see Methods#unstub - def unstub(method_name) - unless @observed_methods.include?(method_name.to_sym) - raise RSpec::Mocks::MockExpectationError, "The method `#{method_name}` was not stubbed or was already unstubbed" - end - message_chains.remove_stub_chains_for!(method_name) - stubs[method_name].clear - stop_observing!(method_name) unless message_chains.has_expectation?(method_name) - end - - # @api private - # - # Used internally to verify that message expectations have been - # fulfilled. - def verify - if @expectation_set && !message_chains.all_expectations_fulfilled? - raise RSpec::Mocks::MockExpectationError, "Exactly one instance should have received the following message(s) but didn't: #{message_chains.unfulfilled_expectations.sort.join(', ')}" - end - end - - # @private - def stop_all_observation! - @observed_methods.each {|method_name| restore_method!(method_name)} - end - - # @private - def playback!(instance, method_name) - RSpec::Mocks.space.ensure_registered(instance) - message_chains.playback!(instance, method_name) - @played_methods[method_name] = instance - received_expected_message!(method_name) if message_chains.has_expectation?(method_name) - end - - # @private - def instance_that_received(method_name) - @played_methods[method_name] - end - - # @private - def build_alias_method_name(method_name) - "__#{method_name}_without_any_instance__" - end - - # @private - def already_observing?(method_name) - @observed_methods.include?(method_name) || super_class_observing?(method_name) - end - - # @private - def notify_received_message(object, message, args, blk) - has_expectation = false - - message_chains.each_unfulfilled_expectation_matching(message, *args) do |expectation| - has_expectation = true - expectation.expectation_fulfilled! - end - - if has_expectation - restore_method!(message) - mark_invoked!(message) - end - end - - protected - - def stop_observing!(method_name) - restore_method!(method_name) - @observed_methods.delete(method_name) - super_class_observers_for(method_name).each do |ancestor| - ::RSpec::Mocks.space. - any_instance_recorder_for(ancestor).stop_observing!(method_name) - end - end - - private - - def ancestor_is_an_observer?(method_name) - lambda do |ancestor| - unless ancestor == @klass - ::RSpec::Mocks.space. - any_instance_recorder_for(ancestor).already_observing?(method_name) - end - end - end - - def super_class_observers_for(method_name) - @klass.ancestors.select(&ancestor_is_an_observer?(method_name)) - end - - def super_class_observing?(method_name) - @klass.ancestors.any?(&ancestor_is_an_observer?(method_name)) - end - - def normalize_chain(*args) - args.shift.to_s.split('.').map {|s| s.to_sym}.reverse.each {|a| args.unshift a} - yield args.first, args - end - - def received_expected_message!(method_name) - message_chains.received_expected_message!(method_name) - restore_method!(method_name) - mark_invoked!(method_name) - end - - def restore_method!(method_name) - if public_protected_or_private_method_defined?(build_alias_method_name(method_name)) - restore_original_method!(method_name) - else - remove_dummy_method!(method_name) - end - end - - def restore_original_method!(method_name) - if @klass.instance_method(method_name).owner == @klass - alias_method_name = build_alias_method_name(method_name) - @klass.class_exec do - remove_method method_name - alias_method method_name, alias_method_name - remove_method alias_method_name - end - end - end - - def remove_dummy_method!(method_name) - @klass.class_exec do - remove_method method_name - end - end - - def backup_method!(method_name) - alias_method_name = build_alias_method_name(method_name) - @klass.class_exec do - alias_method alias_method_name, method_name - end if public_protected_or_private_method_defined?(method_name) - end - - def public_protected_or_private_method_defined?(method_name) - MethodReference.method_defined_at_any_visibility?(@klass, method_name) - end - - def observe!(method_name) - allow_no_prepended_module_definition_of(method_name) - - if RSpec::Mocks.configuration.verify_partial_doubles? - unless public_protected_or_private_method_defined?(method_name) - raise MockExpectationError, - "#{@klass} does not implement ##{method_name}" - end - end - - stop_observing!(method_name) if already_observing?(method_name) - @observed_methods << method_name - backup_method!(method_name) - recorder = self - @klass.__send__(:define_method, method_name) do |*args, &blk| - recorder.playback!(self, method_name) - self.__send__(method_name, *args, &blk) - end - end - - def mark_invoked!(method_name) - backup_method!(method_name) - recorder = self - @klass.__send__(:define_method, method_name) do |*args, &blk| - invoked_instance = recorder.instance_that_received(method_name) - inspect = "#<#{self.class}:#{object_id} #{instance_variables.map { |name| "#{name}=#{instance_variable_get name}" }.join(', ')}>" - raise RSpec::Mocks::MockExpectationError, "The message '#{method_name}' was received by #{inspect} but has already been received by #{invoked_instance}" - end - end - - if Support::RubyFeatures.module_prepends_supported? - def allow_no_prepended_module_definition_of(method_name) - prepended_modules = @klass.ancestors.take_while { |mod| !(Class === mod) } - problem_mod = prepended_modules.find { |mod| mod.method_defined?(method_name) } - return unless problem_mod - - raise RSpec::Mocks::MockExpectationError, - "Using `any_instance` to stub a method (#{method_name}) that has been " + - "defined on a prepended module (#{problem_mod}) is not supported." - end - else - def allow_no_prepended_module_definition_of(method_name) - # nothing to do; prepends aren't supported on this version of ruby - end - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/stub_chain.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/stub_chain.rb deleted file mode 100644 index 16071ec..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/stub_chain.rb +++ /dev/null @@ -1,47 +0,0 @@ -module RSpec - module Mocks - module AnyInstance - # @private - class StubChain < Chain - - # @private - def expectation_fulfilled? - true - end - - private - - def create_message_expectation_on(instance) - proxy = ::RSpec::Mocks.space.proxy_for(instance) - method_name, opts = @expectation_args - opts = (opts || {}).merge(:expected_form => IGNORED_BACKTRACE_LINE) - - stub = proxy.add_stub(method_name, opts, &@expectation_block) - @recorder.stubs[stub.message] << stub - - if RSpec::Mocks.configuration.yield_receiver_to_any_instance_implementation_blocks? - stub.and_yield_receiver_to_implementation - end - - stub - end - - def invocation_order - @invocation_order ||= { - :with => [nil], - :and_return => [:with, nil], - :and_raise => [:with, nil], - :and_yield => [:with, nil], - :and_call_original => [:with, nil] - } - end - - def verify_invocation_order(rspec_method_name, *args, &block) - unless invocation_order[rspec_method_name].include?(last_message) - raise(NoMethodError, "Undefined method #{rspec_method_name}") - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/stub_chain_chain.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/stub_chain_chain.rb deleted file mode 100644 index c056967..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/any_instance/stub_chain_chain.rb +++ /dev/null @@ -1,27 +0,0 @@ -module RSpec - module Mocks - module AnyInstance - # @private - class StubChainChain < StubChain - def initialize(*args) - super - @expectation_fulfilled = false - end - - private - - def create_message_expectation_on(instance) - ::RSpec::Mocks::StubChain.stub_chain_on(instance, *@expectation_args, &@expectation_block) - end - - def invocation_order - @invocation_order ||= { - :and_return => [nil], - :and_raise => [nil], - :and_yield => [nil] - } - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/argument_list_matcher.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/argument_list_matcher.rb deleted file mode 100644 index 927e36f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/argument_list_matcher.rb +++ /dev/null @@ -1,72 +0,0 @@ -# We intentionally do not use the `RSpec::Support.require...` methods -# here so that this file can be loaded individually, as documented -# below. -require 'rspec/mocks/argument_matchers' -require 'rspec/support/fuzzy_matcher' - -module RSpec - module Mocks - # Wrapper for matching arguments against a list of expected values. Used by - # the `with` method on a `MessageExpectation`: - # - # expect(object).to receive(:message).with(:a, 'b', 3) - # object.message(:a, 'b', 3) - # - # Values passed to `with` can be literal values or argument matchers that - # match against the real objects .e.g. - # - # expect(object).to receive(:message).with(hash_including(:a => 'b')) - # - # Can also be used directly to match the contents of any `Array`. This - # enables 3rd party mocking libs to take advantage of rspec's argument - # matching without using the rest of rspec-mocks. - # - # require 'rspec/mocks/argument_list_matcher' - # include RSpec::Mocks::ArgumentMatchers - # - # arg_list_matcher = RSpec::Mocks::ArgumentListMatcher.new(123, hash_including(:a => 'b')) - # arg_list_matcher.args_match?(123, :a => 'b') - # - # This class is immutable. - # - # @see ArgumentMatchers - class ArgumentListMatcher - # @private - attr_reader :expected_args - - # @api public - # @param [Array] expected_args a list of expected literals and/or argument matchers - # - # Initializes an `ArgumentListMatcher` with a collection of literal - # values and/or argument matchers. - # - # @see ArgumentMatchers - # @see #args_match? - def initialize(*expected_args) - @expected_args = expected_args - - @matchers = case expected_args.first - when ArgumentMatchers::AnyArgsMatcher then Array - when ArgumentMatchers::NoArgsMatcher then [] - else expected_args - end - end - - # @api public - # @param [Array] args - # - # Matches each element in the `expected_args` against the element in the same - # position of the arguments passed to `new`. - # - # @see #initialize - def args_match?(*args) - Support::FuzzyMatcher.values_match?(@matchers, args) - end - - # Value that will match all argument lists. - # - # @private - MATCH_ALL = new(ArgumentMatchers::AnyArgsMatcher.new) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/argument_matchers.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/argument_matchers.rb deleted file mode 100644 index dbaf60d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/argument_matchers.rb +++ /dev/null @@ -1,249 +0,0 @@ -module RSpec - module Mocks - - # ArgumentMatchers are placeholders that you can include in message - # expectations to match arguments against a broader check than simple - # equality. - # - # With the exception of `any_args` and `no_args`, they all match against - # the arg in same position in the argument list. - # - # @see ArgumentListMatcher - module ArgumentMatchers - # Matches any args at all. Supports a more explicit variation of - # `expect(object).to receive(:message)` - # - # @example - # - # expect(object).to receive(:message).with(any_args) - def any_args - AnyArgsMatcher.new - end - - # Matches any argument at all. - # - # @example - # - # expect(object).to receive(:message).with(anything) - def anything - AnyArgMatcher.new - end - - # Matches no arguments. - # - # @example - # - # expect(object).to receive(:message).with(no_args) - def no_args - NoArgsMatcher.new - end - - # Matches if the actual argument responds to the specified messages. - # - # @example - # - # expect(object).to receive(:message).with(duck_type(:hello)) - # expect(object).to receive(:message).with(duck_type(:hello, :goodbye)) - def duck_type(*args) - DuckTypeMatcher.new(*args) - end - - # Matches a boolean value. - # - # @example - # - # expect(object).to receive(:message).with(boolean()) - def boolean - BooleanMatcher.new - end - - # Matches a hash that includes the specified key(s) or key/value pairs. - # Ignores any additional keys. - # - # @example - # - # expect(object).to receive(:message).with(hash_including(:key => val)) - # expect(object).to receive(:message).with(hash_including(:key)) - # expect(object).to receive(:message).with(hash_including(:key, :key2 => val2)) - def hash_including(*args) - HashIncludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args)) - end - - # Matches an array that includes the specified items at least once. - # Ignores duplicates and additional values - # - # @example - # - # expect(object).to receive(:message).with(array_including(1,2,3)) - # expect(object).to receive(:message).with(array_including([1,2,3])) - def array_including(*args) - actually_an_array = Array === args.first && args.count == 1 ? args.first : args - ArrayIncludingMatcher.new(actually_an_array) - end - - # Matches a hash that doesn't include the specified key(s) or key/value. - # - # @example - # - # expect(object).to receive(:message).with(hash_excluding(:key => val)) - # expect(object).to receive(:message).with(hash_excluding(:key)) - # expect(object).to receive(:message).with(hash_excluding(:key, :key2 => :val2)) - def hash_excluding(*args) - HashExcludingMatcher.new(ArgumentMatchers.anythingize_lonely_keys(*args)) - end - - alias_method :hash_not_including, :hash_excluding - - # Matches if `arg.instance_of?(klass)` - # - # @example - # - # expect(object).to receive(:message).with(instance_of(Thing)) - def instance_of(klass) - InstanceOf.new(klass) - end - - alias_method :an_instance_of, :instance_of - - # Matches if `arg.kind_of?(klass)` - # @example - # - # expect(object).to receive(:message).with(kind_of(Thing)) - def kind_of(klass) - klass - end - - alias_method :a_kind_of, :kind_of - - # @private - def self.anythingize_lonely_keys(*args) - hash = args.last.class == Hash ? args.delete_at(-1) : {} - args.each { | arg | hash[arg] = AnyArgMatcher.new } - hash - end - - # @private - class AnyArgsMatcher - def description - "any args" - end - end - - # @private - class AnyArgMatcher - def ===(other) - true - end - - def description - "anything" - end - end - - # @private - class NoArgsMatcher - def description - "no args" - end - end - - # @private - class BooleanMatcher - def ===(value) - true == value || false == value - end - - def description - "boolean" - end - end - - # @private - class BaseHashMatcher - def initialize(expected) - @expected = expected - end - - def ===(predicate, actual) - @expected.__send__(predicate) do |k, v| - actual.has_key?(k) && Support::FuzzyMatcher.values_match?(v, actual[k]) - end - rescue NoMethodError - false - end - - def description(name) - "#{name}(#{@expected.inspect.sub(/^\{/,"").sub(/\}$/,"")})" - end - end - - # @private - class HashIncludingMatcher < BaseHashMatcher - def ===(actual) - super(:all?, actual) - end - - def description - super("hash_including") - end - end - - # @private - class HashExcludingMatcher < BaseHashMatcher - def ===(actual) - super(:none?, actual) - end - - def description - super("hash_not_including") - end - end - - # @private - class ArrayIncludingMatcher - def initialize(expected) - @expected = expected - end - - def ===(actual) - Set.new(actual).superset?(Set.new(@expected)) - end - - def description - "array_including(#{@expected.join(", ")})" - end - end - - # @private - class DuckTypeMatcher - def initialize(*methods_to_respond_to) - @methods_to_respond_to = methods_to_respond_to - end - - def ===(value) - @methods_to_respond_to.all? {|message| value.respond_to?(message)} - end - - def description - "duck_type(#{@methods_to_respond_to.map(&:inspect).join(', ')})" - end - end - - # @private - class InstanceOf - def initialize(klass) - @klass = klass - end - - def ===(actual) - actual.instance_of?(@klass) - end - - def description - "an_instance_of(#{@klass.name})" - end - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/configuration.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/configuration.rb deleted file mode 100644 index 35595d5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/configuration.rb +++ /dev/null @@ -1,164 +0,0 @@ -module RSpec - module Mocks - # Provides configuration options for rspec-mocks. - class Configuration - - def initialize - @yield_receiver_to_any_instance_implementation_blocks = true - @verify_doubled_constant_names = false - @transfer_nested_constants = false - @verify_partial_doubles = false - end - - def yield_receiver_to_any_instance_implementation_blocks? - @yield_receiver_to_any_instance_implementation_blocks - end - - # Sets whether or not RSpec will yield the receiving instance of a - # message to blocks that are used for any_instance stub implementations. - # When set, the first yielded argument will be the receiving instance. - # Defaults to `true`. - # - # @example - # - # RSpec.configure do |rspec| - # rspec.mock_with :rspec do |mocks| - # mocks.yield_receiver_to_any_instance_implementation_blocks = false - # end - # end - def yield_receiver_to_any_instance_implementation_blocks=(arg) - @yield_receiver_to_any_instance_implementation_blocks = arg - end - - # Adds `stub` and `should_receive` to the given - # modules or classes. This is usually only necessary - # if you application uses some proxy classes that - # "strip themselves down" to a bare minimum set of - # methods and remove `stub` and `should_receive` in - # the process. - # - # @example - # - # RSpec.configure do |rspec| - # rspec.mock_with :rspec do |mocks| - # mocks.add_stub_and_should_receive_to Delegator - # end - # end - # - def add_stub_and_should_receive_to(*modules) - modules.each do |mod| - Syntax.enable_should(mod) - end - end - - # Provides the ability to set either `expect`, - # `should` or both syntaxes. RSpec uses `expect` - # syntax by default. This is needed if you want to - # explicitly enable `should` syntax and/or explicitly - # disable `expect` syntax. - # - # @example - # - # RSpec.configure do |rspec| - # rspec.mock_with :rspec do |mocks| - # mocks.syntax = [:expect, :should] - # end - # end - # - def syntax=(*values) - syntaxes = values.flatten - if syntaxes.include?(:expect) - Syntax.enable_expect - else - Syntax.disable_expect - end - - if syntaxes.include?(:should) - Syntax.enable_should - else - Syntax.disable_should - end - end - - # Returns an array with a list of syntaxes - # that are enabled. - # - # @example - # - # unless RSpec::Mocks.configuration.syntax.include?(:expect) - # raise "this RSpec extension gem requires the rspec-mocks `:expect` syntax" - # end - # - def syntax - syntaxes = [] - syntaxes << :should if Syntax.should_enabled? - syntaxes << :expect if Syntax.expect_enabled? - syntaxes - end - - def verify_doubled_constant_names? - !!@verify_doubled_constant_names - end - - # When this is set to true, an error will be raised when - # `instance_double` or `class_double` is given the name of an undefined - # constant. You probably only want to set this when running your entire - # test suite, with all production code loaded. Setting this for an - # isolated unit test will prevent you from being able to isolate it! - def verify_doubled_constant_names=(val) - @verify_doubled_constant_names = val - end - - def transfer_nested_constants? - !!@transfer_nested_constants - end - - # Sets the default for the `transfer_nested_constants` option when - # stubbing constants. - def transfer_nested_constants=(val) - @transfer_nested_constants = val - end - - # When set to true, partial mocks will be verified the same as object - # doubles. Any stubs will have their arguments checked against the original - # method, and methods that do not exist cannot be stubbed. - def verify_partial_doubles=(val) - @verify_partial_doubles = !!val - end - - def verify_partial_doubles? - @verify_partial_doubles - end - - # Monkey-patch `Marshal.dump` to enable dumping of mocked or stubbed - # objects. By default this will not work since RSpec mocks works by - # adding singleton methods that cannot be serialized. This patch removes - # these singleton methods before serialization. Setting to falsey removes - # the patch. - # - # This method is idempotent. - def patch_marshal_to_support_partial_doubles=(val) - if val - RSpec::Mocks::MarshalExtension.patch! - else - RSpec::Mocks::MarshalExtension.unpatch! - end - end - - # @api private - # Resets the configured syntax to the default. - def reset_syntaxes_to_default - self.syntax = [:should, :expect] - RSpec::Mocks::Syntax.warn_about_should! - end - end - - # Mocks specific configuration, as distinct from `RSpec.configuration` - # which is core RSpec configuration. - def self.configuration - @configuration ||= Configuration.new - end - - configuration.reset_syntaxes_to_default - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/error_generator.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/error_generator.rb deleted file mode 100644 index 0092c2e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/error_generator.rb +++ /dev/null @@ -1,247 +0,0 @@ -module RSpec - module Mocks - # Raised when a message expectation is not satisfied. - MockExpectationError = Class.new(Exception) - - # Raised when a test double is used after it has been torn - # down (typically at the end of an rspec-core example). - ExpiredTestDoubleError = Class.new(MockExpectationError) - - # Raised when doubles or partial doubles are used outside of the per-test lifecycle. - OutsideOfExampleError = Class.new(StandardError) - - # @private - UnsupportedMatcherError = Class.new(StandardError) - # @private - NegationUnsupportedError = Class.new(StandardError) - # @private - VerifyingDoubleNotDefinedError = Class.new(StandardError) - - # @private - class ErrorGenerator - attr_writer :opts - - def initialize(target, name) - @target = target - @name = name - end - - # @private - def opts - @opts ||= {} - end - - # @private - def raise_unexpected_message_error(message, *args) - __raise "#{intro} received unexpected message :#{message}#{arg_message(*args)}" - end - - # @private - def raise_unexpected_message_args_error(expectation, *args) - expected_args = format_args(*expectation.expected_args) - actual_args = format_received_args(*args) - __raise "#{intro} received #{expectation.message.inspect} with unexpected arguments\n expected: #{expected_args}\n got: #{actual_args}" - end - - # @private - def raise_missing_default_stub_error(expectation, *args) - expected_args = format_args(*expectation.expected_args) - actual_args = format_received_args(*args) - __raise "#{intro} received #{expectation.message.inspect} with unexpected arguments\n expected: #{expected_args}\n got: #{actual_args}\n Please stub a default value first if message might be received with other args as well. \n" - end - - # @private - def raise_similar_message_args_error(expectation, *args_for_multiple_calls) - expected_args = format_args(*expectation.expected_args) - actual_args = args_for_multiple_calls.collect {|a| format_received_args(*a)}.join(", ") - __raise "#{intro} received #{expectation.message.inspect} with unexpected arguments\n expected: #{expected_args}\n got: #{actual_args}" - end - - # @private - def raise_expectation_error(message, expected_received_count, argument_list_matcher, actual_received_count, expectation_count_type, *args) - expected_part = expected_part_of_expectation_error(expected_received_count, expectation_count_type, argument_list_matcher) - received_part = received_part_of_expectation_error(actual_received_count, *args) - __raise "(#{intro}).#{message}#{format_args(*args)}\n #{expected_part}\n #{received_part}" - end - - # @private - def raise_unimplemented_error(doubled_module, method_name) - __raise "%s does not implement: %s" % [ - doubled_module.description, - method_name - ] - end - - # @private - def raise_non_public_error(method_name, visibility) - raise NoMethodError, "%s method `%s' called on %s" % [ - visibility, method_name, intro - ] - end - - # @private - def raise_invalid_arguments_error(verifier) - __raise verifier.error_message - end - - # @private - def raise_expired_test_double_error - raise ExpiredTestDoubleError, - "#{intro} was originally created in one example but has leaked into " + - "another example and can no longer be used. rspec-mocks' doubles are " + - "designed to only last for one example, and you need to create a new " + - "one in each example you wish to use it for." - end - - # @private - def received_part_of_expectation_error(actual_received_count, *args) - "received: #{count_message(actual_received_count)}" + - actual_method_call_args_description(actual_received_count, args) - end - - # @private - def expected_part_of_expectation_error(expected_received_count, expectation_count_type, argument_list_matcher) - "expected: #{count_message(expected_received_count, expectation_count_type)}" + - expected_method_call_args_description(argument_list_matcher.expected_args) - end - - # @private - def actual_method_call_args_description(count, args) - method_call_args_description(args) || - if count > 0 && args.length > 0 - " with arguments: #{args.inspect.gsub(/\A\[(.+)\]\z/, '(\1)')}" - else - "" - end - end - - # @private - def expected_method_call_args_description(args) - method_call_args_description(args) || - if args.length > 0 - " with arguments: #{format_args(*args)}" - else - "" - end - end - - # @private - def method_call_args_description(args) - case args.first - when ArgumentMatchers::AnyArgsMatcher - return " with any arguments" - when ArgumentMatchers::NoArgsMatcher - return " with no arguments" - end - end - - # @private - def describe_expectation(message, expected_received_count, actual_received_count, *args) - "have received #{message}#{format_args(*args)} #{count_message(expected_received_count)}" - end - - # @private - def raise_out_of_order_error(message) - __raise "#{intro} received :#{message} out of order" - end - - # @private - def raise_block_failed_error(message, detail) - __raise "#{intro} received :#{message} but passed block failed with: #{detail}" - end - - # @private - def raise_missing_block_error(args_to_yield) - __raise "#{intro} asked to yield |#{arg_list(*args_to_yield)}| but no block was passed" - end - - # @private - def raise_wrong_arity_error(args_to_yield, signature) - __raise "#{intro} yielded |#{arg_list(*args_to_yield)}| to block with #{signature.description}" - end - - # @private - def raise_only_valid_on_a_partial_double(method) - __raise "#{intro} is a pure test double. `#{method}` is only " + - "available on a partial double." - end - - # @private - def raise_expectation_on_unstubbed_method(method) - __raise "#{intro} expected to have received #{method}, but that " + - "method has not been stubbed." - end - - # @private - def raise_expectation_on_mocked_method(method) - __raise "#{intro} expected to have received #{method}, but that " + - "method has been mocked instead of stubbed." - end - - def self.raise_double_negation_error(wrapped_expression) - raise "Isn't life confusing enough? You've already set a " + - "negative message expectation and now you are trying to " + - "negate it again with `never`. What does an expression like " + - "`#{wrapped_expression}.not_to receive(:msg).never` even mean?" - end - - private - - def intro - if @name - "Double #{@name.inspect}" - elsif TestDouble === @target - "Double" - elsif Class === @target - "<#{@target.inspect} (class)>" - elsif @target - @target - else - "nil" - end - end - - def __raise(message) - message = opts[:message] unless opts[:message].nil? - Kernel::raise(RSpec::Mocks::MockExpectationError, message) - end - - def arg_message(*args) - " with " + format_args(*args) - end - - def format_args(*args) - args.empty? ? "(no args)" : "(" + arg_list(*args) + ")" - end - - def arg_list(*args) - args.collect {|arg| arg_has_valid_description(arg) ? arg.description : arg.inspect }.join(", ") - end - - def arg_has_valid_description(arg) - return false unless arg.respond_to?(:description) - - !arg.description.nil? && !arg.description.empty? - end - - def format_received_args(*args) - args.empty? ? "(no args)" : "(" + received_arg_list(*args) + ")" - end - - def received_arg_list(*args) - args.collect(&:inspect).join(", ") - end - - def count_message(count, expectation_count_type=nil) - return "at least #{times(count.abs)}" if count < 0 || expectation_count_type == :at_least - return "at most #{times(count)}" if expectation_count_type == :at_most - return times(count) - end - - def times(count) - "#{count} time#{count == 1 ? '' : 's'}" - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/example_methods.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/example_methods.rb deleted file mode 100644 index 1bf1492..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/example_methods.rb +++ /dev/null @@ -1,311 +0,0 @@ -RSpec::Support.require_rspec_mocks 'object_reference' - -module RSpec - module Mocks - # Contains methods intended to be used from within code examples. - # Mix this in to your test context (such as a test framework base class) - # to use rspec-mocks with your test framework. If you're using rspec-core, - # it'll take care of doing this for you. - module ExampleMethods - include RSpec::Mocks::ArgumentMatchers - - # @overload double() - # @overload double(name) - # @param name [String/Symbol] used to clarify intent - # @overload double(stubs) - # @param stubs (Hash) hash of message/return-value pairs - # @overload double(name, stubs) - # @param name [String/Symbol] used to clarify intent - # @param stubs (Hash) hash of message/return-value pairs - # @return (Double) - # - # Constructs an instance of [RSpec::Mocks::Double](RSpec::Mocks::Double) configured - # with an optional name, used for reporting in failure messages, and an optional - # hash of message/return-value pairs. - # - # @example - # - # book = double("book", :title => "The RSpec Book") - # book.title #=> "The RSpec Book" - # - # card = double("card", :suit => "Spades", :rank => "A") - # card.suit #=> "Spades" - # card.rank #=> "A" - # - def double(*args) - ExampleMethods.declare_double(Double, *args) - end - - # @overload instance_double(doubled_class) - # @param doubled_class [String, Class] - # @overload instance_double(doubled_class, stubs) - # @param doubled_class [String, Class] - # @param stubs [Hash] hash of message/return-value pairs - # @return InstanceVerifyingDouble - # - # Constructs a test double against a specific class. If the given class - # name has been loaded, only instance methods defined on the class are - # allowed to be stubbed. In all other ways it behaves like a - # [double](double). - def instance_double(doubled_class, *args) - ref = ObjectReference.for(doubled_class) - ExampleMethods.declare_verifying_double(InstanceVerifyingDouble, ref, *args) - end - - # @overload class_double(doubled_class) - # @param doubled_class [String, Module] - # @overload class_double(doubled_class, stubs) - # @param doubled_class [String, Module] - # @param stubs [Hash] hash of message/return-value pairs - # @return ClassVerifyingDouble - # - # Constructs a test double against a specific class. If the given class - # name has been loaded, only class methods defined on the class are - # allowed to be stubbed. In all other ways it behaves like a - # [double](double). - def class_double(doubled_class, *args) - ref = ObjectReference.for(doubled_class) - ExampleMethods.declare_verifying_double(ClassVerifyingDouble, ref, *args) - end - - # @overload object_double(object_or_name) - # @param object_or_name [String, Object] - # @overload object_double(object_or_name, stubs) - # @param object_or_name [String, Object] - # @param stubs [Hash] hash of message/return-value pairs - # @return ObjectVerifyingDouble - # - # Constructs a test double against a specific object. Only the methods - # the object responds to are allowed to be stubbed. If a String argument - # is provided, it is assumed to reference a constant object which is used - # for verification. In all other ways it behaves like a [double](double). - def object_double(object_or_name, *args) - ref = ObjectReference.for(object_or_name, :allow_direct_object_refs) - ExampleMethods.declare_verifying_double(ObjectVerifyingDouble, ref, *args) - end - - # Disables warning messages about expectations being set on nil. - # - # By default warning messages are issued when expectations are set on - # nil. This is to prevent false-positives and to catch potential bugs - # early on. - def allow_message_expectations_on_nil - RSpec::Mocks.space.proxy_for(nil).warn_about_expectations = false - end - - # Stubs the named constant with the given value. - # Like method stubs, the constant will be restored - # to its original value (or lack of one, if it was - # undefined) when the example completes. - # - # @param constant_name [String] The fully qualified name of the constant. The current - # constant scoping at the point of call is not considered. - # @param value [Object] The value to make the constant refer to. When the - # example completes, the constant will be restored to its prior state. - # @param options [Hash] Stubbing options. - # @option options :transfer_nested_constants [Boolean, Array] Determines - # what nested constants, if any, will be transferred from the original value - # of the constant to the new value of the constant. This only works if both - # the original and new values are modules (or classes). - # @return [Object] the stubbed value of the constant - # - # @example - # - # stub_const("MyClass", Class.new) # => Replaces (or defines) MyClass with a new class object. - # stub_const("SomeModel::PER_PAGE", 5) # => Sets SomeModel::PER_PAGE to 5. - # - # class CardDeck - # SUITS = [:Spades, :Diamonds, :Clubs, :Hearts] - # NUM_CARDS = 52 - # end - # - # stub_const("CardDeck", Class.new) - # CardDeck::SUITS # => uninitialized constant error - # CardDeck::NUM_CARDS # => uninitialized constant error - # - # stub_const("CardDeck", Class.new, :transfer_nested_constants => true) - # CardDeck::SUITS # => our suits array - # CardDeck::NUM_CARDS # => 52 - # - # stub_const("CardDeck", Class.new, :transfer_nested_constants => [:SUITS]) - # CardDeck::SUITS # => our suits array - # CardDeck::NUM_CARDS # => uninitialized constant error - def stub_const(constant_name, value, options = {}) - ConstantMutator.stub(constant_name, value, options) - end - - # Hides the named constant with the given value. The constant will be - # undefined for the duration of the test. - # - # Like method stubs, the constant will be restored to its original value - # when the example completes. - # - # @param constant_name [String] The fully qualified name of the constant. - # The current constant scoping at the point of call is not considered. - # - # @example - # - # hide_const("MyClass") # => MyClass is now an undefined constant - def hide_const(constant_name) - ConstantMutator.hide(constant_name) - end - - # Verifies that the given object received the expected message during the - # course of the test. The method must have previously been stubbed in - # order for messages to be verified. - # - # Stubbing and verifying messages received in this way implements the - # Test Spy pattern. - # - # @param method_name [Symbol] name of the method expected to have been - # called. - # - # @example - # - # invitation = double('invitation', accept: true) - # user.accept_invitation(invitation) - # expect(invitation).to have_received(:accept) - # - # # You can also use most message expectations: - # expect(invitation).to have_received(:accept).with(mailer).once - def have_received(method_name, &block) - Matchers::HaveReceived.new(method_name, &block) - end - - # @method expect - # Used to wrap an object in preparation for setting a mock expectation - # on it. - # - # @example - # - # expect(obj).to receive(:foo).with(5).and_return(:return_value) - # - # @note This method is usually provided by rspec-expectations. However, - # if you use rspec-mocks without rspec-expectations, there's a definition - # of it that is made available here. If you disable the `:expect` syntax - # this method will be undefined. - - # @method allow - # Used to wrap an object in preparation for stubbing a method - # on it. - # - # @example - # - # allow(dbl).to receive(:foo).with(5).and_return(:return_value) - # - # @note If you disable the `:expect` syntax this method will be undefined. - - # @method expect_any_instance_of - # Used to wrap a class in preparation for setting a mock expectation - # on instances of it. - # - # @example - # - # expect_any_instance_of(MyClass).to receive(:foo) - # - # @note If you disable the `:expect` syntax this method will be undefined. - - # @method allow_any_instance_of - # Used to wrap a class in preparation for stubbing a method - # on instances of it. - # - # @example - # - # allow_any_instance_of(MyClass).to receive(:foo) - # - # @note This is only available when you have enabled the `expect` syntax. - - # @method receive - # Used to specify a message that you expect or allow an object - # to receive. The object returned by `receive` supports the same - # fluent interface that `should_receive` and `stub` have always - # supported, allowing you to constrain the arguments or number of - # times, and configure how the object should respond to the message. - # - # @example - # - # expect(obj).to receive(:hello).with("world").exactly(3).times - # - # @note If you disable the `:expect` syntax this method will be undefined. - - # @method receive_messages - # Shorthand syntax used to setup message(s), and their return value(s), - # that you expect or allow an object to receive. The method takes a hash - # of messages and their respective return values. Unlike with `receive`, - # you cannot apply further customizations using a block or the fluent - # interface. - # - # @example - # - # allow(obj).to receive_messages(:speak => "Hello World") - # allow(obj).to receive_messages(:speak => "Hello", :meow => "Meow") - # - # @note If you disable the `:expect` syntax this method will be undefined. - - # @method receive_message_chain - # @overload receive_message_chain(method1, method2) - # @overload receive_message_chain("method1.method2") - # @overload receive_message_chain(method1, method_to_value_hash) - # - # stubs/mocks a chain of messages on an object or test double. - # - # ## Warning: - # - # Chains can be arbitrarily long, which makes it quite painless to - # violate the Law of Demeter in violent ways, so you should consider any - # use of `receive_message_chain` a code smell. Even though not all code smells - # indicate real problems (think fluent interfaces), `receive_message_chain` still - # results in brittle examples. For example, if you write - # `allow(foo).to receive_message_chain(:bar, :baz => 37)` in a spec and then the - # implementation calls `foo.baz.bar`, the stub will not work. - # - # @example - # - # allow(double).to receive_message_chain("foo.bar") { :baz } - # allow(double).to receive_message_chain(:foo, :bar => :baz) - # allow(double).to receive_message_chain(:foo, :bar) { :baz } - # - # # Given any of ^^ these three forms ^^: - # double.foo.bar # => :baz - # - # # Common use in Rails/ActiveRecord: - # allow(Article).to receive_message_chain("recent.published") { [Article.new] } - # - # @note If you disable the `:expect` syntax this method will be undefined. - - # @private - def self.included(klass) - klass.class_exec do - # This gets mixed in so that if `RSpec::Matchers` is included in - # `klass` later, it's definition of `expect` will take precedence. - include ExpectHost unless method_defined?(:expect) - end - end - - # @private - def self.declare_verifying_double(type, ref, *args) - if RSpec::Mocks.configuration.verify_doubled_constant_names? && - !ref.defined? - - raise VerifyingDoubleNotDefinedError, - "#{ref.description} is not a defined constant. " + - "Perhaps you misspelt it? " + - "Disable check with verify_doubled_constant_names configuration option." - end - - declare_double(type, ref, *args) - end - - # @private - def self.declare_double(type, *args) - args << {} unless Hash === args.last - type.new(*args) - end - - # This module exists to host the `expect` method for cases where - # rspec-mocks is used w/o rspec-expectations. - module ExpectHost - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/instance_method_stasher.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/instance_method_stasher.rb deleted file mode 100644 index b7e6446..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/instance_method_stasher.rb +++ /dev/null @@ -1,135 +0,0 @@ -module RSpec - module Mocks - # @private - class InstanceMethodStasher - def initialize(object, method) - @object = object - @method = method - @klass = (class << object; self; end) - - @original_method = nil - @method_is_stashed = false - end - - attr_reader :original_method - - if RUBY_VERSION.to_f < 1.9 - # @private - def method_is_stashed? - @method_is_stashed - end - - # @private - def stash - return if !method_defined_directly_on_klass? || @method_is_stashed - - @klass.__send__(:alias_method, stashed_method_name, @method) - @method_is_stashed = true - end - - # @private - def stashed_method_name - "obfuscated_by_rspec_mocks__#{@method}" - end - private :stashed_method_name - - # @private - def restore - return unless @method_is_stashed - - if @klass.__send__(:method_defined?, @method) - @klass.__send__(:undef_method, @method) - end - @klass.__send__(:alias_method, @method, stashed_method_name) - @klass.__send__(:remove_method, stashed_method_name) - @method_is_stashed = false - end - else - - # @private - def method_is_stashed? - !!@original_method - end - - # @private - def stash - return if !method_defined_directly_on_klass? - @original_method ||= ::RSpec::Support.method_handle_for(@object, @method) - end - - # @private - def restore - return unless @original_method - - if @klass.__send__(:method_defined?, @method) - @klass.__send__(:undef_method, @method) - end - - handle_restoration_failures do - @klass.__send__(:define_method, @method, @original_method) - end - - @original_method = nil - end - end - - if RUBY_DESCRIPTION.include?('2.0.0p247') || RUBY_DESCRIPTION.include?('2.0.0p195') - # ruby 2.0.0-p247 and 2.0.0-p195 both have a bug that we can't work around :(. - # https://bugs.ruby-lang.org/issues/8686 - def handle_restoration_failures - yield - rescue TypeError - RSpec.warn_with( - "RSpec failed to properly restore a partial double (#{@object.inspect}) " + - "to its original state due to a known bug in MRI 2.0.0-p195 & p247 " + - "(https://bugs.ruby-lang.org/issues/8686). This object may remain " + - "screwed up for the rest of this process. Please upgrade to 2.0.0-p353 or above.", - :call_site => nil, :use_spec_location_as_call_site => true - ) - end - else - def handle_restoration_failures - # No known reasons for restoration to fail on other rubies. - yield - end - end - - private - - # @private - def method_defined_directly_on_klass? - method_defined_on_klass? && method_owned_by_klass? - end - - # @private - def method_defined_on_klass?(klass = @klass) - MethodReference.method_defined_at_any_visibility?(klass, @method) - end - - def method_owned_by_klass? - owner = @klass.instance_method(@method).owner - - # On Ruby 2.0.0+ the owner of a method on a class which has been - # `prepend`ed may actually be an instance, e.g. - # `#`, rather than the expected `MyClass`. - owner = owner.class unless Module === owner - - # On some 1.9s (e.g. rubinius) aliased methods - # can report the wrong owner. Example: - # class MyClass - # class << self - # alias alternate_new new - # end - # end - # - # MyClass.owner(:alternate_new) returns `Class` when incorrect, - # but we need to consider the owner to be `MyClass` because - # it is not actually available on `Class` but is on `MyClass`. - # Hence, we verify that the owner actually has the method defined. - # If the given owner does not have the method defined, we assume - # that the method is actually owned by @klass. - owner == @klass || !(method_defined_on_klass?(owner)) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/marshal_extension.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/marshal_extension.rb deleted file mode 100644 index cfa9c1a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/marshal_extension.rb +++ /dev/null @@ -1,41 +0,0 @@ -module RSpec - module Mocks - # Support for `patch_marshal_to_support_partial_doubles` configuration. - # - # @private - class MarshalExtension - def self.patch! - return if Marshal.respond_to?(:dump_with_rspec_mocks) - - Marshal.instance_eval do - class << self - def dump_with_rspec_mocks(object, *rest) - if !::RSpec::Mocks.space.registered?(object) || NilClass === object - dump_without_rspec_mocks(object, *rest) - else - dump_without_rspec_mocks(object.dup, *rest) - end - end - - alias_method :dump_without_rspec_mocks, :dump - undef_method :dump - alias_method :dump, :dump_with_rspec_mocks - end - end - end - - def self.unpatch! - return unless Marshal.respond_to?(:dump_with_rspec_mocks) - - Marshal.instance_eval do - class << self - undef_method :dump_with_rspec_mocks - undef_method :dump - alias_method :dump, :dump_without_rspec_mocks - undef_method :dump_without_rspec_mocks - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/expectation_customization.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/expectation_customization.rb deleted file mode 100644 index 81e6427..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/expectation_customization.rb +++ /dev/null @@ -1,20 +0,0 @@ -module RSpec - module Mocks - module Matchers - # @private - class ExpectationCustomization - attr_accessor :block - - def initialize(method_name, args, block) - @method_name = method_name - @args = args - @block = block - end - - def playback_onto(expectation) - expectation.__send__(@method_name, *@args, &@block) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/have_received.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/have_received.rb deleted file mode 100644 index 2675b54..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/have_received.rb +++ /dev/null @@ -1,104 +0,0 @@ -module RSpec - module Mocks - module Matchers - # @private - class HaveReceived - COUNT_CONSTRAINTS = %w(exactly at_least at_most times once twice) - ARGS_CONSTRAINTS = %w(with) - CONSTRAINTS = COUNT_CONSTRAINTS + ARGS_CONSTRAINTS + %w(ordered) - - def initialize(method_name, &block) - @method_name = method_name - @block = block - @constraints = [] - @subject = nil - end - - def name - "have_received" - end - - def matches?(subject, &block) - @block ||= block - @subject = subject - @expectation = expect - mock_proxy.ensure_implemented(@method_name) - - expected_messages_received_in_order? - end - - def does_not_match?(subject) - @subject = subject - ensure_count_unconstrained - @expectation = expect.never - mock_proxy.ensure_implemented(@method_name) - expected_messages_received_in_order? - end - - def failure_message - generate_failure_message - end - - def failure_message_when_negated - generate_failure_message - end - - def description - expect.description - end - - CONSTRAINTS.each do |expectation| - define_method expectation do |*args| - @constraints << [expectation, *args] - self - end - end - - private - - def expect - @expectation ||= begin - expectation = mock_proxy.build_expectation(@method_name) - apply_constraints_to expectation - expectation - end - end - - def apply_constraints_to(expectation) - @constraints.each do |constraint| - expectation.send(*constraint) - end - end - - def ensure_count_unconstrained - if count_constraint - raise RSpec::Mocks::MockExpectationError, - "can't use #{count_constraint} when negative" - end - end - - def count_constraint - @constraints.map(&:first).detect do |constraint| - COUNT_CONSTRAINTS.include?(constraint) - end - end - - def generate_failure_message - mock_proxy.check_for_unexpected_arguments(@expectation) - @expectation.generate_error - rescue RSpec::Mocks::MockExpectationError => error - error.message - end - - def expected_messages_received_in_order? - mock_proxy.replay_received_message_on @expectation, &@block - @expectation.expected_messages_received? && @expectation.ensure_expected_ordering_received! - end - - def mock_proxy - RSpec::Mocks.space.proxy_for(@subject) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive.rb deleted file mode 100644 index e5ff394..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive.rb +++ /dev/null @@ -1,106 +0,0 @@ -RSpec::Support.require_rspec_mocks 'matchers/expectation_customization' - -module RSpec - module Mocks - module Matchers - # @private - class Receive - def initialize(message, block) - @message = message - @block = block - @recorded_customizations = [] - end - - def name - "receive" - end - - def setup_expectation(subject, &block) - warn_if_any_instance("expect", subject) - setup_mock_proxy_method_substitute(subject, :add_message_expectation, block) - end - alias matches? setup_expectation - - def setup_negative_expectation(subject, &block) - # ensure `never` goes first for cases like `never.and_return(5)`, - # where `and_return` is meant to raise an error - @recorded_customizations.unshift ExpectationCustomization.new(:never, [], nil) - - warn_if_any_instance("expect", subject) - - setup_expectation(subject, &block) - end - alias does_not_match? setup_negative_expectation - - def setup_allowance(subject, &block) - warn_if_any_instance("allow", subject) - setup_mock_proxy_method_substitute(subject, :add_stub, block) - end - - def setup_any_instance_expectation(subject, &block) - setup_any_instance_method_substitute(subject, :should_receive, block) - end - - def setup_any_instance_negative_expectation(subject, &block) - setup_any_instance_method_substitute(subject, :should_not_receive, block) - end - - def setup_any_instance_allowance(subject, &block) - setup_any_instance_method_substitute(subject, :stub, block) - end - - MessageExpectation.public_instance_methods(false).each do |method| - next if method_defined?(method) - - define_method(method) do |*args, &block| - @recorded_customizations << ExpectationCustomization.new(method, args, block) - self - end - end - - private - - def warn_if_any_instance(expression, subject) - if AnyInstance::Proxy === subject - RSpec.warning( - "`#{expression}(#{subject.klass}.any_instance).to` " << - "is probably not what you meant, it does not operate on " << - "any instance of `#{subject.klass}`. " << - "Use `#{expression}_any_instance_of(#{subject.klass}).to` instead." - ) - end - end - - def setup_mock_proxy_method_substitute(subject, method, block) - proxy = ::RSpec::Mocks.space.proxy_for(subject) - setup_method_substitute(proxy, method, block) - end - - def setup_any_instance_method_substitute(subject, method, block) - proxy = ::RSpec::Mocks.space.any_instance_proxy_for(subject) - setup_method_substitute(proxy, method, block) - end - - def setup_method_substitute(host, method, block, *args) - args << @message.to_sym - block = move_block_to_last_customization(block) - - expectation = host.__send__(method, *args, &(@block || block)) - - @recorded_customizations.each do |customization| - customization.playback_onto(expectation) - end - expectation - end - - def move_block_to_last_customization(block) - last = @recorded_customizations.last - return block unless last - - last.block ||= block - nil - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive_message_chain.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive_message_chain.rb deleted file mode 100644 index d45e493..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive_message_chain.rb +++ /dev/null @@ -1,67 +0,0 @@ -RSpec::Support.require_rspec_mocks 'matchers/expectation_customization' - -module RSpec - module Mocks - module Matchers - # @private - class ReceiveMessageChain - def initialize(chain, &block) - @chain = chain - @block = block - @recorded_customizations = [] - end - - [:with, :and_return, :and_throw, :and_raise, :and_yield, :and_call_original].each do |msg| - define_method(msg) do |*args, &block| - @recorded_customizations << ExpectationCustomization.new(msg, args, block) - self - end - end - - def name - "receive_message_chain" - end - - def setup_allowance(subject, &block) - chain = StubChain.stub_chain_on(subject, *@chain, &(@block || block)) - replay_customizations(chain) - end - - def setup_any_instance_allowance(subject, &block) - proxy = ::RSpec::Mocks.space.any_instance_proxy_for(subject) - chain = proxy.stub_chain(*@chain, &(@block || block)) - replay_customizations(chain) - end - - def setup_any_instance_expectation(subject, &block) - proxy = ::RSpec::Mocks.space.any_instance_proxy_for(subject) - chain = proxy.expect_chain(*@chain, &(@block || block)) - replay_customizations(chain) - end - - def setup_expectation(subject, &block) - chain = ExpectChain.expect_chain_on(subject, *@chain, &(@block || block)) - replay_customizations(chain) - end - - def setup_negative_expectation(*args) - raise NegationUnsupportedError.new( - "`expect(...).not_to receive_message_chain` is not supported " + - "since it doesn't really make sense. What would it even mean?" - ) - end - - alias matches? setup_expectation - alias does_not_match? setup_negative_expectation - - private - - def replay_customizations(chain) - @recorded_customizations.each do |customization| - customization.playback_onto(chain) - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive_messages.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive_messages.rb deleted file mode 100644 index 1fcb03d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/matchers/receive_messages.rb +++ /dev/null @@ -1,72 +0,0 @@ -module RSpec - module Mocks - module Matchers - # @private - class ReceiveMessages - - def initialize(message_return_value_hash) - @message_return_value_hash = message_return_value_hash - @backtrace_line = CallerFilter.first_non_rspec_line - end - - def name - "receive_messages" - end - - def setup_expectation(subject) - warn_about_block if block_given? - each_message_on( proxy_on(subject) ) do |host, message, return_value| - host.add_simple_expectation(message, return_value, @backtrace_line) - end - end - alias matches? setup_expectation - - def setup_negative_expectation(subject) - raise NegationUnsupportedError, - "`expect(...).to_not receive_messages` is not supported since it " + - "doesn't really make sense. What would it even mean?" - end - alias does_not_match? setup_negative_expectation - - def setup_allowance(subject) - warn_about_block if block_given? - each_message_on( proxy_on(subject) ) do |host, message, return_value| - host.add_simple_stub(message, return_value) - end - end - - def setup_any_instance_expectation(subject) - warn_about_block if block_given? - each_message_on( any_instance_of(subject) ) do |host, message, return_value| - host.should_receive(message).and_return(return_value) - end - end - - def setup_any_instance_allowance(subject) - warn_about_block if block_given? - any_instance_of(subject).stub(@message_return_value_hash) - end - - def warn_about_block - raise "Implementation blocks aren't supported with `receive_messages`" - end - - private - - def proxy_on(subject) - ::RSpec::Mocks.space.proxy_for(subject) - end - - def any_instance_of(subject) - ::RSpec::Mocks.space.any_instance_proxy_for(subject) - end - - def each_message_on(host) - @message_return_value_hash.each do |message, value| - yield host, message, value - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/message_chain.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/message_chain.rb deleted file mode 100644 index f6fc44d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/message_chain.rb +++ /dev/null @@ -1,91 +0,0 @@ -module RSpec - module Mocks - # @private - class MessageChain - attr_reader :object, :chain, :block - - def initialize(object, *chain, &blk) - @object = object - @chain, @block = format_chain(*chain, &blk) - end - - # @api private - def setup_chain - if chain.length > 1 - if matching_stub = find_matching_stub - chain.shift - chain_on(matching_stub.invoke(nil), *chain, &@block) - elsif matching_expectation = find_matching_expectation - chain.shift - chain_on(matching_expectation.invoke_without_incrementing_received_count(nil), *chain, &@block) - else - next_in_chain = Double.new - expectation(object, chain.shift) { next_in_chain } - chain_on(next_in_chain, *chain, &@block) - end - else - expectation(object, chain.shift, &@block) - end - end - - private - - def expectation(object, message, &return_block) - raise NotImplementedError.new - end - - def chain_on(object, *chain, &block) - initialize(object, *chain, &block) - setup_chain - end - - def format_chain(*chain, &blk) - if Hash === chain.last - hash = chain.pop - hash.each do |k,v| - chain << k - blk = Proc.new { v } - end - end - return chain.join('.').split('.'), blk - end - - def find_matching_stub - ::RSpec::Mocks.space.proxy_for(object). - __send__(:find_matching_method_stub, chain.first.to_sym) - end - - def find_matching_expectation - ::RSpec::Mocks.space.proxy_for(object). - __send__(:find_matching_expectation, chain.first.to_sym) - end - end - - # @private - class ExpectChain < MessageChain - # @api private - def self.expect_chain_on(object, *chain, &blk) - new(object, *chain, &blk).setup_chain - end - - private - - def expectation(object, message, &return_block) - ::RSpec::Mocks.expect_message(object, message, {}, &return_block) - end - end - - # @private - class StubChain < MessageChain - def self.stub_chain_on(object, *chain, &blk) - new(object, *chain, &blk).setup_chain - end - - private - - def expectation(object, message, &return_block) - ::RSpec::Mocks.allow_message(object, message, {}, &return_block) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/message_expectation.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/message_expectation.rb deleted file mode 100644 index 7c7ce64..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/message_expectation.rb +++ /dev/null @@ -1,661 +0,0 @@ -module RSpec - module Mocks - - # A message expectation that only allows concrete return values to be set - # for a message. While this same effect can be achieved using a standard - # MessageExpecation, this version is much faster and so can be used as an - # optimization. - # - # @private - class SimpleMessageExpectation - - def initialize(message, response, error_generator, backtrace_line = nil) - @message, @response, @error_generator, @backtrace_line = message.to_sym, response, error_generator, backtrace_line - @received = false - end - - def invoke(*_) - @received = true - @response - end - - def matches?(message, *_) - @message == message.to_sym - end - - def called_max_times? - false - end - - def verify_messages_received - InsertOntoBacktrace.line(@backtrace_line) do - unless @received - @error_generator.raise_expectation_error(@message, 1, ArgumentListMatcher::MATCH_ALL, 0, nil) - end - end - end - end - - # @private - class MessageExpectation - # @private - attr_accessor :error_generator, :implementation - attr_reader :message - attr_reader :orig_object - attr_writer :expected_received_count, :expected_from, :argument_list_matcher - protected :expected_received_count=, :expected_from=, :error_generator, :error_generator=, :implementation= - - # @private - def initialize(error_generator, expectation_ordering, expected_from, method_double, - type=:expectation, opts={}, &implementation_block) - @error_generator = error_generator - @error_generator.opts = opts - @expected_from = expected_from - @method_double = method_double - @orig_object = @method_double.object - @message = @method_double.method_name - @actual_received_count = 0 - @expected_received_count = type == :expectation ? 1 : :any - @argument_list_matcher = ArgumentListMatcher::MATCH_ALL - @order_group = expectation_ordering - @order_group.register(self) unless type == :stub - @expectation_type = type - @ordered = false - @at_least = @at_most = @exactly = nil - @args_to_yield = [] - @failed_fast = nil - @eval_context = nil - @yield_receiver_to_implementation_block = false - - @implementation = Implementation.new - self.inner_implementation_action = implementation_block - end - - # @private - def expected_args - @argument_list_matcher.expected_args - end - - # @overload and_return(value) - # @overload and_return(first_value, second_value) - # - # Tells the object to return a value when it receives the message. Given - # more than one value, the first value is returned the first time the - # message is received, the second value is returned the next time, etc, - # etc. - # - # If the message is received more times than there are values, the last - # value is received for every subsequent call. - # - # @example - # - # allow(counter).to receive(:count).and_return(1) - # counter.count # => 1 - # counter.count # => 1 - # - # allow(counter).to receive(:count).and_return(1,2,3) - # counter.count # => 1 - # counter.count # => 2 - # counter.count # => 3 - # counter.count # => 3 - # counter.count # => 3 - # # etc - def and_return(first_value, *values) - if negative? - raise "`and_return` is not supported with negative message expectations" - end - - if block_given? - raise ArgumentError, "Implementation blocks aren't supported with `and_return`" - end - - values.unshift(first_value) - @expected_received_count = [@expected_received_count, values.size].max unless ignoring_args? || (@expected_received_count == 0 and @at_least) - self.terminal_implementation_action = AndReturnImplementation.new(values) - - nil - end - - def and_yield_receiver_to_implementation - @yield_receiver_to_implementation_block = true - self - end - - def yield_receiver_to_implementation_block? - @yield_receiver_to_implementation_block - end - - # Tells the object to delegate to the original unmodified method - # when it receives the message. - # - # @note This is only available on partial doubles. - # - # @example - # - # expect(counter).to receive(:increment).and_call_original - # original_count = counter.count - # counter.increment - # expect(counter.count).to eq(original_count + 1) - def and_call_original - if RSpec::Mocks::TestDouble === @method_double.object - @error_generator.raise_only_valid_on_a_partial_double(:and_call_original) - else - warn_about_stub_override if implementation.inner_action - @implementation = AndCallOriginalImplementation.new(@method_double.original_method) - @yield_receiver_to_implementation_block = false - end - end - - # @overload and_raise - # @overload and_raise(ExceptionClass) - # @overload and_raise(ExceptionClass, message) - # @overload and_raise(exception_instance) - # - # Tells the object to raise an exception when the message is received. - # - # @note - # - # When you pass an exception class, the MessageExpectation will raise - # an instance of it, creating it with `exception` and passing `message` - # if specified. If the exception class initializer requires more than - # one parameters, you must pass in an instance and not the class, - # otherwise this method will raise an ArgumentError exception. - # - # @example - # - # allow(car).to receive(:go).and_raise - # allow(car).to receive(:go).and_raise(OutOfGas) - # allow(car).to receive(:go).and_raise(OutOfGas, "At least 2 oz of gas needed to drive") - # allow(car).to receive(:go).and_raise(OutOfGas.new(2, :oz)) - def and_raise(exception = RuntimeError, message = nil) - if exception.respond_to?(:exception) - exception = message ? exception.exception(message) : exception.exception - end - - self.terminal_implementation_action = Proc.new { raise exception } - nil - end - - # @overload and_throw(symbol) - # @overload and_throw(symbol, object) - # - # Tells the object to throw a symbol (with the object if that form is - # used) when the message is received. - # - # @example - # - # allow(car).to receive(:go).and_throw(:out_of_gas) - # allow(car).to receive(:go).and_throw(:out_of_gas, :level => 0.1) - def and_throw(*args) - self.terminal_implementation_action = Proc.new { throw(*args) } - nil - end - - # Tells the object to yield one or more args to a block when the message - # is received. - # - # @example - # - # stream.stub(:open).and_yield(StringIO.new) - def and_yield(*args, &block) - yield @eval_context = Object.new if block - @args_to_yield << args - self.initial_implementation_action = AndYieldImplementation.new(@args_to_yield, @eval_context, @error_generator) - self - end - - # @private - def matches?(message, *args) - @message == message && @argument_list_matcher.args_match?(*args) - end - - # @private - def invoke(parent_stub, *args, &block) - invoke_incrementing_actual_calls_by(1, parent_stub, *args, &block) - end - - # @private - def invoke_without_incrementing_received_count(parent_stub, *args, &block) - invoke_incrementing_actual_calls_by(0, parent_stub, *args, &block) - end - - # @private - def negative? - @expected_received_count == 0 && !@at_least - end - - # @private - def called_max_times? - @expected_received_count != :any && - !@at_least && - @expected_received_count > 0 && - @actual_received_count >= @expected_received_count - end - - # @private - def matches_name_but_not_args(message, *args) - @message == message and not @argument_list_matcher.args_match?(*args) - end - - # @private - def verify_messages_received - InsertOntoBacktrace.line(@expected_from) do - generate_error unless expected_messages_received? || failed_fast? - end - end - - # @private - def expected_messages_received? - ignoring_args? || matches_exact_count? || matches_at_least_count? || matches_at_most_count? - end - - def ensure_expected_ordering_received! - @order_group.verify_invocation_order(self) if @ordered - true - end - - # @private - def ignoring_args? - @expected_received_count == :any - end - - # @private - def matches_at_least_count? - @at_least && @actual_received_count >= @expected_received_count - end - - # @private - def matches_at_most_count? - @at_most && @actual_received_count <= @expected_received_count - end - - # @private - def matches_exact_count? - @expected_received_count == @actual_received_count - end - - # @private - def similar_messages - @similar_messages ||= [] - end - - # @private - def advise(*args) - similar_messages << args - end - - # @private - def generate_error - if similar_messages.empty? - @error_generator.raise_expectation_error(@message, @expected_received_count, @argument_list_matcher, @actual_received_count, expectation_count_type, *expected_args) - else - @error_generator.raise_similar_message_args_error(self, *@similar_messages) - end - end - - def expectation_count_type - return :at_least if @at_least - return :at_most if @at_most - return nil - end - - # @private - def description - @error_generator.describe_expectation(@message, @expected_received_count, @actual_received_count, *expected_args) - end - - def raise_out_of_order_error - @error_generator.raise_out_of_order_error @message - end - - # Constrains a stub or message expectation to invocations with specific - # arguments. - # - # With a stub, if the message might be received with other args as well, - # you should stub a default value first, and then stub or mock the same - # message using `with` to constrain to specific arguments. - # - # A message expectation will fail if the message is received with different - # arguments. - # - # @example - # - # allow(cart).to receive(:add) { :failure } - # allow(cart).to receive(:add).with(Book.new(:isbn => 1934356379)) { :success } - # cart.add(Book.new(:isbn => 1234567890)) - # # => :failure - # cart.add(Book.new(:isbn => 1934356379)) - # # => :success - # - # expect(cart).to receive(:add).with(Book.new(:isbn => 1934356379)) { :success } - # cart.add(Book.new(:isbn => 1234567890)) - # # => failed expectation - # cart.add(Book.new(:isbn => 1934356379)) - # # => passes - def with(*args, &block) - if args.empty? - raise ArgumentError, - "`with` must have at least one argument. Use `no_args` matcher to set the expectation of receiving no arguments." - end - - self.inner_implementation_action = block - @argument_list_matcher = ArgumentListMatcher.new(*args) - self - end - - # Constrain a message expectation to be received a specific number of - # times. - # - # @example - # - # expect(dealer).to receive(:deal_card).exactly(10).times - def exactly(n, &block) - self.inner_implementation_action = block - set_expected_received_count :exactly, n - self - end - - # Constrain a message expectation to be received at least a specific - # number of times. - # - # @example - # - # expect(dealer).to receive(:deal_card).at_least(9).times - def at_least(n, &block) - set_expected_received_count :at_least, n - - if n == 0 - raise "at_least(0) has been removed, use allow(...).to receive(:message) instead" - end - - self.inner_implementation_action = block - - self - end - - # Constrain a message expectation to be received at most a specific - # number of times. - # - # @example - # - # expect(dealer).to receive(:deal_card).at_most(10).times - def at_most(n, &block) - self.inner_implementation_action = block - set_expected_received_count :at_most, n - self - end - - # Syntactic sugar for `exactly`, `at_least` and `at_most` - # - # @example - # - # expect(dealer).to receive(:deal_card).exactly(10).times - # expect(dealer).to receive(:deal_card).at_least(10).times - # expect(dealer).to receive(:deal_card).at_most(10).times - def times(&block) - self.inner_implementation_action = block - self - end - - # Expect a message not to be received at all. - # - # @example - # - # expect(car).to receive(:stop).never - def never - ErrorGenerator.raise_double_negation_error("expect(obj)") if negative? - @expected_received_count = 0 - self - end - - # Expect a message to be received exactly one time. - # - # @example - # - # expect(car).to receive(:go).once - def once(&block) - self.inner_implementation_action = block - set_expected_received_count :exactly, 1 - self - end - - # Expect a message to be received exactly two times. - # - # @example - # - # expect(car).to receive(:go).twice - def twice(&block) - self.inner_implementation_action = block - set_expected_received_count :exactly, 2 - self - end - - # Expect messages to be received in a specific order. - # - # @example - # - # expect(api).to receive(:prepare).ordered - # expect(api).to receive(:run).ordered - # expect(api).to receive(:finish).ordered - def ordered(&block) - self.inner_implementation_action = block - additional_expected_calls.times do - @order_group.register(self) - end - @ordered = true - self - end - - # @private - def additional_expected_calls - return 0 if @expectation_type == :stub || !@exactly - @expected_received_count - 1 - end - - - # @private - def ordered? - @ordered - end - - # @private - def negative_expectation_for?(message) - @message == message && negative? - end - - # @private - def actual_received_count_matters? - @at_least || @at_most || @exactly - end - - # @private - def increase_actual_received_count! - @actual_received_count += 1 - end - - private - - def invoke_incrementing_actual_calls_by(increment, parent_stub, *args, &block) - if yield_receiver_to_implementation_block? - args.unshift(orig_object) - end - - if negative? || ((@exactly || @at_most) && (@actual_received_count == @expected_received_count)) - @actual_received_count += increment - @failed_fast = true - #args are the args we actually received, @argument_list_matcher is the - #list of args we were expecting - @error_generator.raise_expectation_error(@message, @expected_received_count, @argument_list_matcher, @actual_received_count, expectation_count_type, *args) - end - - @order_group.handle_order_constraint self - - begin - if implementation.present? - implementation.call(*args, &block) - elsif parent_stub - parent_stub.invoke(nil, *args, &block) - end - ensure - @actual_received_count += increment - end - end - - def failed_fast? - @failed_fast - end - - def set_expected_received_count(relativity, n) - @at_least = (relativity == :at_least) - @at_most = (relativity == :at_most) - @exactly = (relativity == :exactly) - @expected_received_count = case n - when Numeric then n - when :once then 1 - when :twice then 2 - end - end - - def initial_implementation_action=(action) - implementation.initial_action = action - end - - def inner_implementation_action=(action) - return unless action - warn_about_stub_override if implementation.inner_action - implementation.inner_action = action - end - - def terminal_implementation_action=(action) - implementation.terminal_action = action - end - - def warn_about_stub_override - RSpec.warning( - "You're overriding a previous stub implementation of `#{@message}`. " + - "Called from #{CallerFilter.first_non_rspec_line}." - ) - end - end - - # Handles the implementation of an `and_yield` declaration. - # @private - class AndYieldImplementation - def initialize(args_to_yield, eval_context, error_generator) - @args_to_yield = args_to_yield - @eval_context = eval_context - @error_generator = error_generator - end - - def call(*args_to_ignore, &block) - return if @args_to_yield.empty? && @eval_context.nil? - - @error_generator.raise_missing_block_error @args_to_yield unless block - value = nil - block_signature = Support::BlockSignature.new(block) - - @args_to_yield.each do |args| - unless Support::MethodSignatureVerifier.new(block_signature, args).valid? - @error_generator.raise_wrong_arity_error(args, block_signature) - end - - value = @eval_context ? @eval_context.instance_exec(*args, &block) : block.call(*args) - end - value - end - end - - # Handles the implementation of an `and_return` implementation. - # @private - class AndReturnImplementation - def initialize(values_to_return) - @values_to_return = values_to_return - end - - def call(*args_to_ignore, &block) - if @values_to_return.size > 1 - @values_to_return.shift - else - @values_to_return.first - end - end - end - - # Represents a configured implementation. Takes into account - # any number of sub-implementations. - # @private - class Implementation - attr_accessor :initial_action, :inner_action, :terminal_action - - def call(*args, &block) - actions.map do |action| - action.call(*args, &block) - end.last - end - - def present? - actions.any? - end - - private - - def actions - [initial_action, inner_action, terminal_action].compact - end - end - - # Represents an `and_call_original` implementation. - # @private - class AndCallOriginalImplementation - def initialize(method) - @method = method - end - - CannotModifyFurtherError = Class.new(StandardError) - - def initial_action=(value) - raise cannot_modify_further_error - end - - def inner_action=(value) - raise cannot_modify_further_error - end - - def terminal_action=(value) - raise cannot_modify_further_error - end - - def present? - true - end - - def inner_action - true - end - - def call(*args, &block) - @method.call(*args, &block) - end - - private - - def cannot_modify_further_error - CannotModifyFurtherError.new "This method has already been configured " + - "to call the original implementation, and cannot be modified further." - end - end - - # Insert original locations into stacktraces - # - # @private - class InsertOntoBacktrace - def self.line(location) - yield - rescue RSpec::Mocks::MockExpectationError => error - error.backtrace.insert(0, location) - Kernel::raise error - end - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/method_double.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/method_double.rb deleted file mode 100644 index 000e577..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/method_double.rb +++ /dev/null @@ -1,257 +0,0 @@ -module RSpec - module Mocks - # @private - class MethodDouble - # @private - attr_reader :method_name, :object, :expectations, :stubs - - # @private - def initialize(object, method_name, proxy) - @method_name = method_name - @object = object - @proxy = proxy - - @original_visibility = nil - @method_stasher = InstanceMethodStasher.new(object, method_name) - @method_is_proxied = false - @expectations = [] - @stubs = [] - end - - def original_method - # If original method is not present, uses the `method_missing` - # handler of the object. This accounts for cases where the user has not - # correctly defined `respond_to?`, and also 1.8 which does not provide - # method handles for missing methods even if `respond_to?` is correct. - @original_method ||= - @method_stasher.original_method || - @proxy.original_method_handle_for(method_name) || - Proc.new do |*args, &block| - @object.__send__(:method_missing, @method_name, *args, &block) - end - end - - alias_method :save_original_method!, :original_method - - # @private - def visibility - @proxy.visibility_for(@method_name) - end - - # @private - def object_singleton_class - class << @object; self; end - end - - # @private - def configure_method - @original_visibility = [visibility, method_name] - @method_stasher.stash unless @method_is_proxied - define_proxy_method - end - - # @private - def define_proxy_method - return if @method_is_proxied - - save_original_method! - definition_target.class_exec(self, method_name, visibility) do |method_double, method_name, visibility| - define_method(method_name) do |*args, &block| - method_double.proxy_method_invoked(self, *args, &block) - end - self.__send__ visibility, method_name - end - - @method_is_proxied = true - end - - # The implementation of the proxied method. Subclasses may override this - # method to perform additional operations. - # - # @private - def proxy_method_invoked(obj, *args, &block) - @proxy.message_received method_name, *args, &block - end - - # @private - def restore_original_method - return show_frozen_warning if object_singleton_class.frozen? - return unless @method_is_proxied - - definition_target.__send__(:remove_method, @method_name) - - if @method_stasher.method_is_stashed? - @method_stasher.restore - end - restore_original_visibility - - @method_is_proxied = false - end - - # @private - def show_frozen_warning - RSpec.warn_with( - "WARNING: rspec-mocks was unable to restore the original `#{@method_name}` method on #{@object.inspect} because it has been frozen. If you reuse this object, `#{@method_name}` will continue to respond with its stub implementation.", - :call_site => nil, - :use_spec_location_as_call_site => true - ) - end - - # @private - def restore_original_visibility - return unless @original_visibility && - MethodReference.method_defined_at_any_visibility?(object_singleton_class, @method_name) - - object_singleton_class.__send__(*@original_visibility) - end - - # @private - def verify - expectations.each {|e| e.verify_messages_received} - end - - # @private - def reset - restore_original_method - clear - end - - # @private - def clear - expectations.clear - stubs.clear - end - - # The type of message expectation to create has been extracted to its own - # method so that subclasses can override it. - # - # @private - def message_expectation_class - MessageExpectation - end - - # @private - def add_expectation(error_generator, expectation_ordering, expected_from, opts, &implementation) - configure_method - expectation = message_expectation_class.new(error_generator, expectation_ordering, - expected_from, self, :expectation, opts, &implementation) - expectations << expectation - expectation - end - - # @private - def build_expectation(error_generator, expectation_ordering) - expected_from = IGNORED_BACKTRACE_LINE - message_expectation_class.new(error_generator, expectation_ordering, expected_from, self) - end - - # @private - def add_stub(error_generator, expectation_ordering, expected_from, opts={}, &implementation) - configure_method - stub = message_expectation_class.new(error_generator, expectation_ordering, expected_from, - self, :stub, opts, &implementation) - stubs.unshift stub - stub - end - - # A simple stub can only return a concrete value for a message, and - # cannot match on arguments. It is used as an optimization over - # `add_stub` / `add_expectation` where it is known in advance that this - # is all that will be required of a stub, such as when passing attributes - # to the `double` example method. They do not stash or restore existing method - # definitions. - # - # @private - def add_simple_stub(method_name, response) - setup_simple_method_double method_name, response, stubs - end - - # @private - def add_simple_expectation(method_name, response, error_generator, backtrace_line) - setup_simple_method_double method_name, response, expectations, error_generator, backtrace_line - end - - # @private - def setup_simple_method_double(method_name, response, collection, error_generator = nil, backtrace_line = nil) - define_proxy_method - - me = SimpleMessageExpectation.new(method_name, response, error_generator, backtrace_line) - collection.unshift me - me - end - - # @private - def add_default_stub(*args, &implementation) - return if stubs.any? - add_stub(*args, &implementation) - end - - # @private - def remove_stub - raise_method_not_stubbed_error if stubs.empty? - remove_stub_if_present - end - - # @private - def remove_stub_if_present - expectations.empty? ? reset : stubs.clear - end - - # @private - def raise_method_not_stubbed_error - raise MockExpectationError, "The method `#{method_name}` was not stubbed or was already unstubbed" - end - - private - - # In Ruby 2.0.0 and above prepend will alter the method lookup chain. - # We use an object's singleton class to define method doubles upon, - # however if the object has had it's singleton class (as opposed to - # it's actual class) prepended too then the the method lookup chain - # will look in the prepended module first, **before** the singleton - # class. - # - # This code works around that by providing a mock definition target - # that is either the singleton class, or if necessary, a prepended module - # of our own. - # - if Support::RubyFeatures.module_prepends_supported? - # We subclass `Module` in order to be able to easily detect our prepended module. - RSpecPrependedModule = Class.new(Module) - - def definition_target - @definition_target ||= usable_rspec_prepended_module || object_singleton_class - end - - def usable_rspec_prepended_module - @proxy.prepended_modules_of_singleton_class.each do |mod| - # If we have one of our modules prepended before one of the user's - # modules that defines the method, use that, since our module's - # definition will take precedence. - return mod if RSpecPrependedModule === mod - - # If we hit a user module with the method defined first, - # we must create a new prepend module, even if one exists later, - # because ours will only take precedence if it comes first. - return new_rspec_prepended_module if mod.method_defined?(method_name) - end - - nil - end - - def new_rspec_prepended_module - RSpecPrependedModule.new.tap do |mod| - object_singleton_class.__send__ :prepend, mod - end - end - - else - - def definition_target - object_singleton_class - end - - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/method_reference.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/method_reference.rb deleted file mode 100644 index cfc1f86..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/method_reference.rb +++ /dev/null @@ -1,154 +0,0 @@ -module RSpec - module Mocks - # Represents a method on an object that may or may not be defined. - # The method may be an instance method on a module or a method on - # any object. - # - # @private - class MethodReference - def initialize(object_reference, method_name) - @object_reference = object_reference - @method_name = method_name - end - - # A method is implemented if sending the message does not result in - # a `NoMethodError`. It might be dynamically implemented by - # `method_missing`. - def implemented? - @object_reference.when_loaded do |m| - method_implemented?(m) - end - end - - # Returns true if we definitively know that sending the method - # will result in a `NoMethodError`. - # - # This is not simply the inverse of `implemented?`: there are - # cases when we don't know if a method is implemented and - # both `implemented?` and `unimplemented?` will return false. - def unimplemented? - @object_reference.when_loaded do |m| - return !implemented? - end - - # If it's not loaded, then it may be implemented but we can't check. - false - end - - # A method is defined if we are able to get a `Method` object for it. - # In that case, we can assert against metadata like the arity. - def defined? - @object_reference.when_loaded do |m| - method_defined?(m) - end - end - - def with_signature - if original = original_method - yield Support::MethodSignature.new(original) - end - end - - def visibility - @object_reference.when_loaded do |m| - return visibility_from(m) - end - - # When it's not loaded, assume it's public. We don't want to - # wrongly treat the method as private. - :public - end - - private - - def original_method - @object_reference.when_loaded do |m| - self.defined? && find_method(m) - end - end - - def self.instance_method_visibility_for(klass, method_name) - if klass.public_method_defined?(method_name) - :public - elsif klass.private_method_defined?(method_name) - :private - elsif klass.protected_method_defined?(method_name) - :protected - end - end - - class << self - alias method_defined_at_any_visibility? instance_method_visibility_for - end - - def self.method_visibility_for(object, method_name) - instance_method_visibility_for(class << object; self; end, method_name).tap do |vis| - # If the method is not defined on the class, `instance_method_visibility_for` - # returns `nil`. However, it may be handled dynamically by `method_missing`, - # so here we check `respond_to` (passing false to not check private methods). - # - # This only considers the public case, but I don't think it's possible to - # write `method_missing` in such a way that it handles a dynamic message - # with private or protected visibility. Ruby doesn't provide you with - # the caller info. - return :public if vis.nil? && object.respond_to?(method_name, false) - end - end - end - - # @private - class InstanceMethodReference < MethodReference - private - def method_implemented?(mod) - MethodReference.method_defined_at_any_visibility?(mod, @method_name) - end - - # Ideally, we'd use `respond_to?` for `method_implemented?` but we need a - # reference to an instance to do that and we don't have one. Note that - # we may get false negatives: if the method is implemented via - # `method_missing`, we'll return `false` even though it meets our - # definition of "implemented". However, it's the best we can do. - alias method_defined? method_implemented? - - # works around the fact that repeated calls for method parameters will - # falsely return empty arrays on JRuby in certain circumstances, this - # is necessary here because we can't dup/clone UnboundMethods. - # - # This is necessary due to a bug in JRuby prior to 1.7.5 fixed in: - # https://github.com/jruby/jruby/commit/99a0613fe29935150d76a9a1ee4cf2b4f63f4a27 - if RUBY_PLATFORM == 'java' && JRUBY_VERSION.split('.')[-1].to_i < 5 - def find_method(mod) - mod.dup.instance_method(@method_name) - end - else - def find_method(mod) - mod.instance_method(@method_name) - end - end - - def visibility_from(mod) - MethodReference.instance_method_visibility_for(mod, @method_name) - end - end - - # @private - class ObjectMethodReference < MethodReference - private - def method_implemented?(object) - object.respond_to?(@method_name, true) - end - - def method_defined?(object) - (class << object; self; end).method_defined?(@method_name) - end - - def find_method(object) - object.method(@method_name) - end - - def visibility_from(object) - MethodReference.method_visibility_for(object, @method_name) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/mutate_const.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/mutate_const.rb deleted file mode 100644 index 90a9fbf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/mutate_const.rb +++ /dev/null @@ -1,398 +0,0 @@ -module RSpec - module Mocks - # Provides recursive constant lookup methods useful for - # constant stubbing. - # - # @private - module RecursiveConstMethods - # We only want to consider constants that are defined directly on a - # particular module, and not include top-level/inherited constants. - # Unfortunately, the constant API changed between 1.8 and 1.9, so - # we need to conditionally define methods to ignore the top-level/inherited - # constants. - # - # Given: - # class A; B = 1; end - # class C < A; end - # - # On 1.8: - # - C.const_get("Hash") # => ::Hash - # - C.const_defined?("Hash") # => false - # - C.constants # => ["B"] - # - None of these methods accept the extra `inherit` argument - # On 1.9: - # - C.const_get("Hash") # => ::Hash - # - C.const_defined?("Hash") # => true - # - C.const_get("Hash", false) # => raises NameError - # - C.const_defined?("Hash", false) # => false - # - C.constants # => [:B] - # - C.constants(false) #=> [] - if Module.method(:const_defined?).arity == 1 - def const_defined_on?(mod, const_name) - mod.const_defined?(const_name) - end - - def get_const_defined_on(mod, const_name) - if const_defined_on?(mod, const_name) - return mod.const_get(const_name) - end - - raise NameError, "uninitialized constant #{mod.name}::#{const_name}" - end - - def constants_defined_on(mod) - mod.constants.select { |c| const_defined_on?(mod, c) } - end - else - def const_defined_on?(mod, const_name) - mod.const_defined?(const_name, false) - end - - def get_const_defined_on(mod, const_name) - mod.const_get(const_name, false) - end - - def constants_defined_on(mod) - mod.constants(false) - end - end - - def recursive_const_get(const_name) - normalize_const_name(const_name).split('::').inject(Object) do |mod, name| - get_const_defined_on(mod, name) - end - end - - def recursive_const_defined?(const_name) - normalize_const_name(const_name).split('::').inject([Object, '']) do |(mod, full_name), name| - yield(full_name, name) if block_given? && !(Module === mod) - return false unless const_defined_on?(mod, name) - [get_const_defined_on(mod, name), [mod, name].join('::')] - end - end - - def normalize_const_name(const_name) - const_name.sub(/\A::/, '') - end - end - - # Provides information about constants that may (or may not) - # have been mutated by rspec-mocks. - class Constant - extend RecursiveConstMethods - - # @api private - def initialize(name) - @name = name - @previously_defined = false - @stubbed = false - @hidden = false - end - - # @return [String] The fully qualified name of the constant. - attr_reader :name - - # @return [Object, nil] The original value (e.g. before it - # was mutated by rspec-mocks) of the constant, or - # nil if the constant was not previously defined. - attr_accessor :original_value - - # @private - attr_writer :previously_defined, :stubbed, :hidden - - # @return [Boolean] Whether or not the constant was defined - # before the current example. - def previously_defined? - @previously_defined - end - - # @return [Boolean] Whether or not rspec-mocks has mutated - # (stubbed or hidden) this constant. - def mutated? - @stubbed || @hidden - end - - # @return [Boolean] Whether or not rspec-mocks has stubbed - # this constant. - def stubbed? - @stubbed - end - - # @return [Boolean] Whether or not rspec-mocks has hidden - # this constant. - def hidden? - @hidden - end - - # The default `to_s` isn't very useful, so a custom version is provided. - def to_s - "#<#{self.class.name} #{name}>" - end - alias inspect to_s - - # @private - def self.unmutated(name) - const = new(name) - const.previously_defined = recursive_const_defined?(name) - const.stubbed = false - const.hidden = false - const.original_value = recursive_const_get(name) if const.previously_defined? - - const - end - - # Queries rspec-mocks to find out information about the named constant. - # - # @param [String] name the name of the constant - # @return [Constant] an object contaning information about the named - # constant. - def self.original(name) - mutator = ::RSpec::Mocks.space.constant_mutator_for(name) - mutator ? mutator.to_constant : unmutated(name) - end - end - - # Provides a means to stub constants. - class ConstantMutator - extend RecursiveConstMethods - - # Stubs a constant. - # - # @param (see ExampleMethods#stub_const) - # @option (see ExampleMethods#stub_const) - # @return (see ExampleMethods#stub_const) - # - # @see ExampleMethods#stub_const - # @note It's recommended that you use `stub_const` in your - # examples. This is an alternate public API that is provided - # so you can stub constants in other contexts (e.g. helper - # classes). - def self.stub(constant_name, value, options = {}) - mutator = if recursive_const_defined?(constant_name, &raise_on_invalid_const) - DefinedConstantReplacer - else - UndefinedConstantSetter - end - - mutate(mutator.new(constant_name, value, options[:transfer_nested_constants])) - value - end - - # Hides a constant. - # - # @param (see ExampleMethods#hide_const) - # - # @see ExampleMethods#hide_const - # @note It's recommended that you use `hide_const` in your - # examples. This is an alternate public API that is provided - # so you can hide constants in other contexts (e.g. helper - # classes). - def self.hide(constant_name) - mutate(ConstantHider.new(constant_name, nil, { })) - nil - end - - # Contains common functionality used by all of the constant mutators. - # - # @private - class BaseMutator - include RecursiveConstMethods - - attr_reader :original_value, :full_constant_name - - def initialize(full_constant_name, mutated_value, transfer_nested_constants) - @full_constant_name = normalize_const_name(full_constant_name) - @mutated_value = mutated_value - @transfer_nested_constants = transfer_nested_constants - @context_parts = @full_constant_name.split('::') - @const_name = @context_parts.pop - @reset_performed = false - end - - def to_constant - const = Constant.new(full_constant_name) - const.original_value = original_value - - const - end - - def idempotently_reset - reset unless @reset_performed - @reset_performed = true - end - end - - # Hides a defined constant for the duration of an example. - # - # @private - class ConstantHider < BaseMutator - def mutate - return unless @defined = recursive_const_defined?(full_constant_name) - @context = recursive_const_get(@context_parts.join('::')) - @original_value = get_const_defined_on(@context, @const_name) - - @context.__send__(:remove_const, @const_name) - end - - def to_constant - return Constant.unmutated(full_constant_name) unless @defined - - const = super - const.hidden = true - const.previously_defined = true - - const - end - - def reset - return unless @defined - @context.const_set(@const_name, @original_value) - end - end - - # Replaces a defined constant for the duration of an example. - # - # @private - class DefinedConstantReplacer < BaseMutator - def initialize(*args) - super - @constants_to_transfer = [] - end - - def mutate - @context = recursive_const_get(@context_parts.join('::')) - @original_value = get_const_defined_on(@context, @const_name) - - @constants_to_transfer = verify_constants_to_transfer! - - @context.__send__(:remove_const, @const_name) - @context.const_set(@const_name, @mutated_value) - - transfer_nested_constants - end - - def to_constant - const = super - const.stubbed = true - const.previously_defined = true - - const - end - - def reset - @constants_to_transfer.each do |const| - @mutated_value.__send__(:remove_const, const) - end - - @context.__send__(:remove_const, @const_name) - @context.const_set(@const_name, @original_value) - end - - def transfer_nested_constants - @constants_to_transfer.each do |const| - @mutated_value.const_set(const, get_const_defined_on(original_value, const)) - end - end - - def verify_constants_to_transfer! - return [] unless should_transfer_nested_constants? - - { @original_value => "the original value", @mutated_value => "the stubbed value" }.each do |value, description| - unless value.respond_to?(:constants) - raise ArgumentError, - "Cannot transfer nested constants for #{@full_constant_name} " + - "since #{description} is not a class or module and only classes " + - "and modules support nested constants." - end - end - - if Array === @transfer_nested_constants - @transfer_nested_constants = @transfer_nested_constants.map(&:to_s) if RUBY_VERSION == '1.8.7' - undefined_constants = @transfer_nested_constants - constants_defined_on(@original_value) - - if undefined_constants.any? - available_constants = constants_defined_on(@original_value) - @transfer_nested_constants - raise ArgumentError, - "Cannot transfer nested constant(s) #{undefined_constants.join(' and ')} " + - "for #{@full_constant_name} since they are not defined. Did you mean " + - "#{available_constants.join(' or ')}?" - end - - @transfer_nested_constants - else - constants_defined_on(@original_value) - end - end - - def should_transfer_nested_constants? - return true if @transfer_nested_constants - return false unless RSpec::Mocks.configuration.transfer_nested_constants? - @original_value.respond_to?(:constants) && @mutated_value.respond_to?(:constants) - end - end - - # Sets an undefined constant for the duration of an example. - # - # @private - class UndefinedConstantSetter < BaseMutator - def mutate - @parent = @context_parts.inject(Object) do |klass, name| - if const_defined_on?(klass, name) - get_const_defined_on(klass, name) - else - ConstantMutator.stub(name_for(klass, name), Module.new) - end - end - - @parent.const_set(@const_name, @mutated_value) - end - - def to_constant - const = super - const.stubbed = true - const.previously_defined = false - - const - end - - def reset - @parent.__send__(:remove_const, @const_name) - end - - private - - def name_for(parent, name) - root = if parent == Object - '' - else - parent.name - end - root + '::' + name - end - end - - # Uses the mutator to mutate (stub or hide) a constant. Ensures that - # the mutator is correctly registered so it can be backed out at the end - # of the test. - # - # @private - def self.mutate(mutator) - ::RSpec::Mocks.space.register_constant_mutator(mutator) - mutator.mutate - end - - # Used internally by the constant stubbing to raise a helpful - # error when a constant like "A::B::C" is stubbed and A::B is - # not a module (and thus, it's impossible to define "A::B::C" - # since only modules can have nested constants). - # - # @api private - def self.raise_on_invalid_const - lambda do |const_name, failed_name| - raise "Cannot stub constant #{failed_name} on #{const_name} " + - "since #{const_name} is not a module." - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/object_reference.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/object_reference.rb deleted file mode 100644 index 9ccda42..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/object_reference.rb +++ /dev/null @@ -1,92 +0,0 @@ -module RSpec - module Mocks - - # @private - class ObjectReference - # Returns an appropriate Object or Module reference based - # on the given argument. - def self.for(object_module_or_name, allow_direct_object_refs = false) - case object_module_or_name - when Module then DirectModuleReference.new(object_module_or_name) - when String then NamedObjectReference.new(object_module_or_name) - else - if allow_direct_object_refs - DirectObjectReference.new(object_module_or_name) - else - raise ArgumentError, - "Module or String expected, got #{object_module_or_name.inspect}" - end - end - end - end - - # Used when an object is passed to `object_double`. - # Represents a reference to that object. - # - # @private - class DirectObjectReference - def initialize(object) - @object = object - end - - def description - @object.inspect - end - - def const_to_replace - raise ArgumentError, - "Can not perform constant replacement with an object." - end - - def defined? - true - end - - def when_loaded - yield @object - end - end - - # Used when a module is passed to `class_double` or `instance_double`. - # Represents a reference to that module. - # - # @private - class DirectModuleReference < DirectObjectReference - def const_to_replace - @object.name - end - alias description const_to_replace - end - - # Used when a string is passed to `class_double`, `instance_double` - # or `object_double`. - # Represents a reference to the object named (via a constant lookup) - # by the string. - # - # @private - class NamedObjectReference - def initialize(const_name) - @const_name = const_name - end - - def defined? - !!object - end - - def const_to_replace - @const_name - end - alias description const_to_replace - - def when_loaded(&block) - yield object if object - end - - private - - def object - @object ||= Constant.original(@const_name).original_value - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/order_group.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/order_group.rb deleted file mode 100644 index 52f882e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/order_group.rb +++ /dev/null @@ -1,82 +0,0 @@ -module RSpec - module Mocks - # @private - class OrderGroup - def initialize - @expectations = [] - @invocation_order = [] - @index = 0 - end - - # @private - def register(expectation) - @expectations << expectation - end - - def invoked(message) - @invocation_order << message - end - - # @private - def ready_for?(expectation) - remaining_expectations.find(&:ordered?) == expectation - end - - # @private - def consume - remaining_expectations.each_with_index do |expectation, index| - if expectation.ordered? - @index += index + 1 - return expectation - end - end - nil - end - - # @private - def handle_order_constraint(expectation) - return unless expectation.ordered? && remaining_expectations.include?(expectation) - return consume if ready_for?(expectation) - expectation.raise_out_of_order_error - end - - def verify_invocation_order(expectation) - expectation.raise_out_of_order_error unless expectations_invoked_in_order? - true - end - - def clear - @index = 0 - @invocation_order.clear - @expectations.clear - end - - def empty? - @expectations.empty? - end - - private - - def remaining_expectations - @expectations[@index..-1] || [] - end - - def expectations_invoked_in_order? - invoked_expectations == expected_invocations - end - - def invoked_expectations - @expectations.select { |e| e.ordered? && @invocation_order.include?(e) } - end - - def expected_invocations - @invocation_order.map { |invocation| expectation_for(invocation) }.compact - end - - def expectation_for(message) - @expectations.find { |e| message == e } - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/proxy.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/proxy.rb deleted file mode 100644 index 11074f5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/proxy.rb +++ /dev/null @@ -1,424 +0,0 @@ -module RSpec - module Mocks - # @private - class Proxy - SpecificMessage = Struct.new(:object, :message, :args) do - def ==(expectation) - expectation.orig_object == object && expectation.matches?(message, *args) - end - end - - # @private - def ensure_implemented(*args) - # noop for basic proxies, see VerifyingProxy for behaviour. - end - - # @private - def initialize(object, order_group, name=nil, options={}) - @object = object - @order_group = order_group - @name = name - @error_generator = ErrorGenerator.new(object, name) - @messages_received = [] - @options = options - @null_object = false - @method_doubles = Hash.new { |h, k| h[k] = MethodDouble.new(@object, k, self) } - end - - # @private - attr_reader :object - - # @private - def null_object? - @null_object - end - - # @private - # Tells the object to ignore any messages that aren't explicitly set as - # stubs or message expectations. - def as_null_object - @null_object = true - @object - end - - # @private - def original_method_handle_for(message) - nil - end - - # @private - def add_message_expectation(method_name, opts={}, &block) - location = opts.fetch(:expected_from) { CallerFilter.first_non_rspec_line } - meth_double = method_double_for(method_name) - - if null_object? && !block - meth_double.add_default_stub(@error_generator, @order_group, location, opts) do - @object - end - end - - meth_double.add_expectation @error_generator, @order_group, location, opts, &block - end - - # @private - def add_simple_expectation(method_name, response, location) - method_double_for(method_name).add_simple_expectation method_name, response, @error_generator, location - end - - # @private - def build_expectation(method_name) - meth_double = method_double_for(method_name) - - meth_double.build_expectation( - @error_generator, - @order_group - ) - end - - # @private - def replay_received_message_on(expectation, &block) - expected_method_name = expectation.message - meth_double = method_double_for(expected_method_name) - - if meth_double.expectations.any? - @error_generator.raise_expectation_on_mocked_method(expected_method_name) - end - - unless null_object? || meth_double.stubs.any? - @error_generator.raise_expectation_on_unstubbed_method(expected_method_name) - end - - @messages_received.each do |(actual_method_name, args, _)| - if expectation.matches?(actual_method_name, *args) - expectation.invoke(nil) - block.call(*args) if block - end - end - - end - - # @private - def check_for_unexpected_arguments(expectation) - @messages_received.each do |(method_name, args, _)| - if expectation.matches_name_but_not_args(method_name, *args) - raise_unexpected_message_args_error(expectation, *args) - end - end - end - - # @private - def add_stub(method_name, opts={}, &implementation) - location = opts.fetch(:expected_from) { CallerFilter.first_non_rspec_line } - method_double_for(method_name).add_stub @error_generator, @order_group, location, opts, &implementation - end - - # @private - def add_simple_stub(method_name, response) - method_double_for(method_name).add_simple_stub method_name, response - end - - # @private - def remove_stub(method_name) - method_double_for(method_name).remove_stub - end - - # @private - def remove_stub_if_present(method_name) - method_double_for(method_name).remove_stub_if_present - end - - # @private - def verify - @method_doubles.each_value {|d| d.verify} - end - - # @private - def reset - @messages_received.clear - end - - # @private - def received_message?(method_name, *args, &block) - @messages_received.any? {|array| array == [method_name, args, block]} - end - - # @private - def has_negative_expectation?(message) - method_double_for(message).expectations.detect {|expectation| expectation.negative_expectation_for?(message)} - end - - # @private - def record_message_received(message, *args, &block) - @order_group.invoked SpecificMessage.new(object, message, args) - @messages_received << [message, args, block] - end - - # @private - def message_received(message, *args, &block) - record_message_received message, *args, &block - - expectation = find_matching_expectation(message, *args) - stub = find_matching_method_stub(message, *args) - - if (stub && expectation && expectation.called_max_times?) || (stub && !expectation) - expectation.increase_actual_received_count! if expectation && expectation.actual_received_count_matters? - if expectation = find_almost_matching_expectation(message, *args) - expectation.advise(*args) unless expectation.expected_messages_received? - end - stub.invoke(nil, *args, &block) - elsif expectation - expectation.invoke(stub, *args, &block) - elsif expectation = find_almost_matching_expectation(message, *args) - expectation.advise(*args) if null_object? unless expectation.expected_messages_received? - raise_unexpected_message_args_error(expectation, *args) unless (has_negative_expectation?(message) or null_object?) - elsif stub = find_almost_matching_stub(message, *args) - stub.advise(*args) - raise_missing_default_stub_error(stub, *args) - elsif Class === @object - @object.superclass.__send__(message, *args, &block) - else - @object.__send__(:method_missing, message, *args, &block) - end - end - - # @private - def raise_unexpected_message_error(method_name, *args) - @error_generator.raise_unexpected_message_error method_name, *args - end - - # @private - def raise_unexpected_message_args_error(expectation, *args) - @error_generator.raise_unexpected_message_args_error(expectation, *args) - end - - # @private - def raise_missing_default_stub_error(expectation, *args) - @error_generator.raise_missing_default_stub_error(expectation, *args) - end - - # @private - def visibility_for(method_name) - # This is the default (for test doubles). Subclasses override this. - :public - end - - if Support::RubyFeatures.module_prepends_supported? - def prepended_modules_of_singleton_class - @prepended_modules_of_singleton_class ||= begin - singleton_class = @object.singleton_class - singleton_class.ancestors.take_while do |mod| - !(Class === mod || @object.equal?(mod)) - end - end - end - end - - private - - def method_double_for(message) - @method_doubles[message.to_sym] - end - - def find_matching_expectation(method_name, *args) - find_best_matching_expectation_for(method_name) do |expectation| - expectation.matches?(method_name, *args) - end - end - - def find_almost_matching_expectation(method_name, *args) - find_best_matching_expectation_for(method_name) do |expectation| - expectation.matches_name_but_not_args(method_name, *args) - end - end - - def find_best_matching_expectation_for(method_name) - first_match = nil - - method_double_for(method_name).expectations.each do |expectation| - next unless yield expectation - return expectation unless expectation.called_max_times? - first_match ||= expectation - end - - first_match - end - - def find_matching_method_stub(method_name, *args) - method_double_for(method_name).stubs.find {|stub| stub.matches?(method_name, *args)} - end - - def find_almost_matching_stub(method_name, *args) - method_double_for(method_name).stubs.find {|stub| stub.matches_name_but_not_args(method_name, *args)} - end - end - - # @private - class TestDoubleProxy < Proxy - def reset - @method_doubles.clear - object.__disallow_further_usage! - super - end - end - - # @private - class PartialDoubleProxy < Proxy - def original_method_handle_for(message) - if any_instance_class_recorder_observing_method?(@object.class, message) - message = ::RSpec::Mocks.space. - any_instance_recorder_for(@object.class). - build_alias_method_name(message) - end - - ::RSpec::Support.method_handle_for(@object, message) - rescue NameError - nil - end - - # @private - def add_simple_expectation(method_name, response, location) - method_double_for(method_name).configure_method - super - end - - # @private - def add_simple_stub(method_name, response) - method_double_for(method_name).configure_method - super - end - - # @private - def visibility_for(method_name) - # We fall back to :public because by default we allow undefined methods - # to be stubbed, and when we do so, we make them public. - MethodReference.method_visibility_for(@object, method_name) || :public - end - - def reset - @method_doubles.each_value {|d| d.reset} - super - end - - def message_received(message, *args, &block) - RSpec::Mocks.space.any_instance_recorders_from_ancestry_of(object).each do |subscriber| - subscriber.notify_received_message(object, message, args, block) - end - super - end - - private - - def any_instance_class_recorder_observing_method?(klass, method_name) - only_return_existing = true - recorder = ::RSpec::Mocks.space.any_instance_recorder_for(klass, only_return_existing) - return true if recorder && recorder.already_observing?(method_name) - - superklass = klass.superclass - return false if superklass.nil? - any_instance_class_recorder_observing_method?(superklass, method_name) - end - end - - # @private - # When we mock or stub a method on a class, we have to treat it a bit different, - # because normally singleton method definitions only affect the object on which - # they are defined, but on classes they affect subclasses, too. As a result, - # we need some special handling to get the original method. - module PartialClassDoubleProxyMethods - def initialize(source_space, *args) - @source_space = source_space - super(*args) - end - - # Consider this situation: - # - # class A; end - # class B < A; end - # - # allow(A).to receive(:new) - # expect(B).to receive(:new).and_call_original - # - # When getting the original definition for `B.new`, we cannot rely purely on - # using `B.method(:new)` before our redefinition is defined on `B`, because - # `B.method(:new)` will return a method that will execute the stubbed version - # of the method on `A` since singleton methods on classes are in the lookup - # hierarchy. - # - # To do it properly, we need to find the original definition of `new` from `A` - # from _before_ `A` was stubbed, and we need to rebind it to `B` so that it will - # run with the proper `self`. - # - # That's what this method (together with `original_unbound_method_handle_from_ancestor_for`) - # does. - def original_method_handle_for(message) - unbound_method = superclass_proxy && - superclass_proxy.original_unbound_method_handle_from_ancestor_for(message.to_sym) - - return super unless unbound_method - unbound_method.bind(object) - end - - protected - - def original_unbound_method_handle_from_ancestor_for(message) - method_double = @method_doubles.fetch(message) do - # The fact that there is no method double for this message indicates - # that it has not been redefined by rspec-mocks. We need to continue - # looking up the ancestor chain. - return superclass_proxy && - superclass_proxy.original_unbound_method_handle_from_ancestor_for(message) - end - - method_double.original_method.unbind - end - - def superclass_proxy - return @superclass_proxy if defined?(@superclass_proxy) - - if (superclass = object.superclass) - @superclass_proxy = @source_space.proxy_for(superclass) - else - @superclass_proxy = nil - end - end - end - - # @private - class PartialClassDoubleProxy < PartialDoubleProxy - include PartialClassDoubleProxyMethods - end - - # @private - class ProxyForNil < PartialDoubleProxy - def initialize(order_group) - @warn_about_expectations = true - super(nil, order_group) - end - - attr_accessor :warn_about_expectations - alias warn_about_expectations? warn_about_expectations - - def add_message_expectation(method_name, opts={}, &block) - warn(method_name) if warn_about_expectations? - super - end - - def add_negative_message_expectation(location, method_name, &implementation) - warn(method_name) if warn_about_expectations? - super - end - - def add_stub(method_name, opts={}, &implementation) - warn(method_name) if warn_about_expectations? - super - end - - private - - def warn method_name - source = CallerFilter.first_non_rspec_line - Kernel.warn("An expectation of :#{method_name} was set on nil. Called from #{source}. Use allow_message_expectations_on_nil to disable warnings.") - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/space.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/space.rb deleted file mode 100644 index 73ceae9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/space.rb +++ /dev/null @@ -1,221 +0,0 @@ -module RSpec - module Mocks - # @private - # Provides a default space implementation for outside - # the scope of an example. Called "root" because it serves - # as the root of the space stack. - class RootSpace - def proxy_for(*args) - raise_lifecycle_message - end - - def any_instance_recorder_for(*args) - raise_lifecycle_message - end - - def any_instance_proxy_for(*args) - raise_lifecycle_message - end - - def register_constant_mutator(mutator) - raise_lifecycle_message - end - - def any_instance_recorders_from_ancestry_of(object) - raise_lifecycle_message - end - - def reset_all - end - - def verify_all - end - - def registered?(object) - false - end - - def new_scope - Space.new - end - - private - - def raise_lifecycle_message - raise OutsideOfExampleError, - "The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported." - end - end - - # @private - class Space - attr_reader :proxies, :any_instance_recorders, :proxy_mutex, :any_instance_mutex - - def initialize - @proxies = {} - @any_instance_recorders = {} - @constant_mutators = [] - @expectation_ordering = OrderGroup.new - @proxy_mutex = new_mutex - @any_instance_mutex = new_mutex - end - - def new_scope - NestedSpace.new(self) - end - - def verify_all - proxies.values.each { |proxy| proxy.verify } - any_instance_recorders.each_value { |recorder| recorder.verify } - end - - def reset_all - proxies.each_value { |proxy| proxy.reset } - @constant_mutators.reverse.each { |mut| mut.idempotently_reset } - any_instance_recorders.each_value { |recorder| recorder.stop_all_observation! } - any_instance_recorders.clear - end - - def register_constant_mutator(mutator) - @constant_mutators << mutator - end - - def constant_mutator_for(name) - @constant_mutators.find { |m| m.full_constant_name == name } - end - - def any_instance_recorder_for(klass, only_return_existing = false) - any_instance_mutex.synchronize do - id = klass.__id__ - any_instance_recorders.fetch(id) do - return nil if only_return_existing - any_instance_recorder_not_found_for(id, klass) - end - end - end - - def any_instance_proxy_for(klass) - AnyInstance::Proxy.new(any_instance_recorder_for(klass), proxies_of(klass)) - end - - def proxies_of(klass) - proxies.values.select { |proxy| klass === proxy.object } - end - - def proxy_for(object) - proxy_mutex.synchronize do - id = id_for(object) - proxies.fetch(id) { proxy_not_found_for(id, object) } - end - end - - alias ensure_registered proxy_for - - def registered?(object) - proxies.has_key?(id_for object) - end - - def any_instance_recorders_from_ancestry_of(object) - # Optimization: `any_instance` is a feature we generally - # recommend not using, so we can often early exit here - # without doing an O(N) linear search over the number of - # ancestors in the object's class hierarchy. - return [] if any_instance_recorders.empty? - - # We access the ancestors through the singleton class, to avoid calling - # `class` in case `class` has been stubbed. - (class << object; ancestors; end).map do |klass| - any_instance_recorders[klass.__id__] - end.compact - end - - private - - # We don't want to depend on the stdlib ourselves, but if the user is - # using threads then a Mutex will be available to us. If not, we don't - # need to synchronize anyway. - def new_mutex - defined?(::Mutex) ? ::Mutex.new : FakeMutex - end - - # @private - module FakeMutex - def self.synchronize - yield - end - end - - def proxy_not_found_for(id, object) - proxies[id] = case object - when NilClass then ProxyForNil.new(@expectation_ordering) - when TestDouble then object.__build_mock_proxy_unless_expired(@expectation_ordering) - when Class - if RSpec::Mocks.configuration.verify_partial_doubles? - VerifyingPartialClassDoubleProxy.new(self, object, @expectation_ordering) - else - PartialClassDoubleProxy.new(self, object, @expectation_ordering) - end - else - if RSpec::Mocks.configuration.verify_partial_doubles? - VerifyingPartialDoubleProxy.new(object, @expectation_ordering) - else - PartialDoubleProxy.new(object, @expectation_ordering) - end - end - end - - def any_instance_recorder_not_found_for(id, klass) - any_instance_recorders[id] = AnyInstance::Recorder.new(klass) - end - - if defined?(::BasicObject) && !::BasicObject.method_defined?(:__id__) # for 1.9.2 - require 'securerandom' - - def id_for(object) - id = object.__id__ - - return id if object.equal?(::ObjectSpace._id2ref(id)) - # this suggests that object.__id__ is proxying through to some wrapped object - - object.instance_exec do - @__id_for_rspec_mocks_space ||= ::SecureRandom.uuid - end - end - else - def id_for(object) - object.__id__ - end - end - end - - # @private - class NestedSpace < Space - def initialize(parent) - @parent = parent - super() - end - - def proxies_of(klass) - super + @parent.proxies_of(klass) - end - - def constant_mutator_for(name) - super || @parent.constant_mutator_for(name) - end - - def registered?(object) - super || @parent.registered?(object) - end - - private - - def proxy_not_found_for(id, object) - @parent.proxies[id] || super - end - - def any_instance_recorder_not_found_for(id, klass) - @parent.any_instance_recorders[id] || super - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/standalone.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/standalone.rb deleted file mode 100644 index c586712..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/standalone.rb +++ /dev/null @@ -1,3 +0,0 @@ -require 'rspec/mocks' -include RSpec::Mocks::ExampleMethods -RSpec::Mocks.setup diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/syntax.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/syntax.rb deleted file mode 100644 index 1b5af12..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/syntax.rb +++ /dev/null @@ -1,329 +0,0 @@ -module RSpec - module Mocks - # @api private - # Provides methods for enabling and disabling the available syntaxes - # provided by rspec-mocks. - module Syntax - # @private - def self.warn_about_should! - @warn_about_should = true - end - - # @private - def self.warn_unless_should_configured(method_name ,replacement = "the new `:expect` syntax or explicitly enable `:should`") - if @warn_about_should - RSpec.deprecate( - "Using `#{method_name}` from rspec-mocks' old `:should` syntax without explicitly enabling the syntax", - :replacement => replacement - ) - - @warn_about_should = false - end - end - - # @api private - # Enables the should syntax (`dbl.stub`, `dbl.should_receive`, etc). - def self.enable_should(syntax_host = default_should_syntax_host) - @warn_about_should = false if syntax_host == default_should_syntax_host - return if should_enabled?(syntax_host) - - syntax_host.class_exec do - def should_receive(message, opts={}, &block) - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - ::RSpec::Mocks.expect_message(self, message, opts, &block) - end - - def should_not_receive(message, &block) - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - ::RSpec::Mocks.expect_message(self, message, {}, &block).never - end - - def stub(message_or_hash, opts={}, &block) - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - if ::Hash === message_or_hash - message_or_hash.each {|message, value| stub(message).and_return value } - else - ::RSpec::Mocks.allow_message(self, message_or_hash, opts, &block) - end - end - - def unstub(message) - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__, "`allow(...).to_receive(...).and_call_original` or explicitly enable `:should`") - ::RSpec::Mocks.space.proxy_for(self).remove_stub(message) - end - - def stub_chain(*chain, &blk) - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - ::RSpec::Mocks::StubChain.stub_chain_on(self, *chain, &blk) - end - - def as_null_object - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - @_null_object = true - ::RSpec::Mocks.space.proxy_for(self).as_null_object - end - - def null_object? - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - defined?(@_null_object) - end - - def received_message?(message, *args, &block) - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - ::RSpec::Mocks.space.proxy_for(self).received_message?(message, *args, &block) - end - - unless Class.respond_to? :any_instance - Class.class_exec do - def any_instance - ::RSpec::Mocks::Syntax.warn_unless_should_configured(__method__) - ::RSpec::Mocks.space.any_instance_proxy_for(self) - end - end - end - end - end - - # @api private - # Disables the should syntax (`dbl.stub`, `dbl.should_receive`, etc). - def self.disable_should(syntax_host = default_should_syntax_host) - return unless should_enabled?(syntax_host) - - syntax_host.class_exec do - undef should_receive - undef should_not_receive - undef stub - undef unstub - undef stub_chain - undef as_null_object - undef null_object? - undef received_message? - end - - Class.class_exec do - undef any_instance - end - end - - # @api private - # Enables the expect syntax (`expect(dbl).to receive`, `allow(dbl).to receive`, etc). - def self.enable_expect(syntax_host = ::RSpec::Mocks::ExampleMethods) - return if expect_enabled?(syntax_host) - - syntax_host.class_exec do - def receive(method_name, &block) - Matchers::Receive.new(method_name, block) - end - - def receive_messages(message_return_value_hash) - matcher = Matchers::ReceiveMessages.new(message_return_value_hash) - matcher.warn_about_block if block_given? - matcher - end - - def receive_message_chain(*messages, &block) - Matchers::ReceiveMessageChain.new(messages, &block) - end - - def allow(target) - AllowanceTarget.new(target) - end - - def expect_any_instance_of(klass) - AnyInstanceExpectationTarget.new(klass) - end - - def allow_any_instance_of(klass) - AnyInstanceAllowanceTarget.new(klass) - end - end - - RSpec::Mocks::ExampleMethods::ExpectHost.class_exec do - def expect(target) - ExpectationTarget.new(target) - end - end - end - - # @api private - # Disables the expect syntax (`expect(dbl).to receive`, `allow(dbl).to receive`, etc). - def self.disable_expect(syntax_host = ::RSpec::Mocks::ExampleMethods) - return unless expect_enabled?(syntax_host) - - syntax_host.class_exec do - undef receive - undef receive_messages - undef receive_message_chain - undef allow - undef expect_any_instance_of - undef allow_any_instance_of - end - - RSpec::Mocks::ExampleMethods::ExpectHost.class_exec do - undef expect - end - end - - # @api private - # Indicates whether or not the should syntax is enabled. - def self.should_enabled?(syntax_host = default_should_syntax_host) - syntax_host.method_defined?(:should_receive) - end - - # @api private - # Indicates whether or not the expect syntax is enabled. - def self.expect_enabled?(syntax_host = ::RSpec::Mocks::ExampleMethods) - syntax_host.method_defined?(:allow) - end - - # @api private - # Determines where the methods like `should_receive`, and `stub` are added. - def self.default_should_syntax_host - # JRuby 1.7.4 introduces a regression whereby `defined?(::BasicObject) => nil` - # yet `BasicObject` still exists and patching onto ::Object breaks things - # e.g. SimpleDelegator expectations won't work - # - # See: https://github.com/jruby/jruby/issues/814 - if defined?(JRUBY_VERSION) && JRUBY_VERSION == '1.7.4' && RUBY_VERSION.to_f > 1.8 - return ::BasicObject - end - - # On 1.8.7, Object.ancestors.last == Kernel but - # things blow up if we include `RSpec::Mocks::Methods` - # into Kernel...not sure why. - return Object unless defined?(::BasicObject) - - # MacRuby has BasicObject but it's not the root class. - return Object unless Object.ancestors.last == ::BasicObject - - ::BasicObject - end - end - end -end - -if defined?(BasicObject) - # The legacy `:should` syntax adds the following methods directly to - # `BasicObject` so that they are available off of any object. Note, however, - # that this syntax does not always play nice with delegate/proxy objects. - # We recommend you use the non-monkeypatching `:expect` syntax instead. - # @see Class - class BasicObject - # @method should_receive - # Sets an expectation that this object should receive a message before - # the end of the example. - # - # @example - # - # logger = double('logger') - # thing_that_logs = ThingThatLogs.new(logger) - # logger.should_receive(:log) - # thing_that_logs.do_something_that_logs_a_message - # - # @note This is only available when you have enabled the `should` syntax. - # @see RSpec::Mocks::ExampleMethods#expect - - # @method should_not_receive - # Sets and expectation that this object should _not_ receive a message - # during this example. - # @see RSpec::Mocks::ExampleMethods#expect - - # @method stub - # Tells the object to respond to the message with the specified value. - # - # @example - # - # counter.stub(:count).and_return(37) - # counter.stub(:count => 37) - # counter.stub(:count) { 37 } - # - # @note This is only available when you have enabled the `should` syntax. - # @see RSpec::Mocks::ExampleMethods#allow - - # @method unstub - # Removes a stub. On a double, the object will no longer respond to - # `message`. On a real object, the original method (if it exists) is - # restored. - # - # This is rarely used, but can be useful when a stub is set up during a - # shared `before` hook for the common case, but you want to replace it - # for a special case. - # - # @note This is only available when you have enabled the `should` syntax. - - # @method stub_chain - # @overload stub_chain(method1, method2) - # @overload stub_chain("method1.method2") - # @overload stub_chain(method1, method_to_value_hash) - # - # Stubs a chain of methods. - # - # ## Warning: - # - # Chains can be arbitrarily long, which makes it quite painless to - # violate the Law of Demeter in violent ways, so you should consider any - # use of `stub_chain` a code smell. Even though not all code smells - # indicate real problems (think fluent interfaces), `stub_chain` still - # results in brittle examples. For example, if you write - # `foo.stub_chain(:bar, :baz => 37)` in a spec and then the - # implementation calls `foo.baz.bar`, the stub will not work. - # - # @example - # - # double.stub_chain("foo.bar") { :baz } - # double.stub_chain(:foo, :bar => :baz) - # double.stub_chain(:foo, :bar) { :baz } - # - # # Given any of ^^ these three forms ^^: - # double.foo.bar # => :baz - # - # # Common use in Rails/ActiveRecord: - # Article.stub_chain("recent.published") { [Article.new] } - # - # @note This is only available when you have enabled the `should` syntax. - # @see RSpec::Mocks::ExampleMethods#receive_message_chain - - # @method as_null_object - # Tells the object to respond to all messages. If specific stub values - # are declared, they'll work as expected. If not, the receiver is - # returned. - # - # @note This is only available when you have enabled the `should` syntax. - - # @method null_object? - # Returns true if this object has received `as_null_object` - # - # @note This is only available when you have enabled the `should` syntax. - end -end - -# The legacy `:should` syntax adds the `any_instance` to `Class`. -# We generally recommend you use the newer `:expect` syntax instead, -# which allows you to stub any instance of a class using -# `allow_any_instance_of(klass)` or mock any instance using -# `expect_any_instance_of(klass)`. -# @see BasicObject -class Class - # @method any_instance - # Used to set stubs and message expectations on any instance of a given - # class. Returns a [Recorder](Recorder), which records messages like - # `stub` and `should_receive` for later playback on instances of the - # class. - # - # @example - # - # Car.any_instance.should_receive(:go) - # race = Race.new - # race.cars << Car.new - # race.go # assuming this delegates to all of its cars - # # this example would pass - # - # Account.any_instance.stub(:balance) { Money.new(:USD, 25) } - # Account.new.balance # => Money.new(:USD, 25)) - # - # @return [Recorder] - # - # @note This is only available when you have enabled the `should` syntax. - # @see RSpec::Mocks::ExampleMethods#expect_any_instance_of - # @see RSpec::Mocks::ExampleMethods#allow_any_instance_of -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/targets.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/targets.rb deleted file mode 100644 index 5579772..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/targets.rb +++ /dev/null @@ -1,97 +0,0 @@ -module RSpec - module Mocks - # @private - class TargetBase - def initialize(target) - @target = target - end - - def self.delegate_to(matcher_method) - define_method(:to) do |matcher, &block| - unless matcher_allowed?(matcher) - raise_unsupported_matcher(:to, matcher) - end - define_matcher(matcher, matcher_method, &block) - end - end - - def self.delegate_not_to(matcher_method, options = {}) - method_name = options.fetch(:from) - define_method(method_name) do |matcher, &block| - case matcher - when Matchers::Receive - define_matcher(matcher, matcher_method, &block) - when Matchers::ReceiveMessages, Matchers::ReceiveMessageChain - raise_negation_unsupported(method_name, matcher) - else - raise_unsupported_matcher(method_name, matcher) - end - end - end - - def self.disallow_negation(method_name) - define_method(method_name) do |matcher, *args| - raise_negation_unsupported(method_name, matcher) - end - end - - private - - def matcher_allowed?(matcher) - matcher.class.name.start_with?("RSpec::Mocks::Matchers".freeze) - end - - def define_matcher(matcher, name, &block) - matcher.__send__(name, @target, &block) - end - - def raise_unsupported_matcher(method_name, matcher) - raise UnsupportedMatcherError, - "only the `receive` or `receive_messages` matchers are supported " + - "with `#{expression}(...).#{method_name}`, but you have provided: #{matcher}" - end - - def raise_negation_unsupported(method_name, matcher) - raise NegationUnsupportedError, - "`#{expression}(...).#{method_name} #{matcher.name}` is not supported since it " + - "doesn't really make sense. What would it even mean?" - end - - def expression - self.class::EXPRESSION - end - end - - # @private - class AllowanceTarget < TargetBase - EXPRESSION = :allow - delegate_to :setup_allowance - disallow_negation :not_to - disallow_negation :to_not - end - - # @private - class ExpectationTarget < TargetBase - EXPRESSION = :expect - delegate_to :setup_expectation - delegate_not_to :setup_negative_expectation, :from => :not_to - delegate_not_to :setup_negative_expectation, :from => :to_not - end - - # @private - class AnyInstanceAllowanceTarget < TargetBase - EXPRESSION = :allow_any_instance_of - delegate_to :setup_any_instance_allowance - disallow_negation :not_to - disallow_negation :to_not - end - - # @private - class AnyInstanceExpectationTarget < TargetBase - EXPRESSION = :expect_any_instance_of - delegate_to :setup_any_instance_expectation - delegate_not_to :setup_any_instance_negative_expectation, :from => :not_to - delegate_not_to :setup_any_instance_negative_expectation, :from => :to_not - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/test_double.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/test_double.rb deleted file mode 100644 index 5ff3f6a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/test_double.rb +++ /dev/null @@ -1,135 +0,0 @@ -module RSpec - module Mocks - # Implements the methods needed for a pure test double. RSpec::Mocks::Double - # includes this module, and it is provided for cases where you want a - # pure test double without subclassing RSpec::Mocks::Double. - module TestDouble - # Creates a new test double with a `name` (that will be used in error - # messages only) - def initialize(name=nil, stubs={}) - @__expired = false - if Hash === name && stubs.empty? - stubs = name - @name = nil - else - @name = name - end - assign_stubs(stubs) - end - - # Tells the object to respond to all messages. If specific stub values - # are declared, they'll work as expected. If not, the receiver is - # returned. - def as_null_object - __mock_proxy.as_null_object - end - - # Returns true if this object has received `as_null_object` - def null_object? - __mock_proxy.null_object? - end - - # This allows for comparing the mock to other objects that proxy such as - # ActiveRecords belongs_to proxy objects. By making the other object run - # the comparison, we're sure the call gets delegated to the proxy - # target. - def ==(other) - other == __mock_proxy - end - - # @private - def inspect - "#<#{self.class}:#{sprintf '0x%x', self.object_id} @name=#{@name.inspect}>" - end - - # @private - def to_s - inspect.gsub('<','[').gsub('>',']') - end - - # @private - def respond_to?(message, incl_private=false) - __mock_proxy.null_object? ? true : super - end - - # @private - def __build_mock_proxy_unless_expired(order_group) - __raise_expired_error or __build_mock_proxy(order_group) - end - - # @private - def __disallow_further_usage! - @__expired = true - end - - # Override for default freeze implementation to prevent freezing of test - # doubles. - def freeze - RSpec.warn_with("WARNING: you attempted to freeze a test double. This is explicitly a no-op as freezing doubles can lead to undesired behaviour when resetting tests.") - end - - private - - def method_missing(message, *args, &block) - proxy = __mock_proxy - proxy.record_message_received(message, *args, &block) - - if proxy.null_object? - case message - when :to_int then return 0 - when :to_a, :to_ary then return nil - when :to_str then return to_s - else return self - end - end - - # Defined private and protected methods will still trigger `method_missing` - # when called publicly. We want ruby's method visibility error to get raised, - # so we simply delegate to `super` in that case. - # ...well, we would delegate to `super`, but there's a JRuby - # bug, so we raise our own visibility error instead: - # https://github.com/jruby/jruby/issues/1398 - visibility = proxy.visibility_for(message) - if visibility == :private || visibility == :protected - ErrorGenerator.new(self, @name).raise_non_public_error( - message, visibility - ) - end - - # Required wrapping doubles in an Array on Ruby 1.9.2 - raise NoMethodError if [:to_a, :to_ary].include? message - proxy.raise_unexpected_message_error(message, *args) - end - - def assign_stubs(stubs) - stubs.each_pair do |message, response| - __mock_proxy.add_simple_stub(message, response) - end - end - - def __mock_proxy - ::RSpec::Mocks.space.proxy_for(self) - end - - def __build_mock_proxy(order_group) - TestDoubleProxy.new(self, order_group, @name) - end - - def __raise_expired_error - return false unless @__expired - ErrorGenerator.new(self, @name).raise_expired_test_double_error - end - - def initialize_copy(other) - as_null_object if other.null_object? - super - end - end - - # A generic test double object. `double`, `instance_double` and friends - # return an instance of this. - class Double - include TestDouble - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_double.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_double.rb deleted file mode 100644 index ca1e1ad..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_double.rb +++ /dev/null @@ -1,129 +0,0 @@ -RSpec::Support.require_rspec_mocks 'verifying_proxy' -require 'stringio' - -module RSpec - module Mocks - - # @private - module VerifyingDouble - def respond_to?(message, include_private=false) - return super unless null_object? - - method_ref = __mock_proxy.method_reference[message] - - return case method_ref.visibility - when :public then true - when :private then include_private - when :protected then include_private || RUBY_VERSION.to_f < 2.0 - else !method_ref.unimplemented? - end - end - - def method_missing(message, *args, &block) - # Null object conditional is an optimization. If not a null object, - # validity of method expectations will have been checked at definition - # time. - if null_object? - if @__sending_message == message - __mock_proxy.ensure_implemented(message) - else - __mock_proxy.ensure_publicly_implemented(message, self) - end - end - - super - end - - # Redefining `__send__` causes ruby to issue a warning. - old, $stderr = $stderr, StringIO.new - def __send__(name, *args, &block) - @__sending_message = name - super - ensure - @__sending_message = nil - end - $stderr = old - - def send(name, *args, &block) - __send__(name, *args, &block) - end - - def initialize(*args) - super - @__sending_message = nil - end - end - - # A mock providing a custom proxy that can verify the validity of any - # method stubs or expectations against the public instance methods of the - # given class. - # - # @private - class InstanceVerifyingDouble - include TestDouble - include VerifyingDouble - - def initialize(doubled_module, *args) - @doubled_module = doubled_module - - super( - "#{doubled_module.description} (instance)", - *args - ) - end - - def __build_mock_proxy(order_group) - VerifyingProxy.new(self, order_group, @name, - @doubled_module, - InstanceMethodReference - ) - end - end - - # An awkward module necessary because we cannot otherwise have - # ClassVerifyingDouble inherit from Module and still share these methods. - # - # @private - module ObjectVerifyingDoubleMethods - include TestDouble - include VerifyingDouble - - def as_stubbed_const(options = {}) - ConstantMutator.stub(@doubled_module.const_to_replace, self, options) - self - end - - private - - def initialize(doubled_module, *args) - @doubled_module = doubled_module - super(doubled_module.description, *args) - end - - def __build_mock_proxy(order_group) - VerifyingProxy.new(self, order_group, @name, - @doubled_module, - ObjectMethodReference - ) - end - end - - # Similar to an InstanceVerifyingDouble, except that it verifies against - # public methods of the given object. - # - # @private - class ObjectVerifyingDouble - include ObjectVerifyingDoubleMethods - end - - # Effectively the same as an ObjectVerifyingDouble (since a class is a type - # of object), except with Module in the inheritance chain so that - # transferring nested constants to work. - # - # @private - class ClassVerifyingDouble < Module - include ObjectVerifyingDoubleMethods - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_message_expecation.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_message_expecation.rb deleted file mode 100644 index 93df99d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_message_expecation.rb +++ /dev/null @@ -1,60 +0,0 @@ -RSpec::Support.require_rspec_support 'method_signature_verifier' - -module RSpec - module Mocks - - # A message expectation that knows about the real implementation of the - # message being expected, so that it can verify that any expectations - # have the valid arguments. - # @api private - class VerifyingMessageExpectation < MessageExpectation - - # A level of indirection is used here rather than just passing in the - # method itself, since method look up is expensive and we only want to - # do it if actually needed. - # - # Conceptually the method reference makes more sense as a constructor - # argument since it should be immutable, but it is significantly more - # straight forward to build the object in pieces so for now it stays as - # an accessor. - attr_accessor :method_reference - - def initialize(*args) - super - end - - # @private - def with(*args, &block) - unless ArgumentMatchers::AnyArgsMatcher === args.first - expected_args = if ArgumentMatchers::NoArgsMatcher === args.first - [] - elsif args.length > 0 - args - else - # No arguments given, this will raise. - super - end - - validate_arguments!(expected_args) - end - super - end - - private - - def validate_arguments!(actual_args) - return if method_reference.nil? - - method_reference.with_signature do |signature| - verifier = Support::MethodSignatureVerifier.new(signature, actual_args) - unless verifier.valid? - # Fail fast is required, otherwise the message expecation will fail - # as well ("expected method not called") and clobber this one. - @failed_fast = true - @error_generator.raise_invalid_arguments_error(verifier) - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_proxy.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_proxy.rb deleted file mode 100644 index f4cd3ab..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/verifying_proxy.rb +++ /dev/null @@ -1,170 +0,0 @@ -RSpec::Support.require_rspec_mocks 'verifying_message_expecation' -RSpec::Support.require_rspec_mocks 'method_reference' - -module RSpec - module Mocks - - # @private - module VerifyingProxyMethods - def add_stub(method_name, opts={}, &implementation) - ensure_implemented(method_name) - super - end - - def add_simple_stub(method_name, *args) - ensure_implemented(method_name) - super - end - - def add_message_expectation(method_name, opts={}, &block) - ensure_implemented(method_name) - super - end - - def ensure_implemented(method_name) - if method_reference[method_name].unimplemented? - @error_generator.raise_unimplemented_error( - @doubled_module, - method_name - ) - end - end - - def ensure_publicly_implemented(method_name, object) - ensure_implemented(method_name) - visibility = method_reference[method_name].visibility - - unless visibility == :public - @error_generator.raise_non_public_error(method_name, visibility) - end - end - end - - # A verifying proxy mostly acts like a normal proxy, except that it - # contains extra logic to try and determine the validity of any expectation - # set on it. This includes whether or not methods have been defined and the - # validatiy of arguments on method calls. - # - # In all other ways this behaves like a normal proxy. It only adds the - # verification behaviour to specific methods then delegates to the parent - # implementation. - # - # These checks are only activated if the doubled class has already been - # loaded, otherwise they are disabled. This allows for testing in - # isolation. - # - # @private - class VerifyingProxy < TestDoubleProxy - include VerifyingProxyMethods - - def initialize(object, order_group, name, doubled_module, method_reference_class) - super(object, order_group, name) - @object = object - @doubled_module = doubled_module - @method_reference_class = method_reference_class - - # A custom method double is required to pass through a way to lookup - # methods to determine their parameters. This is only relevant if the doubled - # class is loaded. - @method_doubles = Hash.new do |h, k| - h[k] = VerifyingMethodDouble.new(@object, k, self, method_reference[k]) - end - end - - def method_reference - @method_reference ||= Hash.new do |h, k| - h[k] = @method_reference_class.new(@doubled_module, k) - end - end - - def visibility_for(method_name) - method_reference[method_name].visibility - end - end - - # @private - class VerifyingPartialDoubleProxy < PartialDoubleProxy - include VerifyingProxyMethods - - def initialize(object, expectation_ordering) - super(object, expectation_ordering) - @doubled_module = DirectObjectReference.new(object) - - # A custom method double is required to pass through a way to lookup - # methods to determine their parameters. - @method_doubles = Hash.new do |h, k| - h[k] = VerifyingExistingMethodDouble.new(object, k, self) - end - end - - def method_reference - @method_doubles - end - end - - # @private - class VerifyingPartialClassDoubleProxy < VerifyingPartialDoubleProxy - include PartialClassDoubleProxyMethods - end - - # @private - class VerifyingMethodDouble < MethodDouble - def initialize(object, method_name, proxy, method_reference) - super(object, method_name, proxy) - @method_reference = method_reference - end - - def message_expectation_class - VerifyingMessageExpectation - end - - def add_expectation(*args, &block) - # explict params necessary for 1.8.7 see #626 - super(*args, &block).tap { |x| x.method_reference = @method_reference } - end - - def proxy_method_invoked(obj, *args, &block) - validate_arguments!(args) - super - end - - private - - def validate_arguments!(actual_args) - @method_reference.with_signature do |signature| - verifier = Support::MethodSignatureVerifier.new(signature, actual_args) - unless verifier.valid? - raise ArgumentError, verifier.error_message - end - end - end - end - - # A VerifyingMethodDouble fetches the method to verify against from the - # original object, using a MethodReference. This works for pure doubles, - # but when the original object is itself the one being modified we need to - # collapse the reference and the method double into a single object so that - # we can access the original pristine method definition. - # - # @private - class VerifyingExistingMethodDouble < VerifyingMethodDouble - def initialize(object, method_name, proxy) - super(object, method_name, proxy, self) - - @valid_method = object.respond_to?(method_name, true) - - # Trigger an eager find of the original method since if we find it any - # later we end up getting a stubbed method with incorrect arity. - save_original_method! - end - - def with_signature - yield Support::MethodSignature.new(original_method) - end - - def unimplemented? - !@valid_method - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/version.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/version.rb deleted file mode 100644 index 5e0f86b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-mocks-3.0.3/lib/rspec/mocks/version.rb +++ /dev/null @@ -1,9 +0,0 @@ -module RSpec - module Mocks - # Version information for RSpec mocks. - module Version - # Version of RSpec mocks currently in use in SemVer format. - STRING = '3.0.3' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/Changelog.md b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/Changelog.md deleted file mode 100644 index eda8307..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/Changelog.md +++ /dev/null @@ -1,42 +0,0 @@ -### 3.0.3 / 2014-07-21 -[Full Changelog](http://github.com/rspec/rspec-support/compare/v3.0.2...v3.0.3) - -Bug Fixes: - -* Fix regression in `Support#method_handle_for` where proxy objects - with method delegated would wrongly not return a method handle. - (Jon Rowe, #90) -* Properly detect Module#prepend support in Ruby 2.1+ (Ben Langfeld, #91) -* Fix `rspec/support/warnings.rb` so it can be loaded and used in - isolation. (Myron Marston, #93) - -### 3.0.2 / 2014-06-20 -[Full Changelog](http://github.com/rspec/rspec-support/compare/v3.0.1...v3.0.2) - -* Revert `BlockSignature` change from 3.0.1 because of a ruby bug that - caused it to change the block's behavior (https://bugs.ruby-lang.org/issues/9967). - (Myron Marston, rspec-mocks#721) - -### 3.0.1 / 2014-06-19 -[Full Changelog](http://github.com/rspec/rspec-support/compare/v3.0.0...v3.0.1) - -* Fix `BlockSignature` so that it correctly differentiates between - required and optional block args. (Myron Marston, rspec-mocks#714) - -### 3.0.0 / 2014-06-01 -[Full Changelog](http://github.com/rspec/rspec-support/compare/v3.0.0.rc1...v3.0.0) - -### 3.0.0.rc1 / 2014-05-18 -[Full Changelog](http://github.com/rspec/rspec-support/compare/v3.0.0.beta2...v3.0.0.rc1) - -### 3.0.0.beta2 / 2014-02-17 -[Full Changelog](http://github.com/rspec/rspec-support/compare/v3.0.0.beta1...v3.0.0.beta2) - -Bug Fixes: - -* Issue message when :replacement is passed to `RSpec.warn_with`. (Jon Rowe) - -### 3.0.0.beta1 / 2013-11-07 -[Full Changelog](https://github.com/rspec/rspec-support/compare/0dc12d1bdbbacc757a9989f8c09cd08ef3a4837e...v3.0.0.beta1) - -Initial release. diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/LICENSE.txt b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/LICENSE.txt deleted file mode 100644 index ecb71df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 David Chelimsky, Myron Marston, Jon Rowe, Sam Phippen, Xavier Shay, Bradley Schaefer - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/README.md b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/README.md deleted file mode 100644 index e1e294a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# RSpec::Support - -`RSpec::Support` provides common functionality to `RSpec::Core`, -`RSpec::Expectations` and `RSpec::Mocks`. It is considered -suitable for internal use only at this time. - -## Installation / Usage - -Install one or more of the `RSpec` gems. - -## Contributing - -1. Fork it -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create new Pull Request diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support.rb deleted file mode 100644 index d45ff84..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support.rb +++ /dev/null @@ -1,76 +0,0 @@ -module RSpec - module Support - # @api private - # - # Defines a helper method that is optimized to require files from the - # named lib. The passed block MUST be `{ |f| require_relative f }` - # because for `require_relative` to work properly from within the named - # lib the line of code must be IN that lib. - # - # `require_relative` is preferred when available because it is always O(1), - # regardless of the number of dirs in $LOAD_PATH. `require`, on the other - # hand, does a linear O(N) search over the dirs in the $LOAD_PATH until - # it can resolve the file relative to one of the dirs. - def self.define_optimized_require_for_rspec(lib, &require_relative) - name = "require_rspec_#{lib}" - - if Kernel.respond_to?(:require_relative) - (class << self; self; end).__send__(:define_method, name) do |f| - require_relative.call("#{lib}/#{f}") - end - else - (class << self; self; end).__send__(:define_method, name) do |f| - require "rspec/#{lib}/#{f}" - end - end - end - - define_optimized_require_for_rspec(:support) { |f| require_relative(f) } - require_rspec_support "version" - require_rspec_support "ruby_features" - - # @api private - KERNEL_METHOD_METHOD = ::Kernel.instance_method(:method) - - # @api private - # - # Used internally to get a method handle for a particular object - # and method name. - # - # Includes handling for a few special cases: - # - # - Objects that redefine #method (e.g. an HTTPRequest struct) - # - BasicObject subclasses that mixin a Kernel dup (e.g. SimpleDelegator) - # - Objects that undefine method and delegate everything to another - # object (e.g. Mongoid association objects) - if RubyFeatures.supports_rebinding_module_methods? - def self.method_handle_for(object, method_name) - KERNEL_METHOD_METHOD.bind(object).call(method_name) - rescue NameError => original - begin - handle = object.method(method_name) - raise original unless handle.is_a? Method - handle - rescue Exception - raise original - end - end - else - def self.method_handle_for(object, method_name) - if ::Kernel === object - KERNEL_METHOD_METHOD.bind(object).call(method_name) - else - object.method(method_name) - end - rescue NameError => original - begin - handle = object.method(method_name) - raise original unless handle.is_a? Method - handle - rescue Exception - raise original - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/caller_filter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/caller_filter.rb deleted file mode 100644 index 19c2124..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/caller_filter.rb +++ /dev/null @@ -1,64 +0,0 @@ -module RSpec - # Consistent implementation for "cleaning" the caller method to strip out - # non-rspec lines. This enables errors to be reported at the call site in - # the code using the library, which is far more useful than the particular - # internal method that raised an error. - class CallerFilter - - RSPEC_LIBS = %w[ - core - mocks - expectations - support - matchers - rails - ] - - ADDITIONAL_TOP_LEVEL_FILES = %w[ autorun ] - - LIB_REGEX = %r{/lib/rspec/(#{(RSPEC_LIBS + ADDITIONAL_TOP_LEVEL_FILES).join('|')})(\.rb|/)} - - # rubygems/core_ext/kernel_require.rb isn't actually part of rspec (obviously) but we want - # it ignored when we are looking for the first meaningful line of the backtrace outside - # of RSpec. It can show up in the backtrace as the immediate first caller - # when `CallerFilter.first_non_rspec_line` is called from the top level of a required - # file, but it depends on if rubygems is loaded or not. We don't want to have to deal - # with this complexity in our `RSpec.deprecate` calls, so we ignore it here. - IGNORE_REGEX = Regexp.union(LIB_REGEX, "rubygems/core_ext/kernel_require.rb") - - if RUBY_VERSION >= '2.0.0' - def self.first_non_rspec_line - # `caller` is an expensive method that scales linearly with the size of - # the stack. The performance hit for fetching it in chunks is small, - # and since the target line is probably near the top of the stack, the - # overall improvement of a chunked search like this is significant. - # - # See benchmarks/caller.rb for measurements. - - # Initial value here is mostly arbitrary, but is chosen to give good - # performance on the common case of creating a double. - increment = 5 - i = 1 - line = nil - - while !line - stack = caller(i, increment) - raise "No non-lib lines in stack" unless stack - - line = stack.find { |l| l !~ IGNORE_REGEX } - - i += increment - increment *= 2 # The choice of two here is arbitrary. - end - - line - end - else - # Earlier rubies do not support the two argument form of `caller`. This - # fallback is logically the same, but slower. - def self.first_non_rspec_line - caller.find { |line| line !~ IGNORE_REGEX } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/differ.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/differ.rb deleted file mode 100644 index fc99f43..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/differ.rb +++ /dev/null @@ -1,205 +0,0 @@ -RSpec::Support.require_rspec_support 'encoded_string' -RSpec::Support.require_rspec_support 'hunk_generator' - -require 'pp' - -module RSpec - module Support - class Differ - def diff(actual, expected) - diff = "" - - if actual && expected - if all_strings?(actual, expected) - if any_multiline_strings?(actual, expected) - diff = diff_as_string(coerce_to_string(actual), coerce_to_string(expected)) - end - elsif no_procs?(actual, expected) && no_numbers?(actual, expected) - diff = diff_as_object(actual, expected) - end - end - - diff.to_s - end - - def diff_as_string(actual, expected) - @encoding = pick_encoding actual, expected - - @actual = EncodedString.new(actual, @encoding) - @expected = EncodedString.new(expected, @encoding) - - output = EncodedString.new("\n", @encoding) - - hunks.each_cons(2) do |prev_hunk, current_hunk| - begin - if current_hunk.overlaps?(prev_hunk) - add_old_hunk_to_hunk(current_hunk, prev_hunk) - else - add_to_output(output, prev_hunk.diff(format).to_s) - end - ensure - add_to_output(output, "\n") - end - end - - if hunks.last - finalize_output(output, hunks.last.diff(format).to_s) - end - - color_diff output - rescue Encoding::CompatibilityError - handle_encoding_errors - end - - def diff_as_object(actual, expected) - actual_as_string = object_to_string(actual) - expected_as_string = object_to_string(expected) - diff_as_string(actual_as_string, expected_as_string) - end - - attr_reader :color - alias_method :color?, :color - - def initialize(opts={}) - @color = opts.fetch(:color, false) - @object_preparer = opts.fetch(:object_preparer, lambda { |string| string }) - end - - private - - def no_procs?(*args) - args.flatten.none? { |a| Proc === a} - end - - def all_strings?(*args) - args.flatten.all? { |a| String === a} - end - - def any_multiline_strings?(*args) - all_strings?(*args) && args.flatten.any? { |a| multiline?(a) } - end - - def no_numbers?(*args) - args.flatten.none? { |a| Numeric === a} - end - - def coerce_to_string(string_or_array) - return string_or_array unless Array === string_or_array - diffably_stringify(string_or_array).join("\n") - end - - def diffably_stringify(array) - array.map do |entry| - if Array === entry - entry.inspect - else - entry.to_s.gsub("\n", "\\n") - end - end - end - - if String.method_defined?(:encoding) - def multiline?(string) - string.include?("\n".encode(string.encoding)) - end - else - def multiline?(string) - string.include?("\n") - end - end - - def hunks - @hunks ||= HunkGenerator.new(@actual, @expected).hunks - end - - def finalize_output(output, final_line) - add_to_output(output, final_line) - add_to_output(output, "\n") - end - - def add_to_output(output, string) - output << string - end - - def add_old_hunk_to_hunk(hunk, oldhunk) - hunk.merge(oldhunk) - end - - def format - :unified - end - - def color(text, color_code) - "\e[#{color_code}m#{text}\e[0m" - end - - def red(text) - color(text, 31) - end - - def green(text) - color(text, 32) - end - - def blue(text) - color(text, 34) - end - - def normal(text) - color(text, 0) - end - - def color_diff(diff) - return diff unless color? - - diff.lines.map { |line| - case line[0].chr - when "+" - green line - when "-" - red line - when "@" - line[1].chr == "@" ? blue(line) : normal(line) - else - normal(line) - end - }.join - end - - def object_to_string(object) - object = @object_preparer.call(object) - case object - when Hash - object.keys.sort_by { |k| k.to_s }.map do |key| - pp_key = PP.singleline_pp(key, "") - pp_value = PP.singleline_pp(object[key], "") - - "#{pp_key} => #{pp_value}," - end.join("\n") - when String - object =~ /\n/ ? object : object.inspect - else - PP.pp(object,"") - end - end - - if String.method_defined?(:encoding) - def pick_encoding(source_a, source_b) - Encoding.compatible?(source_a, source_b) || Encoding.default_external - end - else - def pick_encoding(source_a, source_b) - end - end - - def handle_encoding_errors - if @actual.source_encoding != @expected.source_encoding - "Could not produce a diff because the encoding of the actual string (#{@actual.source_encoding}) "+ - "differs from the encoding of the expected string (#{@expected.source_encoding})" - else - "Could not produce a diff because of the encoding of the string (#{@expected.source_encoding})" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/encoded_string.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/encoded_string.rb deleted file mode 100644 index 7254552..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/encoded_string.rb +++ /dev/null @@ -1,66 +0,0 @@ -module RSpec - module Support - # @private - class EncodedString - - MRI_UNICODE_UNKOWN_CHARACTER = "\xEF\xBF\xBD" - - def initialize(string, encoding = nil) - @encoding = encoding - @source_encoding = detect_source_encoding(string) - @string = matching_encoding(string) - end - attr_reader :source_encoding - - delegated_methods = String.instance_methods.map(&:to_s) & %w[eql? lines == encoding empty?] - delegated_methods.each do |name| - define_method(name) { |*args, &block| @string.__send__(name, *args, &block) } - end - - def <<(string) - @string << matching_encoding(string) - end - - def split(regex_or_string) - @string.split(matching_encoding(regex_or_string)) - end - - def to_s - @string - end - alias :to_str :to_s - - private - - if String.method_defined?(:encoding) - def matching_encoding(string) - string.encode(@encoding) - rescue Encoding::UndefinedConversionError, Encoding::InvalidByteSequenceError - normalize_missing(string.encode(@encoding, :invalid => :replace, :undef => :replace)) - rescue Encoding::ConverterNotFoundError - normalize_missing(string.force_encoding(@encoding).encode(:invalid => :replace)) - end - - def normalize_missing(string) - if @encoding.to_s == "UTF-8" - string.gsub(MRI_UNICODE_UNKOWN_CHARACTER.force_encoding(@encoding), "?") - else - string - end - end - - def detect_source_encoding(string) - string.encoding - end - else - def matching_encoding(string) - string - end - - def detect_source_encoding(string) - 'US-ASCII' - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/fuzzy_matcher.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/fuzzy_matcher.rb deleted file mode 100644 index 9b4dbdd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/fuzzy_matcher.rb +++ /dev/null @@ -1,47 +0,0 @@ -module RSpec - module Support - # Provides a means to fuzzy-match between two arbitrary objects. - # Understands array/hash nesting. Uses `===` or `==` to - # perform the matching. - module FuzzyMatcher - # @api private - def self.values_match?(expected, actual) - if Array === expected && Enumerable === actual - return arrays_match?(expected, actual.to_a) - elsif Hash === expected && Hash === actual - return hashes_match?(expected, actual) - end - - begin - actual == expected || expected === actual - rescue ArgumentError - # Some objects, like 0-arg lambdas on 1.9+, raise - # ArgumentError for `expected === actual`. - false - end - end - - # @private - def self.arrays_match?(expected_list, actual_list) - return false if expected_list.size != actual_list.size - - expected_list.zip(actual_list).all? do |expected, actual| - values_match?(expected, actual) - end - end - - # @private - def self.hashes_match?(expected_hash, actual_hash) - return false if expected_hash.size != actual_hash.size - - expected_hash.all? do |expected_key, expected_value| - actual_value = actual_hash.fetch(expected_key) { return false } - values_match?(expected_value, actual_value) - end - end - - private_class_method :arrays_match?, :hashes_match? - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/hunk_generator.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/hunk_generator.rb deleted file mode 100644 index 5b0d68d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/hunk_generator.rb +++ /dev/null @@ -1,48 +0,0 @@ -require 'diff/lcs' -require 'diff/lcs/hunk' - -module RSpec - module Support - # @private - class HunkGenerator - def initialize(actual, expected) - @actual = actual - @expected = expected - end - - def hunks - @file_length_difference = 0 - @hunks ||= diffs.map do |piece| - build_hunk(piece) - end - end - - private - - def diffs - Diff::LCS.diff(expected_lines, actual_lines) - end - - def expected_lines - @expected.split("\n").map! { |e| e.chomp } - end - - def actual_lines - @actual.split("\n").map! { |e| e.chomp } - end - - def build_hunk(piece) - Diff::LCS::Hunk.new( - expected_lines, actual_lines, piece, context_lines, @file_length_difference - ).tap do |h| - @file_length_difference = h.file_length_difference - end - end - - def context_lines - 3 - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/method_signature_verifier.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/method_signature_verifier.rb deleted file mode 100644 index f574a93..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/method_signature_verifier.rb +++ /dev/null @@ -1,205 +0,0 @@ -require 'rspec/support' -RSpec::Support.require_rspec_support "ruby_features" - -module RSpec - module Support - # Extracts info about the number of arguments and allowed/required - # keyword args of a given method. - # - # @private - class MethodSignature - attr_reader :min_non_kw_args, :max_non_kw_args - - def initialize(method) - @method = method - classify_parameters - end - - def non_kw_args_arity_description - case max_non_kw_args - when min_non_kw_args then min_non_kw_args.to_s - when INFINITY then "#{min_non_kw_args} or more" - else "#{min_non_kw_args} to #{max_non_kw_args}" - end - end - - if RubyFeatures.optional_and_splat_args_supported? - def description - @description ||= begin - parts = [] - - unless non_kw_args_arity_description == "0" - parts << "arity of #{non_kw_args_arity_description}" - end - - if @optional_kw_args.any? - parts << "optional keyword args (#{@optional_kw_args.map(&:inspect).join(", ")})" - end - - if @required_kw_args.any? - parts << "required keyword args (#{@required_kw_args.map(&:inspect).join(", ")})" - end - - if @allows_any_kw_args - parts << "any additional keyword args" - end - - parts.join(" and ") - end - end - - def missing_kw_args_from(given_kw_args) - @required_kw_args - given_kw_args - end - - def invalid_kw_args_from(given_kw_args) - return [] if @allows_any_kw_args - given_kw_args - @allowed_kw_args - end - - def has_kw_args_in?(args) - return false unless Hash === args.last - return false if args.count <= min_non_kw_args - - @allows_any_kw_args || @allowed_kw_args.any? - end - - def classify_parameters - optional_non_kw_args = @min_non_kw_args = 0 - @optional_kw_args, @required_kw_args = [], [] - @allows_any_kw_args = false - - @method.parameters.each do |(type, name)| - case type - # def foo(a:) - when :keyreq then @required_kw_args << name - # def foo(a: 1) - when :key then @optional_kw_args << name - # def foo(**kw_args) - when :keyrest then @allows_any_kw_args = true - # def foo(a) - when :req then @min_non_kw_args += 1 - # def foo(a = 1) - when :opt then optional_non_kw_args += 1 - # def foo(*a) - when :rest then optional_non_kw_args = INFINITY - end - end - - @max_non_kw_args = @min_non_kw_args + optional_non_kw_args - @allowed_kw_args = @required_kw_args + @optional_kw_args - end - else - def description - "arity of #{non_kw_args_arity_description}" - end - - def missing_kw_args_from(given_kw_args) - [] - end - - def invalid_kw_args_from(given_kw_args) - [] - end - - def has_kw_args_in?(args) - false - end - - def classify_parameters - arity = @method.arity - if arity < 0 - # `~` inverts the one's complement and gives us the - # number of required args - @min_non_kw_args = ~arity - @max_non_kw_args = INFINITY - else - @min_non_kw_args = arity - @max_non_kw_args = arity - end - end - end - - INFINITY = 1/0.0 - end - - # Deals with the slightly different semantics of block arguments. - # For methods, arguments are required unless a default value is provided. - # For blocks, arguments are optional, even if no default value is provided. - # - # However, we want to treat block args as required since you virtually always - # want to pass a value for each received argument and our `and_yield` has - # treated block args as required for many years. - # - # @api private - class BlockSignature < MethodSignature - if RubyFeatures.optional_and_splat_args_supported? - def classify_parameters - super - @min_non_kw_args = @max_non_kw_args unless @max_non_kw_args == INFINITY - end - end - end - - # Figures out wheter a given method can accept various arguments. - # Surprisingly non-trivial. - # - # @private - class MethodSignatureVerifier - attr_reader :non_kw_args, :kw_args - - def initialize(signature, args) - @signature = signature - @non_kw_args, @kw_args = split_args(*args) - end - - def valid? - missing_kw_args.empty? && - invalid_kw_args.empty? && - valid_non_kw_args? - end - - def error_message - if missing_kw_args.any? - "Missing required keyword arguments: %s" % [ - missing_kw_args.join(", ") - ] - elsif invalid_kw_args.any? - "Invalid keyword arguments provided: %s" % [ - invalid_kw_args.join(", ") - ] - elsif !valid_non_kw_args? - "Wrong number of arguments. Expected %s, got %s." % [ - @signature.non_kw_args_arity_description, - non_kw_args.length - ] - end - end - - private - - def valid_non_kw_args? - actual = non_kw_args.length - @signature.min_non_kw_args <= actual && actual <= @signature.max_non_kw_args - end - - def missing_kw_args - @signature.missing_kw_args_from(kw_args) - end - - def invalid_kw_args - @signature.invalid_kw_args_from(kw_args) - end - - def split_args(*args) - kw_args = if @signature.has_kw_args_in?(args) - args.pop.keys - else - [] - end - - [args, kw_args] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/ruby_features.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/ruby_features.rb deleted file mode 100644 index c46b3c9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/ruby_features.rb +++ /dev/null @@ -1,35 +0,0 @@ -module RSpec - module Support - # @api private - # - # Provides query methods for ruby features that differ among - # implementations. - module RubyFeatures - def optional_and_splat_args_supported? - Method.method_defined?(:parameters) - end - module_function :optional_and_splat_args_supported? - - def kw_args_supported? - RUBY_VERSION >= '2.0.0' && RUBY_ENGINE != 'rbx' && RUBY_ENGINE != 'jruby' - end - module_function :kw_args_supported? - - def required_kw_args_supported? - RUBY_VERSION >= '2.1.0' && RUBY_ENGINE != 'rbx' && RUBY_ENGINE != 'jruby' - end - module_function :required_kw_args_supported? - - def module_prepends_supported? - Module.method_defined?(:prepend) || Module.private_method_defined?(:prepend) - end - module_function :module_prepends_supported? - - def supports_rebinding_module_methods? - # RBX and JRuby don't yet support this. - RUBY_VERSION.to_i >= 2 && RUBY_ENGINE != 'rbx' && RUBY_ENGINE != 'jruby' - end - module_function :supports_rebinding_module_methods? - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec.rb deleted file mode 100644 index a4a14f9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec.rb +++ /dev/null @@ -1,62 +0,0 @@ -require 'rspec/support' -RSpec::Support.require_rspec_support "spec/deprecation_helpers" -RSpec::Support.require_rspec_support "spec/with_isolated_stderr" -RSpec::Support.require_rspec_support "spec/stderr_splitter" -RSpec::Support.require_rspec_support "spec/formatting_support" - -warning_preventer = $stderr = RSpec::Support::StdErrSplitter.new($stderr) - -RSpec.configure do |c| - c.include RSpecHelpers - c.include RSpec::Support::WithIsolatedStdErr - c.include RSpec::Support::FormattingSupport - - unless defined?(Debugger) # debugger causes warnings when used - c.before do - warning_preventer.reset! - end - - c.after do |example| - warning_preventer.verify_example!(example) - end - end - - if c.files_to_run.one? - c.full_backtrace = true - c.default_formatter = 'doc' - end - - c.filter_run :focus - c.run_all_when_everything_filtered = true -end - -module RSpec::Support::Spec - def self.setup_simplecov(&block) - # Simplecov emits some ruby warnings when loaded, so silence them. - old_verbose, $VERBOSE = $VERBOSE, false - - return if ENV['NO_COVERAGE'] || RUBY_VERSION < '1.9.3' || RUBY_ENGINE != 'ruby' - - # Don't load it when we're running a single isolated - # test file rather than the whole suite. - return if RSpec.configuration.files_to_run.one? - - require 'simplecov' - - SimpleCov.start do - add_filter "./bundle/" - add_filter "./tmp/" - add_filter do |source_file| - # Filter out `spec` directory except when it is under `lib` - # (as is the case in rspec-support) - source_file.filename.include?('/spec/') && !source_file.filename.include?('/lib/') - end - - instance_eval(&block) if block - end - rescue LoadError - ensure - $VERBOSE = old_verbose - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/deprecation_helpers.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/deprecation_helpers.rb deleted file mode 100644 index 93eff9d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/deprecation_helpers.rb +++ /dev/null @@ -1,61 +0,0 @@ -module RSpecHelpers - - def expect_no_deprecation - expect(RSpec.configuration.reporter).not_to receive(:deprecation) - end - - def expect_deprecation_with_call_site(file, line, snippet=//) - expect(RSpec.configuration.reporter).to receive(:deprecation) do |options| - expect(options[:call_site]).to include([file, line].join(':')) - expect(options[:deprecated]).to match(snippet) - end - end - - def expect_deprecation_without_call_site(snippet=//) - expect(RSpec.configuration.reporter).to receive(:deprecation) do |options| - expect(options[:call_site]).to eq nil - expect(options[:deprecated]).to match(snippet) - end - end - - def expect_warn_deprecation_with_call_site(file, line, snippet=//) - expect(RSpec.configuration.reporter).to receive(:deprecation) do |options| - message = options[:message] - expect(message).to match(snippet) - expect(message).to include([file, line].join(':')) - end - end - - def expect_warn_deprecation(snippet=//) - expect(RSpec.configuration.reporter).to receive(:deprecation) do |options| - message = options[:message] - expect(message).to match(snippet) - end - end - - def allow_deprecation - allow(RSpec.configuration.reporter).to receive(:deprecation) - end - - def expect_no_deprecations - expect(RSpec.configuration.reporter).not_to receive(:deprecation) - end - - def expect_warning_without_call_site(expected = //) - expect(::Kernel).to receive(:warn) do |message| - expect(message).to match expected - expect(message).to_not match(/Called from/) - end - end - - def expect_warning_with_call_site(file, line, expected = //) - expect(::Kernel).to receive(:warn) do |message| - expect(message).to match expected - expect(message).to match(/Called from #{file}:#{line}/) - end - end - - def allow_warning - allow(::Kernel).to receive(:warn) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/formatting_support.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/formatting_support.rb deleted file mode 100644 index 7e61cef..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/formatting_support.rb +++ /dev/null @@ -1,9 +0,0 @@ -module RSpec - module Support - module FormattingSupport - def dedent(string) - string.gsub(/^\s+\|/, '').chomp - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/in_sub_process.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/in_sub_process.rb deleted file mode 100644 index adb5dde..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/in_sub_process.rb +++ /dev/null @@ -1,40 +0,0 @@ -module RSpec - module Support - module InSubProcess - if Process.respond_to?(:fork) && !(RUBY_PLATFORM == 'java' && RUBY_VERSION == '1.8.7') - # Useful as a way to isolate a global change to a subprocess. - def in_sub_process - readme, writeme = IO.pipe - - pid = Process.fork do - exception = nil - begin - yield - rescue Exception => e - exception = e - end - - writeme.write Marshal.dump(exception) - - readme.close - writeme.close - exit! # prevent at_exit hooks from running (e.g. minitest) - end - - writeme.close - Process.waitpid(pid) - - exception = Marshal.load(readme.read) - readme.close - - raise exception if exception - end - else - def in_sub_process - skip "This spec requires forking to work properly, " + - "and your platform does not support forking" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/stderr_splitter.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/stderr_splitter.rb deleted file mode 100644 index dc603ae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/stderr_splitter.rb +++ /dev/null @@ -1,53 +0,0 @@ -require 'stringio' - -module RSpec - module Support - class StdErrSplitter - def initialize(original) - @orig_stderr = original - @output_tracker = ::StringIO.new - end - - respond_to_name = (::RUBY_VERSION.to_f < 1.9) ? :respond_to? : :respond_to_missing? - define_method respond_to_name do |*args| - @orig_stderr.respond_to?(*args) || super - end - - def method_missing(name, *args, &block) - @output_tracker.__send__(name, *args, &block) - @orig_stderr.__send__(name, *args, &block) - end - - def ==(other) - @orig_stderr == other - end - - # To work around JRuby error: - # TypeError: $stderr must have write method, RSpec::StdErrSplitter given - def write(line) - if line !~ %r{^\S+/gems/\S+:\d+: warning:} # http://rubular.com/r/kqeUIZOfPG - @orig_stderr.write(line) - @output_tracker.write(line) - end - end - - def has_output? - !output.empty? - end - - def reset! - @output_tracker = ::StringIO.new - end - - def verify_example!(example) - example.send(:fail,"Warnings were generated: #{output}") if has_output? - reset! - end - - def output - @output_tracker.string - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/with_isolated_stderr.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/with_isolated_stderr.rb deleted file mode 100644 index 728ea92..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/spec/with_isolated_stderr.rb +++ /dev/null @@ -1,15 +0,0 @@ -module RSpec - module Support - module WithIsolatedStdErr - - def with_isolated_stderr - original = $stderr - $stderr = StringIO.new - yield - ensure - $stderr = original - end - - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/version.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/version.rb deleted file mode 100644 index 50a143f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/version.rb +++ /dev/null @@ -1,7 +0,0 @@ -module RSpec - module Support - module Version - STRING = '3.0.3' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/version_checker.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/version_checker.rb deleted file mode 100644 index 182b549..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/version_checker.rb +++ /dev/null @@ -1,53 +0,0 @@ -module RSpec - module Support - LibraryVersionTooLowError = Class.new(StandardError) - - # @private - class VersionChecker - def initialize(library_name, library_version, min_patch_level) - @library_name, @library_version = library_name, library_version - @min_patch_level = min_patch_level - - @major, @minor, @patch = parse_version(library_version) - @min_major, @min_minor, @min_patch = parse_version(min_patch_level) - - @comparison_result = compare_version - end - - def check_version! - raise_too_low_error if too_low? - end - - private - - def too_low? - @comparison_result == :too_low - end - - def raise_too_low_error - raise LibraryVersionTooLowError, - "You are using #{@library_name} #{@library_version}. " + - "RSpec requires version #{version_requirement}." - end - - def compare_version - case - when @major < @min_major then :too_low - when @major > @min_major then :ok - when @minor < @min_minor then :too_low - when @minor > @min_minor then :ok - when @patch < @min_patch then :too_low - else :ok - end - end - - def version_requirement - ">= #{@min_patch_level}" - end - - def parse_version(version) - version.split('.').map { |v| v.to_i } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/warnings.rb b/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/warnings.rb deleted file mode 100644 index dac9a9a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/rspec-support-3.0.3/lib/rspec/support/warnings.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'rspec/support' -RSpec::Support.require_rspec_support "caller_filter" - -module RSpec - module Support - module Warnings - def deprecate(deprecated, options = {}) - warn_with "DEPRECATION: #{deprecated} is deprecated.", options - end - - # @private - # - # Used internally to print deprecation warnings - # when rspec-core isn't loaded - def warn_deprecation(message, options = {}) - warn_with "DEPRECATION: \n #{message}", options - end - - # @private - # - # Used internally to print warnings - def warning(text, options={}) - warn_with "WARNING: #{text}.", options - end - - # @private - # - # Used internally to print longer warnings - def warn_with(message, options = {}) - call_site = options.fetch(:call_site) { CallerFilter.first_non_rspec_line } - message << " Use #{options[:replacement]} instead." if options[:replacement] - message << " Called from #{call_site}." if call_site - ::Kernel.warn message - end - end - end - - extend RSpec::Support::Warnings -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/.yardopts b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/.yardopts deleted file mode 100644 index 60e00e9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/.yardopts +++ /dev/null @@ -1,5 +0,0 @@ ---readme README.md ---title 'Sinatra API Documentation' ---charset utf-8 ---markup markdown -'lib/**/*.rb' - '*.md' diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/AUTHORS b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/AUTHORS deleted file mode 100644 index 47150c8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/AUTHORS +++ /dev/null @@ -1,61 +0,0 @@ -Sinatra was designed and developed by Blake Mizerany (bmizerany) in -California. - -Sinatra would not have been possible without strong company backing. -In the past, financial and emotional support have been provided mainly by -[Heroku](http://heroku.com), [GitHub](http://github.com) and -[Engine Yard](http://www.engineyard.com/), and is now taken care of by -[Travis CI](http://travis-ci.com/). - -Special thanks to the following extraordinary individuals, who-out which -Sinatra would not be possible: - -* Ryan Tomayko (rtomayko) for constantly fixing whitespace errors 60d5006 -* Ezra Zygmuntowicz (ezmobius) for initial help and letting Blake steal - some of merbs internal code. -* Ari Lerner (http://xnot.org/) for his evangelism, spirit, and gumption - that got Sinatra recognized from Day 1. -* Christopher Schneid (cschneid) for The Book, the blog (gittr.com), - irclogger.com, and a bunch of useful patches. -* Markus Prinz (cypher) for patches over the years, caring about - the README, and hanging in there when times were rough. -* Simon Rozet (sr) for a ton of doc patches, HAML options, and all that - advocacy stuff he's going to do for 1.0. -* Erik Kastner (kastner) for fixing `MIME_TYPES` under Rack 0.5. -* Ben Bleything (bleything) for caring about HTTP status codes and doc fixes. -* Igal Koshevoy (igal) for root path detection under Thin/Passenger. -* Jon Crosby (jcrosby) for coffee breaks, doc fixes, and just because, man. -* Karel Minarik (karmi) for screaming until the website came back up. -* Jeremy Evans (jeremyevans) for unbreaking optional path params (twice!) -* The GitHub guys for stealing Blake's table. -* Nickolas Means (nmeans) for Sass template support. -* Victor Hugo Borja (vic) for splat'n routes specs and doco. -* Avdi Grimm (avdi) for basic RSpec support. -* Jack Danger Canty for a more accurate root directory and for making me - watch [this](http://www.youtube.com/watch?v=ueaHLHgskkw) just now. -* Mathew Walker for making escaped paths work with static files. -* Millions of Us for having the problem that led to Sinatra's conception. -* Songbird for the problems that helped Sinatra's future become realized. -* Rick Olson (technoweenie) for the killer plug at RailsConf '08. -* Steven Garcia for the amazing custom artwork you see on 404's and 500's -* Pat Nakajima (nakajima) for fixing non-nested params in nested params Hash's. -* Konstantin Haase for his hard work and ongoing commitment to improving - Sinatra, for 1.1.0, 1.2.0 and beyond.. -* Zachary Scott for adding Konstantin to the AUTHORS file. He also did help - writing the book, but mainly for adding Konstantin. -* Gabriel Andretta for having people wonder whether our documentation is - actually in English or in Spanish. -* Vasily Polovnyov, Nickolay Schwarz, Luciano Sousa, Wu Jiang, Mickael Riga, - Bernhard Essl, Janos Hardi, Kouhei Yanagita and "burningTyger" for willingly - translating whatever ends up in the README. -* [Wordy](http://www.wordy.com/) for proofreading our README. 73e137d -* cactus for digging through code and specs, multiple times. -* Nicolás Sanguinetti (foca) for strong demand of karma and shaping - helpers/register. - -and last but not least: - -* Frank Sinatra (chairman of the board) for having so much class he - deserves a web-framework named after him. - -For a complete list of all contributors to Sinatra itself, run `rake authors`. diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/CHANGES b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/CHANGES deleted file mode 100644 index bb0160f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/CHANGES +++ /dev/null @@ -1,1293 +0,0 @@ -= 1.4.5 / 2014-04-08 - - * Improve tests and documentation. (Seiichi Yonezawa, Mike Gehard, Andrew - Deitrick, Matthew Nicholas Bradley, GoGo tanaka, Carlos Lazo, Shim Tw, - kyoendo, Roman Kuznietsov, Stanislav Chistenko, Ryunosuke SATO, Ben Lewis, - wuleicanada, Patricio Mac Adden, Thais Camilo) - - * Fix Ruby warnings. (Vipul A M, Piotr Szotkowski) - - * Fix template cache memory leak. (Scott Holden) - - * Work around UTF-8 bug in JRuby. (namusyaka) - - * Don't set charset for JSON mime-type (Sebastian Borrazas) - - * Fix bug in request.accept? that might trigger a NoMethodError. (sbonami) - -= 1.4.4 / 2013-10-21 - - * Allow setting layout to false specifically for a single rendering engine. - (Matt Wildig) - - * Allow using wildcard in argument passed to `request.accept?`. (wilkie) - - * Treat missing Accept header like wild card. (Patricio Mac Adden) - - * Improve tests and documentation. (Darío Javier Cravero, Armen P., michelc, - Patricio Mac Adden, Matt Wildig, Vipul A M, utenmiki, George Timoschenko, - Diogo Scudelletti) - - * Fix Ruby warnings. (Vipul A M, Patricio Mac Adden) - - * Improve self-hosted server started by `run!` method or in classic mode. - (Tobias Bühlmann) - - * Reduce objects allocated per request. (Vipul A M) - - * Drop unused, undocumented options hash from Sinatra.new. (George Timoschenko) - - * Keep Content-Length header when response is a `Rack::File` or when streaming. - (Patricio Mac Adden, George Timoschenko) - - * Use reel if it's the only server available besides webrick. (Tobias Bühlmann) - - * Add `disable :traps` so setting up signal traps for self hosted server can be - skipped. (George Timoschenko) - - * The `status` option passed to `send_file` may now be a string. (George - Timoschenko) - - * Reduce file size of dev mode images for 404 and 500 pages. (Francis Go) - -= 1.4.3 / 2013-06-07 - - * Running a Sinatra file directly or via `run!` it will now ignore an - empty $PORT env variable. (noxqsgit) - - * Improve documentation. (burningTyger, Patricio Mac Adden, - Konstantin Haase, Diogo Scudelletti, Dominic Imhof) - - * Expose matched pattern as env["sinatra.route"]. (Aman Gupta) - - * Fix warning on Ruby 2.0. (Craig Little) - - * Improve running subset of tests in isolation. (Viliam Pucik) - - * Reorder private/public methods. (Patricio Mac Adden) - - * Loosen version dependency for rack, so it runs with Rails 3.2. - (Konstantin Haase) - - * Request#accept? now returns true instead of a truthy value. (Alan Harris) - -= 1.4.2 / 2013-03-21 - - * Fix parsing error for case where both the pattern and the captured part - contain a dot. (Florian Hanke, Konstantin Haase) - - * Missing Accept header is treated like */*. (Greg Denton) - - * Improve documentation. (Patricio Mac Adden, Joe Bottigliero) - -= 1.4.1 / 2013-03-15 - - * Make delegated methods available in config.ru (Konstantin Haase) - -= 1.4.0 / 2013-03-15 - - * Add support for LINK and UNLINK requests. (Konstantin Haase) - - * Add support for Yajl templates. (Jamie Hodge) - - * Add support for Rabl templates. (Jesse Cooke) - - * Add support for Wlang templates. (Bernard Lambeau) - - * Add support for Stylus templates. (Juan David Pastas, Konstantin Haase) - - * You can now pass a block to ERb, Haml, Slim, Liquid and Wlang templates, - which will be used when calling `yield` in the template. (Alexey Muranov) - - * When running in classic mode, no longer include Sinatra::Delegator in Object, - instead extend the main object only. (Konstantin Haase) - - * Improved route parsing: "/:name.?:format?" with "/foo.png" now matches to - {name: "foo", format: "png"} instead of {name: "foo.png"}. (Florian Hanke) - - * Add :status option support to send_file. (Konstantin Haase) - - * The `provides` condition now respects an earlier set content type. - (Konstantin Haase) - - * Exception#code is only used when :use_code is enabled. Moreover, it will - be ignored if the value is not between 400 and 599. You should use - Exception#http_status instead. (Konstantin Haase) - - * Status, headers and body will be set correctly in an after filter when using - halt in a before filter or route. (Konstantin Haase) - - * Sinatra::Base.new now returns a Sinatra::Wrapper instance, exposing - #settings and #helpers, yet going through the middleware stack on #call. - It also implements a nice #inspect, so it plays nice with Rails' `rake - routes`. (Konstantin Haase) - - * In addition to WebRick, Thin and Mongrel, Sinatra will now automatically pick - up Puma, Trinidad, ControlTower or Net::HTTP::Server when installed. The - logic for picking the server has been improved and now depends on the Ruby - implementation used. (Mark Rada, Konstantin Haase, Patricio Mac Adden) - - * "Sinatra doesn't know this ditty" pages now show the app class when running - a modular application. This helps detecting where the response came from when - combining multiple modular apps. (Konstantin Haase) - - * When port is not set explicitly, use $PORT env variable if set and only - default to 4567 if not. Plays nice with foreman. (Konstantin Haase) - - * Allow setting layout on a per engine basis. (Zachary Scott, Konstantin Haase) - - * You can now use `register` directly in a classic app. (Konstantin Haase) - - * `redirect` now accepts URI or Addressable::URI instances. (Nicolas - Sanguinetti) - - * Have Content-Disposition header also include file name for `inline`, not - just for `attachment`. (Konstantin Haase) - - * Better compatibility to Rack 1.5. (James Tucker, Konstantin Haase) - - * Make route parsing regex more robust. (Zoltan Dezso, Konstantin Haase) - - * Improve Accept header parsing, expose parameters. (Pieter van de Bruggen, - Konstantin Haase) - - * Add `layout_options` render option. Allows you, amongst other things, to - render a layout from a different folder. (Konstantin Haase) - - * Explicitly setting `layout` to `nil` is treated like setting it to `false`. - (richo) - - * Properly escape attributes in Content-Type header. (Pieter van de Bruggen) - - * Default to only serving localhost in development mode. (Postmodern) - - * Setting status code to 404 in error handler no longer triggers not_found - handler. (Konstantin Haase) - - * The `protection` option now takes a `session` key for force - disabling/enabling session based protections. (Konstantin Haase) - - * Add `x_cascade` option to disable `X-Cascade` header on missing route. - (Konstantin Haase) - - * Improve documentation. (Kashyap, Stanislav Chistenko, Zachary Scott, - Anthony Accomazzo, Peter Suschlik, Rachel Mehl, ymmtmsys, Anurag Priyam, - burningTyger, Tony Miller, akicho8, Vasily Polovnyov, Markus Prinz, - Alexey Muranov, Erik Johnson, Vipul A M, Konstantin Haase) - - * Convert documentation to Markdown. (Kashyap, Robin Dupret, burningTyger, - Vasily Polovnyov, Iain Barnett, Giuseppe Capizzi, Neil West) - - * Don't set not_found content type to HTML in development mode with custom - not_found handler. (Konstantin Haase) - - * Fix mixed indentation for private methods. (Robin Dupret) - - * Recalculate Content-Length even if hard coded if body is reset. Relevant - mostly for error handlers. (Nathan Esquenazi, Konstantin Haase) - - * Plus sign is once again kept as such when used for URL matches. (Konstantin - Haase) - - * Take views option into account for template caching. (Konstantin Haase) - - * Consistent use of `headers` instead of `header` internally. (Patricio Mac Adden) - - * Fix compatibility to RDoc 4. (Bohuslav Kabrda) - - * Make chat example work with latest jQuery. (loveky, Tony Miller) - - * Make tests run without warnings. (Patricio Mac Adden) - - * Make sure value returned by `mime_type` is a String or nil, even when a - different object is passed in, like an AcceptEntry. (Konstantin Haase) - - * Exceptions in `after` filter are now handled like any other exception. - (Nathan Esquenazi) - -= 1.3.6 (backport release) / 2013-03-15 - -Backported from 1.4.0: - - * Take views option into account for template caching. (Konstantin Haase) - - * Improve documentation (Konstantin Haase) - - * No longer override `define_singleton_method`. (Konstantin Haase) - -= 1.3.5 / 2013-02-25 - - * Fix for RubyGems 2.0 (Uchio KONDO) - - * Improve documentation (Konstantin Haase) - - * No longer override `define_singleton_method`. (Konstantin Haase) - -= 1.3.4 / 2013-01-26 - - * Improve documentation. (Kashyap, Stanislav Chistenko, Konstantin Haase, - ymmtmsys, Anurag Priyam) - - * Adjustments to template system to work with Tilt edge. (Konstantin Haase) - - * Fix streaming with latest Rack release. (Konstantin Haase) - - * Fix default content type for Sinatra::Response with latest Rack release. - (Konstantin Haase) - - * Fix regression where + was no longer treated like space. (Ross Boucher) - - * Status, headers and body will be set correctly in an after filter when using - halt in a before filter or route. (Konstantin Haase) - -= 1.3.3 / 2012-08-19 - - * Improved documentation. (burningTyger, Konstantin Haase, Gabriel Andretta, - Anurag Priyam, michelc) - - * No longer modify the load path. (Konstantin Haase) - - * When keeping a stream open, set up callback/errback correctly to deal with - clients closing the connection. (Konstantin Haase) - - * Fix bug where having a query param and a URL param by the same name would - concatenate the two values. (Konstantin Haase) - - * Prevent duplicated log output when application is already wrapped in a - `Rack::CommonLogger`. (Konstantin Haase) - - * Fix issue where `Rack::Link` and Rails were preventing indefinite streaming. - (Konstantin Haase) - - * No longer cause warnings when running Ruby with `-w`. (Konstantin Haase) - - * HEAD requests on static files no longer report a Content-Length of 0, but - instead the proper length. (Konstantin Haase) - - * When protecting against CSRF attacks, drop the session instead of refusing - the request. (Konstantin Haase) - -= 1.3.2 / 2011-12-30 - - * Don't automatically add `Rack::CommonLogger` if `Rack::Server` is adding it, - too. (Konstantin Haase) - - * Setting `logging` to `nil` will avoid setting up `Rack::NullLogger`. - (Konstantin Haase) - - * Route specific params are now available in the block passed to #stream. - (Konstantin Haase) - - * Fix bug where rendering a second template in the same request, after the - first one raised an exception, skipped the default layout. (Nathan Baum) - - * Fix bug where parameter escaping got enabled when disabling a different - protection. (Konstantin Haase) - - * Fix regression: Filters without a pattern may now again manipulate the params - hash. (Konstantin Haase) - - * Added examples directory. (Konstantin Haase) - - * Improved documentation. (Gabriel Andretta, Markus Prinz, Erick Zetta, Just - Lest, Adam Vaughan, Aleksander Dąbrowski) - - * Improved MagLev support. (Tim Felgentreff) - -= 1.3.1 / 2011-10-05 - - * Support adding more than one callback to the stream object. (Konstantin - Haase) - - * Fix for infinite loop when streaming on 1.9.2 with Thin from a modular - application (Konstantin Haase) - -= 1.3.0 / 2011-09-30 - - * Added `stream` helper method for easily creating streaming APIs, Server - Sent Events or even WebSockets. See README for more on that topic. - (Konstantin Haase) - - * If a HTTP 1.1 client is redirected from a different verb than GET, use 303 - instead of 302 by default. You may still pass 302 explicitly. Fixes AJAX - redirects in Internet Explorer 9 (to be fair, everyone else is doing it - wrong and IE is behaving correct). (Konstantin Haase) - - * Added support for HTTP PATCH requests. (Konstantin Haase) - - * Use rack-protection to defend against common opportunistic attacks. - (Josh Lane, Jacob Burkhart, Konstantin Haase) - - * Support for Creole templates, Creole is a standardized wiki markup, - supported by many wiki implementations. (Konstanin Haase) - - * The `erubis` method has been deprecated. If Erubis is available, Sinatra - will automatically use it for rendering ERB templates. `require 'erb'` - explicitly to prevent that behavior. (Magnus Holm, Ryan Tomayko, Konstantin - Haase) - - * Patterns now match against the escaped URLs rather than the unescaped - version. This makes Sinatra confirm with RFC 2396 section 2.2 and RFC 2616 - section 3.2.3 (escaped reserved characters should not be treated like the - unescaped version), meaning that "/:name" will also match `/foo%2Fbar`, but - not `/foo/bar`. To avoid incompatibility, pattern matching has been - adjusted. Moreover, since we do no longer need to keep an unescaped version - of path_info around, we handle all changes to `env['PATH_INFO']` correctly. - (Konstantin Haase) - - * `settings.app_file` now defaults to the file subclassing `Sinatra::Base` in - modular applications. (Konstantin Haase) - - * Set up `Rack::Logger` or `Rack::NullLogger` depending on whether logging - was enabled or not. Also, expose that logger with the `logger` helper - method. (Konstantin Haase) - - * The sessions setting may be an options hash now. (Konstantin Haase) - - * Important: Ruby 1.8.6 support has been dropped. This version also depends - on at least Rack 1.3.0. This means that it is incompatible with Rails prior - to 3.1.0. Please use 1.2.x if you require an earlier version of Ruby or - Rack, which we will continue to supply with bug fixes. (Konstantin Haase) - - * Renamed `:public` to `:public_folder` to avoid overriding Ruby's built-in - `public` method/keyword. `set(:public, ...)` is still possible but shows a - warning. (Konstantin Haase) - - * It is now possible to use a different target class for the top level DSL - (aka classic style) than `Sinatra::Application` by setting - `Delegator.target`. This was mainly introduced to ease testing. (Konstantin - Haase) - - * Error handlers defined for an error class will now also handle subclasses - of that class, unless more specific error handlers exist. (Konstantin - Haase) - - * Error handling respects Exception#code, again. (Konstantin Haase) - - * Changing a setting will merge hashes: `set(:x, :a => 1); set(:x :b => 2)` - will result in `{:a => 1, :b => 2}`. Use `set(:x, {:a => 1}, true)` to - avoid this behavior. (Konstantin Haase) - - * Added `request.accept?` and `request.preferred_type` to ease dealing with - `Accept` headers. (Konstantin Haase) - - * Added `:static_cache_control` setting to automatically set cache control - headers to static files. (Kenichi Nakamura) - - * Added `informal?`, `success?`, `redirect?`, `client_error?`, - `server_error?` and `not_found?` helper methods to ease dealing with status - codes. (Konstantin Haase) - - * Uses SecureRandom to generate default session secret. (Konstantin Haase) - - * The `attachment` helper will set Content-Type (if it hasn't been set yet) - depending on the supplied file name. (Vasiliy Ermolovich) - - * Conditional requests on `etag` helper now work properly for unsafe HTTP - methods. (Matthew Schinckel, Konstantin Haase) - - * The `last_modified` helper does not stop execution and change the status code - if the status code is something different than 200. (Konstantin Haase) - - * Added support for If-Unmodified-Since header. (Konstantin Haase) - - * `Sinatra::Base.run!` now prints to stderr rather than stdout. (Andrew - Armenia) - - * `Sinatra::Base.run!` takes a block allowing access to the Rack handler. - (David Waite) - - * Automatic `app_file` detection now works in directories containing brackets - (Konstantin Haase) - - * Exception objects are now passed to error handlers. (Konstantin Haase) - - * Improved documentation. (Emanuele Vicentini, Peter Higgins, Takanori - Ishikawa, Konstantin Haase) - - * Also specify charset in Content-Type header for JSON. (Konstantin Haase) - - * Rack handler names will not be converted to lower case internally, this - allows you to run Sinatra with custom Rack handlers, like Kirk or Mongrel2. - Example: `ruby app.rb -s Mongrel2` (Konstantin Haase) - - * Ignore `to_ary` on response bodies. Fixes compatibility to Rails 3.1. - (Konstantin Haase) - - * Middleware setup is now distributed across multiple methods, allowing - Sinatra extensions to easily hook into the setup process. (Konstantin - Haase) - - * Internal refactoring and minor performance improvements. (Konstantin Haase) - - * Move Sinatra::VERSION to separate file, so it can be checked without - loading Sinatra. (Konstantin Haase) - - * Command line options now complain if value passed to `-p` is not a valid - integer. (Konstantin Haase) - - * Fix handling of broken query params when displaying exceptions. (Luke - Jahnke) - -= 1.2.9 (backports release) / 2013-03-15 - -IMPORTANT: THIS IS THE LAST 1.2.x RELEASE, PLEASE UPGRADE. - - * Display EOL warning when loading Sinatra. (Konstantin Haase) - - * Improve documentation. (Anurag Priyam, Konstantin Haase) - - * Do not modify the load path. (Konstantin Haase) - - * Display deprecation warning if RUBY_IGNORE_CALLERS is used. (Konstantin Haase) - - * Add backports library so we can still run on Ruby 1.8.6. (Konstantin Haase) - -= 1.2.8 (backports release) / 2011-12-30 - -Backported from 1.3.2: - -* Fix bug where rendering a second template in the same request after the - first one raised an exception skipped the default layout (Nathan Baum) - -= 1.2.7 (backports release) / 2011-09-30 - -Custom changes: - - * Fix Ruby 1.8.6 issue with Accept header parsing. (Konstantin Haase) - -Backported from 1.3.0: - - * Ignore `to_ary` on response bodies. Fixes compatibility to Rails 3.1. - (Konstantin Haase) - - * `Sinatra.run!` now prints to stderr rather than stdout. (Andrew Armenia) - - * Automatic `app_file` detection now works in directories containing brackets - (Konstantin Haase) - - * Improved documentation. (Emanuele Vicentini, Peter Higgins, Takanori - Ishikawa, Konstantin Haase) - - * Also specify charset in Content-Type header for JSON. (Konstantin Haase) - - * Rack handler names will not be converted to lower case internally, this - allows you to run Sinatra with custom Rack handlers, like Kirk or Mongrel2. - Example: `ruby app.rb -s Mongrel2` (Konstantin Haase) - - * Fix uninitialized instance variable warning. (David Kellum) - - * Command line options now complain if value passed to `-p` is not a valid - integer. (Konstantin Haase) - - * Fix handling of broken query params when displaying exceptions. (Luke - Jahnke) - -= 1.2.6 / 2011-05-01 - - * Fix broken delegation, backport delegation tests from Sinatra 1.3. - (Konstantin Haase) - -= 1.2.5 / 2011-04-30 - - * Restore compatibility with Ruby 1.8.6. (Konstantin Haase) - -= 1.2.4 / 2011-04-30 - - * Sinatra::Application (classic style) does not use a session secret in - development mode, so sessions are not invalidated after every request when - using Shotgun. (Konstantin Haase) - - * The request object was shared between multiple Sinatra instances in the - same middleware chain. This caused issues if any non-sinatra routing - happend in-between two of those instances, or running a request twice - against an application (described in the README). The caching was reverted. - See GH#239 and GH#256 for more infos. (Konstantin Haase) - - * Fixes issues where the top level DSL was interfering with method_missing - proxies. This issue surfaced when Rails 3 was used with older Sass versions - and Sinatra >= 1.2.0. (Konstantin Haase) - - * Sinatra::Delegator.delegate is now able to delegate any method names, even - those containing special characters. This allows better integration into - other programming languages on Rubinius (probably on the JVM, too), like - Fancy. (Konstantin Haase) - - * Remove HEAD request logic and let Rack::Head handle it instead. (Paolo - "Nusco" Perrotta) - -= 1.2.3 / 2011-04-13 - - * This release is compatible with Tilt 1.3, it will still work with Tilt 1.2.2, - however, if you want to use a newer Tilt version, you have to upgrade to at - least this version of Sinatra. (Konstantin Haase) - - * Helpers dealing with time, like `expires`, handle objects that pretend to be - numbers, like `ActiveSupport::Duration`, better. (Konstantin Haase) - -= 1.2.2 / 2011-04-08 - - * The `:provides => :js` condition now matches both `application/javascript` - and `text/javascript`. The `:provides => :xml` condition now matches both - `application/xml` and `text/xml`. The `Content-Type` header is set - accordingly. If the client accepts both, the `application/*` version is - preferred, since the `text/*` versions are deprecated. (Konstantin Haase) - - * The `provides` condition now handles wildcards in `Accept` headers correctly. - Thus `:provides => :html` matches `text/html`, `text/*` and `*/*`. - (Konstantin Haase) - - * When parsing `Accept` headers, `Content-Type` preferences are honored - according to RFC 2616 section 14.1. (Konstantin Haase) - - * URIs passed to the `url` helper or `redirect` may now use any schema to be - identified as absolute URIs, not only `http` or `https`. (Konstantin Haase) - - * Handles `Content-Type` strings that already contain parameters correctly in - `content_type` (example: `content_type "text/plain; charset=utf-16"`). - (Konstantin Haase) - - * If a route with an empty pattern is defined (`get("") { ... }`) requests with - an empty path info match this route instead of "/". (Konstantin Haase) - - * In development environment, when running under a nested path, the image URIs - on the error pages are set properly. (Konstantin Haase) - -= 1.2.1 / 2011-03-17 - - * Use a generated session secret when using `enable :sessions`. (Konstantin - Haase) - - * Fixed a bug where the wrong content type was used if no content type was set - and a template engine was used with a different engine for the layout with - different default content types, say Less embedded in Slim. (Konstantin - Haase) - - * README translations improved (Gabriel Andretta, burningTyger, Sylvain Desvé, - Gregor Schmidt) - -= 1.2.0 / 2011-03-03 - - * Added `slim` rendering method for rendering Slim templates. (Steve - Hodgkiss) - - * The `markaby` rendering method now allows passing a block, making inline - usage possible. Requires Tilt 1.2 or newer. (Konstantin Haase) - - * All render methods now take a `:layout_engine` option, allowing to use a - layout in a different template language. Even more useful than using this - directly (`erb :index, :layout_engine => :haml`) is setting this globally for - a template engine that otherwise does not support layouts, like Markdown or - Textile (`set :markdown, :layout_engine => :erb`). (Konstantin Haase) - - * Before and after filters now support conditions, both with and without - patterns (`before '/api/*', :agent => /Songbird/`). (Konstantin Haase) - - * Added a `url` helper method which constructs absolute URLs. Copes with - reverse proxies and Rack handlers correctly. Aliased to `to`, so you can - write `redirect to('/foo')`. (Konstantin Haase) - - * If running on 1.9, patterns for routes and filters now support named - captures: `get(%r{/hi/(?[^/?#]+)}) { "Hi #{params['name']}" }`. - (Steve Price) - - * All rendering methods now take a `:scope` option, which renders them in - another context. Note that helpers and instance variables will be - unavailable if you use this feature. (Paul Walker) - - * The behavior of `redirect` can now be configured with `absolute_redirects` - and `prefixed_redirects`. (Konstantin Haase) - - * `send_file` now allows overriding the Last-Modified header, which defaults - to the file's mtime, by passing a `:last_modified` option. (Konstantin Haase) - - * You can use your own template lookup method by defining `find_template`. - This allows, among other things, using more than one views folder. - (Konstantin Haase) - - * Largely improved documentation. (burningTyger, Vasily Polovnyov, Gabriel - Andretta, Konstantin Haase) - - * Improved error handling. (cactus, Konstantin Haase) - - * Skip missing template engines in tests correctly. (cactus) - - * Sinatra now ships with a Gemfile for development dependencies, since it eases - supporting different platforms, like JRuby. (Konstantin Haase) - -= 1.1.4 (backports release) / 2011-04-13 - - * Compatible with Tilt 1.3. (Konstantin Haase) - -= 1.1.3 / 2011-02-20 - - * Fixed issues with `user_agent` condition if the user agent header is missing. - (Konstantin Haase) - - * Fix some routing tests that have been skipped by accident (Ross A. Baker) - - * Fix rendering issues with Builder and Nokogiri (Konstantin Haase) - - * Replace last_modified helper with better implementation. (cactus, - Konstantin Haase) - - * Fix issue with charset not being set when using `provides` condition. - (Konstantin Haase) - - * Fix issue with `render` not picking up all alternative file extensions for - a rendering engine - it was not possible to register ".html.erb" without - tricks. (Konstantin Haase) - -= 1.1.2 / 2010-10-25 - -Like 1.1.1, but with proper CHANGES file. - -= 1.1.1 / 2010-10-25 - - * README has been translated to Russian (Nickolay Schwarz, Vasily Polovnyov) - and Portuguese (Luciano Sousa). - - * Nested templates without a `:layout` option can now be used from the layout - template without causing an infinite loop. (Konstantin Haase) - - * Inline templates are now encoding aware and can therefore be used with - unicode characters on Ruby 1.9. Magic comments at the beginning of the file - will be honored. (Konstantin Haase) - - * Default `app_file` is set correctly when running with bundler. Using - bundler caused Sinatra not to find the `app_file` and therefore not to find - the `views` folder on it's own. (Konstantin Haase) - - * Better handling of Content-Type when using `send_file`: If file extension - is unknown, fall back to `application/octet-stream` and do not override - content type if it has already been set, except if `:type` is passed - explicitly (Konstantin Haase) - - * Path is no longer cached if changed between handlers that do pattern - matching. This means you can change `request.path_info` in a pattern - matching before filter. (Konstantin Haase) - - * Headers set by cache_control now always set max_age as an Integer, making - sure it is compatible with RFC2616. (Konstantin Haase) - - * Further improved handling of string encodings on Ruby 1.9, templates now - honor default_encoding and URLs support unicode characters. (Konstantin - Haase) - -= 1.1.0 / 2010-10-24 - - * Before and after filters now support pattern matching, including the - ability to use captures: "before('/user/:name') { |name| ... }". This - avoids manual path checking. No performance loss if patterns are avoided. - (Konstantin Haase) - - * It is now possible to render SCSS files with the `scss` method, which - behaves exactly like `sass` except for the different file extension and - assuming the SCSS syntax. (Pedro Menezes, Konstantin Haase) - - * Added `liquid`, `markdown`, `nokogiri`, `textile`, `rdoc`, `radius`, - `markaby`, and `coffee` rendering methods for rendering Liquid, Markdown, - Nokogiri, Textile, RDoc, Radius, Markaby and CoffeeScript templates. - (Konstantin Haase) - - * Now supports byte-range requests (the HTTP_RANGE header) for static files. - Multi-range requests are not supported, however. (Jens Alfke) - - * You can now use #settings method from class and top level for convenience. - (Konstantin Haase) - - * Setting multiple values now no longer relies on #to_hash and therefore - accepts any Enumerable as parameter. (Simon Rozet) - - * Nested templates default the `layout` option to `false` rather than `true`. - This eases the use of partials. If you wanted to render one haml template - embedded in another, you had to call `haml :partial, {}, :layout => false`. - As you almost never want the partial to be wrapped in the standard layout - in this situation, you now only have to call `haml :partial`. Passing in - `layout` explicitly is still possible. (Konstantin Haase) - - * If a the return value of one of the render functions is used as a response - body and the content type has not been set explicitly, Sinatra chooses a - content type corresponding to the rendering engine rather than just using - "text/html". (Konstantin Haase) - - * README is now available in Chinese (Wu Jiang), French (Mickael Riga), - German (Bernhard Essl, Konstantin Haase, burningTyger), Hungarian (Janos - Hardi) and Spanish (Gabriel Andretta). The extremely outdated Japanese - README has been updated (Kouhei Yanagita). - - * It is now possible to access Sinatra's template_cache from the outside. - (Nick Sutterer) - - * The `last_modified` method now also accepts DateTime instances and makes - sure the header will always be set to a string. (Konstantin Haase) - - * 599 now is a legal status code. (Steve Shreeve) - - * This release is compatible with Ruby 1.9.2. Sinatra was trying to read - non existent files Ruby added to the call stack. (Shota Fukumori, - Konstantin Haase) - - * Prevents a memory leak on 1.8.6 in production mode. Note, however, that - this is due to a bug in 1.8.6 and request will have the additional overhead - of parsing templates again on that version. It is recommended to use at - least Ruby 1.8.7. (Konstantin Haase) - - * Compares last modified date correctly. `last_modified` was halting only - when the 'If-Modified-Since' header date was equal to the time specified. - Now, it halts when is equal or later than the time specified (Gabriel - Andretta). - - * Sinatra is now usable in combination with Rails 3. When mounting a Sinatra - application under a subpath in Rails 3, the PATH_INFO is not prefixed with - a slash and no routes did match. (José Valim) - - * Better handling of encodings in 1.9, defaults params encoding to UTF-8. - (Konstantin Haase) - - * `show_exceptions` handling is now triggered after custom error handlers, if - it is set to `:after_handlers`, thus not disabling those handler in - development mode. (pangel, Konstantin Haase) - - * Added ability to handle weighted HTTP_ACCEPT headers. (Davide D'Agostino) - - * `send_file` now always respects the `:type` option if set. Previously it - was discarded if no matching mime type was found, which made it impossible - to directly pass a mime type. (Konstantin Haase) - - * `redirect` always redirects to an absolute URI, even if a relative URI was - passed. Ensures compatibility with RFC 2616 section 14.30. (Jean-Philippe - Garcia Ballester, Anthony Williams) - - * Broken examples for using Erubis, Haml and Test::Unit in README have been - fixed. (Nick Sutterer, Doug Ireton, Jason Stewart, Eric Marden) - - * Sinatra now handles SIGTERM correctly. (Patrick Collison) - - * Fixes an issue with inline templates in modular applications that manually - call `run!`. (Konstantin Haase) - - * Spaces after inline template names are now ignored (Konstantin Haase) - - * It's now possible to use Sinatra with different package management - systems defining a custom require. (Konstantin Haase) - - * Lighthouse has been dropped in favor of GitHub issues. - - * Tilt is now a dependency and therefore no longer ships bundled with - Sinatra. (Ryan Tomayko, Konstantin Haase) - - * Sinatra now depends on Rack 1.1 or higher. Rack 1.0 is no longer supported. - (Konstantin Haase) - -= 1.0 / 2010-03-23 - - * It's now possible to register blocks to run after each request using - after filters. After filters run at the end of each request, after - routes and error handlers. (Jimmy Schementi) - - * Sinatra now uses Tilt for rendering - templates. This adds support for template caching, consistent - template backtraces, and support for new template engines, like - mustache and liquid. (Ryan Tomayko) - - * ERB, Erubis, and Haml templates are now compiled the first time - they're rendered instead of being string eval'd on each invocation. - Benchmarks show a 5x-10x improvement in render time. This also - reduces the number of objects created, decreasing pressure on Ruby's - GC. (Ryan Tomayko) - - * New 'settings' method gives access to options in both class and request - scopes. This replaces the 'options' method. (Chris Wanstrath) - - * New boolean 'reload_templates' setting controls whether template files - are reread from disk and recompiled on each request. Template read/compile - is cached by default in all environments except development. (Ryan Tomayko) - - * New 'erubis' helper method for rendering ERB template with Erubis. The - erubis gem is required. (Dylan Egan) - - * New 'cache_control' helper method provides a convenient way of - setting the Cache-Control response header. Takes a variable number - of boolean directives followed by a hash of value directives, like - this: cache_control :public, :must_revalidate, :max_age => 60 - (Ryan Tomayko) - - * New 'expires' helper method is like cache_control but takes an - integer number of seconds or Time object: - expires 300, :public, :must_revalidate - (Ryan Tomayko) - - * New request.secure? method for checking for an SSL connection. - (Adam Wiggins) - - * Sinatra apps can now be run with a `-o ` argument to specify - the address to bind to. (Ryan Tomayko) - - * Rack::Session::Cookie is now added to the middleware pipeline when - running in test environments if the :sessions option is set. - (Simon Rozet) - - * Route handlers, before filters, templates, error mappings, and - middleware are now resolved dynamically up the inheritance hierarchy - when needed instead of duplicating the superclass's version when - a new Sinatra::Base subclass is created. This should fix a variety - of issues with extensions that need to add any of these things - to the base class. (Ryan Tomayko) - - * Exception error handlers always override the raise_errors option now. - Previously, all exceptions would be raised outside of the application - when the raise_errors option was enabled, even if an error handler was - defined for that exception. The raise_errors option now controls - whether unhandled exceptions are raised (enabled) or if a generic 500 - error is returned (disabled). (Ryan Tomayko) - - * The X-Cascade response header is set to 'pass' when no matching route - is found or all routes pass. (Josh Peek) - - * Filters do not run when serving static files anymore. (Ryan Tomayko) - - * pass takes an optional block to be used as the route handler if no - subsequent route matches the request. (Blake Mizerany) - -The following Sinatra features have been obsoleted (removed entirely) in -the 1.0 release: - - * The `sinatra/test` library is obsolete. This includes the `Sinatra::Test` - module, the `Sinatra::TestHarness` class, and the `get_it`, `post_it`, - `put_it`, `delete_it`, and `head_it` helper methods. The - [`Rack::Test` library](http://gitrdoc.com/brynary/rack-test) should - be used instead. - - * Test framework specific libraries (`sinatra/test/spec`, - `sinatra/test/bacon`,`sinatra/test/rspec`, etc.) are obsolete. See - http://www.sinatrarb.com/testing.html for instructions on setting up a - testing environment under each of these frameworks. - - * `Sinatra::Default` is obsolete; use `Sinatra::Base` instead. - `Sinatra::Base` acts more like `Sinatra::Default` in development mode. - For example, static file serving and sexy development error pages are - enabled by default. - - * Auto-requiring template libraries in the `erb`, `builder`, `haml`, - and `sass` methods is obsolete due to thread-safety issues. You must - require the template libraries explicitly in your app. - - * The `:views_directory` option to rendering methods is obsolete; use - `:views` instead. - - * The `:haml` and `:sass` options to rendering methods are obsolete. - Template engine options should be passed in the second Hash argument - instead. - - * The `use_in_file_templates` method is obsolete. Use - `enable :inline_templates` or `set :inline_templates, 'path/to/file'` - - * The 'media_type' helper method is obsolete. Use 'mime_type' instead. - - * The 'mime' main and class method is obsolete. Use 'mime_type' instead. - - * The request-level `send_data` method is no longer supported. - - * The `Sinatra::Event` and `Sinatra::EventContext` classes are no longer - supported. This may effect extensions written for versions prior to 0.9.2. - See [Writing Sinatra Extensions](http://www.sinatrarb.com/extensions.html) - for the officially supported extensions API. - - * The `set_option` and `set_options` methods are obsolete; use `set` - instead. - - * The `:env` setting (`settings.env`) is obsolete; use `:environment` - instead. - - * The request level `stop` method is obsolete; use `halt` instead. - - * The request level `entity_tag` method is obsolete; use `etag` - instead. - - * The request level `headers` method (HTTP response headers) is obsolete; - use `response['Header-Name']` instead. - - * `Sinatra.application` is obsolete; use `Sinatra::Application` instead. - - * Using `Sinatra.application = nil` to reset an application is obsolete. - This should no longer be necessary. - - * Using `Sinatra.default_options` to set base configuration items is - obsolete; use `Sinatra::Base.set(key, value)` instead. - - * The `Sinatra::ServerError` exception is obsolete. All exceptions raised - within a request are now treated as internal server errors and result in - a 500 response status. - - * The `:methodoverride' option to enable/disable the POST _method hack is - obsolete; use `:method_override` instead. - -= 0.9.2 / 2009-05-18 - - * This version is compatible with Rack 1.0. [Rein Henrichs] - - * The development-mode unhandled exception / error page has been - greatly enhanced, functionally and aesthetically. The error - page is used when the :show_exceptions option is enabled and an - exception propagates outside of a route handler or before filter. - [Simon Rozet / Matte Noble / Ryan Tomayko] - - * Backtraces that move through templates now include filenames and - line numbers where possible. [#51 / S. Brent Faulkner] - - * All templates now have an app-level option for setting default - template options (:haml, :sass, :erb, :builder). The app-level - option value must be a Hash if set and is merged with the - template options specified to the render method (Base#haml, - Base#erb, Base#builder). [S. Brent Faulkner, Ryan Tomayko] - - * The method signature for all template rendering methods has - been unified: "def engine(template, options={}, locals={})". - The options Hash now takes the generic :views, :layout, and - :locals options but also any template-specific options. The - generic options are removed before calling the template specific - render method. Locals may be specified using either the - :locals key in the options hash or a second Hash option to the - rendering method. [#191 / Ryan Tomayko] - - * The receiver is now passed to "configure" blocks. This - allows for the following idiom in top-level apps: - configure { |app| set :foo, app.root + '/foo' } - [TJ Holowaychuck / Ryan Tomayko] - - * The "sinatra/test" lib is deprecated and will be removed in - Sinatra 1.0. This includes the Sinatra::Test module and - Sinatra::TestHarness class in addition to all the framework - test helpers that were deprecated in 0.9.1. The Rack::Test - lib should be used instead: http://gitrdoc.com/brynary/rack-test - [#176 / Simon Rozet] - - * Development mode source file reloading has been removed. The - "shotgun" (http://rtomayko.github.com/shotgun/) program can be - used to achieve the same basic functionality in most situations. - Passenger users should use the "tmp/always_restart.txt" - file (http://tinyurl.com/c67o4h). [#166 / Ryan Tomayko] - - * Auto-requiring template libs in the erb, builder, haml, and - sass methods is deprecated due to thread-safety issues. You must - require the template libs explicitly in your app file. [Simon Rozet] - - * A new Sinatra::Base#route_missing method was added. route_missing - is sent when no route matches the request or all route handlers - pass. The default implementation forwards the request to the - downstream app when running as middleware (i.e., "@app" is - non-nil), or raises a NotFound exception when no downstream app - is defined. Subclasses can override this method to perform custom - route miss logic. [Jon Crosby] - - * A new Sinatra::Base#route_eval method was added. The method - yields to the block and throws :halt with the result. Subclasses - can override this method to tap into the route execution logic. - [TJ Holowaychuck] - - * Fix the "-x" (enable request mutex / locking) command line - argument. Passing -x now properly sets the :lock option. - [S. Brent Faulkner, Ryan Tomayko] - - * Fix writer ("foo=") and predicate ("foo?") methods in extension - modules not being added to the registering class. - [#172 / Pat Nakajima] - - * Fix in-file templates when running alongside activesupport and - fatal errors when requiring activesupport before sinatra - [#178 / Brian Candler] - - * Fix various issues running on Google AppEngine. - [Samuel Goebert, Simon Rozet] - - * Fix in-file templates __END__ detection when __END__ exists with - other stuff on a line [Yoji Shidara] - -= 0.9.1.1 / 2009-03-09 - - * Fix directory traversal vulnerability in default static files - route. See [#177] for more info. - -= 0.9.1 / 2009-03-01 - - * Sinatra now runs under Ruby 1.9.1 [#61] - - * Route patterns (splats, :named, or Regexp captures) are now - passed as arguments to the block. [#140] - - * The "helpers" method now takes a variable number of modules - along with the normal block syntax. [#133] - - * New request-level #forward method for middleware components: passes - the env to the downstream app and merges the response status, headers, - and body into the current context. [#126] - - * Requests are now automatically forwarded to the downstream app when - running as middleware and no matching route is found or all routes - pass. - - * New simple API for extensions/plugins to add DSL-level and - request-level methods. Use Sinatra.register(mixin) to extend - the DSL with all public methods defined in the mixin module; - use Sinatra.helpers(mixin) to make all public methods defined - in the mixin module available at the request level. [#138] - See http://www.sinatrarb.com/extensions.html for details. - - * Named parameters in routes now capture the "." character. This makes - routes like "/:path/:filename" match against requests like - "/foo/bar.txt"; in this case, "params[:filename]" is "bar.txt". - Previously, the route would not match at all. - - * Added request-level "redirect back" to redirect to the referring - URL. - - * Added a new "clean_trace" option that causes backtraces dumped - to rack.errors and displayed on the development error page to - omit framework and core library backtrace lines. The option is - enabled by default. [#77] - - * The ERB output buffer is now available to helpers via the @_out_buf - instance variable. - - * It's now much easier to test sessions in unit tests by passing a - ":session" option to any of the mock request methods. e.g., - get '/', {}, :session => { 'foo' => 'bar' } - - * The testing framework specific files ('sinatra/test/spec', - 'sinatra/test/bacon', 'sinatra/test/rspec', etc.) have been deprecated. - See http://sinatrarb.com/testing.html for instructions on setting up - a testing environment with these frameworks. - - * The request-level #send_data method from Sinatra 0.3.3 has been added - for compatibility but is deprecated. - - * Fix :provides causing crash on any request when request has no - Accept header [#139] - - * Fix that ERB templates were evaluated twice per "erb" call. - - * Fix app-level middleware not being run when the Sinatra application is - run as middleware. - - * Fixed some issues with running under Rack's CGI handler caused by - writing informational stuff to stdout. - - * Fixed that reloading was sometimes enabled when starting from a - rackup file [#110] - - * Fixed that "." in route patterns erroneously matched any character - instead of a literal ".". [#124] - -= 0.9.0.4 / 2009-01-25 - - * Using halt with more than 1 args causes ArgumentError [#131] - * using halt in a before filter doesn't modify response [#127] - * Add deprecated Sinatra::EventContext to unbreak plugins [#130] - * Give access to GET/POST params in filters [#129] - * Preserve non-nested params in nested params hash [#117] - * Fix backtrace dump with Rack::Lint [#116] - -= 0.9.0.3 / 2009-01-21 - - * Fall back on mongrel then webrick when thin not found. [#75] - * Use :environment instead of :env in test helpers to - fix deprecation warnings coming from framework. - * Make sinatra/test/rspec work again [#113] - * Fix app_file detection on windows [#118] - * Fix static files with Rack::Lint in pipeline [#121] - -= 0.9.0.2 / 2009-01-18 - - * Halting a before block should stop processing of routes [#85] - * Fix redirect/halt in before filters [#85] - -= 0.9.0 / 2009-01-18 - - * Works with and requires Rack >= 0.9.1 - - * Multiple Sinatra applications can now co-exist peacefully within a - single process. The new "Sinatra::Base" class can be subclassed to - establish a blank-slate Rack application or middleware component. - Documentation on using these features is forth-coming; the following - provides the basic gist: http://gist.github.com/38605 - - * Parameters with subscripts are now parsed into a nested/recursive - Hash structure. e.g., "post[title]=Hello&post[body]=World" yields - params: {'post' => {'title' => 'Hello', 'body' => 'World'}}. - - * Regular expressions may now be used in route pattens; captures are - available at "params[:captures]". - - * New ":provides" route condition takes an array of mime types and - matches only when an Accept request header is present with a - corresponding type. [cypher] - - * New request-level "pass" method; immediately exits the current block - and passes control to the next matching route. - - * The request-level "body" method now takes a block; evaluation is - deferred until an attempt is made to read the body. The block must - return a String or Array. - - * New "route conditions" system for attaching rules for when a route - matches. The :agent and :host route options now use this system. - - * New "dump_errors" option controls whether the backtrace is dumped to - rack.errors when an exception is raised from a route. The option is - enabled by default for top-level apps. - - * Better default "app_file", "root", "public", and "views" location - detection; changes to "root" and "app_file" automatically cascade to - other options that depend on them. - - * Error mappings are now split into two distinct layers: exception - mappings and custom error pages. Exception mappings are registered - with "error(Exception)" and are run only when the app raises an - exception. Custom error pages are registered with "error(status_code)", - where "status_code" is an integer, and are run any time the response - has the status code specified. It's also possible to register an error - page for a range of status codes: "error(500..599)". - - * In-file templates are now automatically imported from the file that - requires 'sinatra'. The use_in_file_templates! method is still available - for loading templates from other files. - - * Sinatra's testing support is no longer dependent on Test::Unit. Requiring - 'sinatra/test' adds the Sinatra::Test module and Sinatra::TestHarness - class, which can be used with any test framework. The 'sinatra/test/unit', - 'sinatra/test/spec', 'sinatra/test/rspec', or 'sinatra/test/bacon' files - can be required to setup a framework-specific testing environment. See the - README for more information. - - * Added support for Bacon (test framework). The 'sinatra/test/bacon' file - can be required to setup Sinatra test helpers on Bacon::Context. - - * Deprecated "set_option" and "set_options"; use "set" instead. - - * Deprecated the "env" option ("options.env"); use "environment" instead. - - * Deprecated the request level "stop" method; use "halt" instead. - - * Deprecated the request level "entity_tag" method; use "etag" instead. - Both "entity_tag" and "etag" were previously supported. - - * Deprecated the request level "headers" method (HTTP response headers); - use "response['Header-Name']" instead. - - * Deprecated "Sinatra.application"; use "Sinatra::Application" instead. - - * Deprecated setting Sinatra.application = nil to reset an application. - This should no longer be necessary. - - * Deprecated "Sinatra.default_options"; use - "Sinatra::Default.set(key, value)" instead. - - * Deprecated the "ServerError" exception. All Exceptions are now - treated as internal server errors and result in a 500 response - status. - - * Deprecated the "get_it", "post_it", "put_it", "delete_it", and "head_it" - test helper methods. Use "get", "post", "put", "delete", and "head", - respectively, instead. - - * Removed Event and EventContext classes. Applications are defined in a - subclass of Sinatra::Base; each request is processed within an - instance. - -= 0.3.3 / 2009-01-06 - - * Pin to Rack 0.4.0 (this is the last release on Rack 0.4) - - * Log unhandled exception backtraces to rack.errors. - - * Use RACK_ENV environment variable to establish Sinatra - environment when given. Thin sets this when started with - the -e argument. - - * BUG: raising Sinatra::NotFound resulted in a 500 response - code instead of 404. - - * BUG: use_in_file_templates! fails with CR/LF (#45) - - * BUG: Sinatra detects the app file and root path when run under - thin/passenger. - -= 0.3.2 - - * BUG: Static and send_file read entire file into String before - sending. Updated to stream with 8K chunks instead. - - * Rake tasks and assets for building basic documentation website. - See http://sinatra.rubyforge.org - - * Various minor doc fixes. - -= 0.3.1 - - * Unbreak optional path parameters [jeremyevans] - -= 0.3.0 - - * Add sinatra.gemspec w/ support for github gem builds. Forks can now - enable the build gem option in github to get free username-sinatra.gem - builds: gem install username-sinatra.gem --source=http://gems.github.com/ - - * Require rack-0.4 gem; removes frozen rack dir. - - * Basic RSpec support; require 'sinatra/test/rspec' instead of - 'sinatra/test/spec' to use. [avdi] - - * before filters can modify request environment vars used for - routing (e.g., PATH_INFO, REQUEST_METHOD, etc.) for URL rewriting - type functionality. - - * In-file templates now uses @@ instead of ## as template separator. - - * Top-level environment test predicates: development?, test?, production? - - * Top-level "set", "enable", and "disable" methods for tweaking - app options. [rtomayko] - - * Top-level "use" method for building Rack middleware pipelines - leading to app. See README for usage. [rtomayko] - - * New "reload" option - set false to disable reloading in development. - - * New "host" option - host/ip to bind to [cschneid] - - * New "app_file" option - override the file to reload in development - mode [cschneid] - - * Development error/not_found page cleanup [sr, adamwiggins] - - * Remove a bunch of core extensions (String#to_param, String#from_param, - Hash#from_params, Hash#to_params, Hash#symbolize_keys, Hash#pass) - - * Various grammar and formatting fixes to README; additions on - community and contributing [cypher] - - * Build RDoc using Hanna template: http://sinatrarb.rubyforge.org/api - - * Specs, documentation and fixes for splat'n routes [vic] - - * Fix whitespace errors across all source files. [rtomayko] - - * Fix streaming issues with Mongrel (body not closed). [bmizerany] - - * Fix various issues with environment not being set properly (configure - blocks not running, error pages not registering, etc.) [cypher] - - * Fix to allow locals to be passed to ERB templates [cschneid] - - * Fix locking issues causing random errors during reload in development. - - * Fix for escaped paths not resolving static files [Matthew Walker] - -= 0.2.1 - - * File upload fix and minor tweaks. - -= 0.2.0 - - * Initial gem release of 0.2 codebase. diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/Gemfile b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/Gemfile deleted file mode 100644 index 5f8e892..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/Gemfile +++ /dev/null @@ -1,76 +0,0 @@ -# Why use bundler? -# Well, not all development dependencies install on all rubies. Moreover, `gem -# install sinatra --development` doesn't work, as it will also try to install -# development dependencies of our dependencies, and those are not conflict free. -# So, here we are, `bundle install`. -# -# If you have issues with a gem: `bundle install --without-coffee-script`. - -RUBY_ENGINE = 'ruby' unless defined? RUBY_ENGINE -source 'https://rubygems.org' unless ENV['QUICK'] -gemspec - -gem 'rake' -gem 'rack-test', '>= 0.5.6' - -# Allows stuff like `tilt=1.2.2 bundle install` or `tilt=master ...`. -# Used by the CI. -github = "git://github.com/%s.git" -repos = {'tilt' => github % "rtomayko/tilt", 'rack' => github % "rack/rack"} - -%w[tilt rack].each do |lib| - dep = case ENV[lib] - when 'stable', nil then nil - when /(\d+\.)+\d+/ then "~> " + ENV[lib].sub("#{lib}-", '') - else {:git => repos[lib], :branch => dep} - end - gem lib, dep -end - -if RUBY_ENGINE == 'jruby' - gem 'nokogiri', '!= 1.5.0' - gem 'jruby-openssl' - gem 'trinidad' -end - -if RUBY_ENGINE == "ruby" and RUBY_VERSION > '1.9.2' - gem 'less', '~> 2.0' - gem 'therubyracer' - gem 'redcarpet' - gem 'wlang', '>= 2.0.1' - gem 'bluecloth' - gem 'rdiscount' - gem 'RedCloth' - gem 'puma' - gem 'net-http-server' - gem 'yajl-ruby' - gem 'nokogiri' - gem 'thin' - gem 'slim', '~> 1.0' - gem 'coffee-script', '>= 2.0' - gem 'rdoc' - gem 'kramdown' - gem 'maruku' - gem 'creole' - gem 'wikicloth' - gem 'markaby' - gem 'radius' - gem 'asciidoctor' - gem 'liquid' - gem 'stylus' - gem 'rabl' - gem 'builder' - gem 'erubis' - gem 'haml', '>= 3.0' - gem 'sass' -end - -if RUBY_ENGINE == "rbx" - gem 'json' - gem 'rubysl' - gem 'rubysl-test-unit' -end - -platforms :ruby_18, :jruby do - gem 'json' unless RUBY_VERSION > '1.9' # is there a jruby but 1.8 only selector? -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/LICENSE b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/LICENSE deleted file mode 100644 index 9cd6fa5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2007, 2008, 2009 Blake Mizerany -Copyright (c) 2010, 2011, 2012, 2013, 2014 Konstantin Haase - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.de.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.de.md deleted file mode 100644 index 2f8618b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.de.md +++ /dev/null @@ -1,2864 +0,0 @@ -# Sinatra - -*Wichtig: Dieses Dokument ist eine Übersetzung aus dem Englischen und unter -Umständen nicht auf dem aktuellen Stand (aktuell Sinatra 1.4.2).* - -Sinatra ist eine -[DSL](http://de.wikipedia.org/wiki/Domänenspezifische_Sprache), die das -schnelle Erstellen von Webanwendungen in Ruby mit minimalem Aufwand -ermöglicht: - -Sinatra via `rubygems` installieren: - -```shell -gem install sinatra -``` - -Eine Datei mit dem Namen `myapp.rb` erstellen: - -```ruby -require 'sinatra' -get '/' do - 'Hallo Welt!' -end -``` - -und im gleichen Verzeichnis ausführen: - -```shell -ruby myapp.rb -``` - -Die Seite kann nun unter [http://localhost:4567](http://localhost:4567) -aufgerufen werden. - -## Inhalt - -* [Sinatra](#sinatra) - * [Routen](#routen) - * [Bedingungen](#bedingungen) - * [Rückgabewerte](#rckgabewerte) - * [Eigene Routen-Muster](#eigene-routen-muster) - * [Statische Dateien](#statische-dateien) - * [Views/Templates](#viewstemplates) - * [Direkte Templates](#direkte-templates) - * [Verfügbare Templatesprachen](#verfgbare-templatesprachen) - * [Haml Templates](#haml-templates) - * [Erb Templates](#erb-templates) - * [Builder Templates](#builder-templates) - * [Nokogiri Templates](#nokogiri-templates) - * [Sass Templates](#sass-templates) - * [SCSS Templates](#scss-templates) - * [Less Templates](#less-templates) - * [Liquid Templates](#liquid-templates) - * [Markdown Templates](#markdown-templates) - * [Textile Templates](#textile-templates) - * [RDoc Templates](#rdoc-templates) - * [Radius Templates](#radius-templates) - * [Markaby Templates](#markaby-templates) - * [RABL Templates](#rabl-templates) - * [Slim Templates](#slim-templates) - * [Creole Templates](#creole-templates) - * [CoffeeScript Templates](#coffeescript-templates) - * [Stylus Templates](#stylus-templates) - * [Yajl Templates](#yajl-templates) - * [WLang Templates](#wlang-templates) - * [Auf Variablen in Templates zugreifen](#auf-variablen-in-templates-zugreifen) - * [Templates mit `yield` und verschachtelte Layouts](#templates-mit-yield-und-verschachtelte-layouts) - * [Inline-Templates](#inline-templates) - * [Benannte Templates](#benannte-templates) - * [Dateiendungen zuordnen](#dateiendungen-zuordnen) - * [Eine eigene Template-Engine hinzufügen](#eine-eigene-template-engine-hinzufgen) - * [Filter](#filter) - * [Helfer](#helfer) - * [Sessions verwenden](#sessions-verwenden) - * [Anhalten](#anhalten) - * [Weiterspringen](#weiterspringen) - * [Eine andere Route ansteuern](#eine-andere-route-ansteuern) - * [Body, Status-Code und Header setzen](#body-status-code-und-header-setzen) - * [Response-Streams](#response-streams) - * [Logger](#logger) - * [Mime-Types](#mime-types) - * [URLs generieren](#urls-generieren) - * [Browser-Umleitung](#browser-umleitung) - * [Cache einsetzen](#cache-einsetzen) - * [Dateien versenden](#dateien-versenden) - * [Das Request-Objekt](#das-request-objekt) - * [Anhänge](#anhnge) - * [Umgang mit Datum und Zeit](#umgang-mit-datum-und-zeit) - * [Nachschlagen von Template-Dateien](#nachschlagen-von-template-dateien) - * [Konfiguration](#konfiguration) - * [Einstellung des Angriffsschutzes](#einstellung-des-angriffsschutzes) - * [Mögliche Einstellungen](#mgliche-einstellungen) - * [Umgebungen](#umgebungen) - * [Fehlerbehandlung](#fehlerbehandlung) - * [Nicht gefunden](#nicht-gefunden) - * [Fehler](#fehler) - * [Rack-Middleware](#rack-middleware) - * [Testen](#testen) - * [Sinatra::Base - Middleware, Bibliotheken und modulare Anwendungen](#sinatrabase---middleware-bibliotheken-und-modulare-anwendungen) - * [Modularer vs. klassischer Stil](#modularer-vs-klassischer-stil) - * [Eine modulare Applikation bereitstellen](#eine-modulare-applikation-bereitstellen) - * [Eine klassische Anwendung mit einer config.ru verwenden](#eine-klassische-anwendung-mit-einer-configru-verwenden) - * [Wann sollte eine config.ru-Datei verwendet werden?](#wann-sollte-eine-configru-datei-verwendet-werden) - * [Sinatra als Middleware nutzen](#sinatra-als-middleware-nutzen) - * [Dynamische Applikationserstellung](#dynamische-applikationserstellung) - * [Geltungsbereich und Bindung](#geltungsbereich-und-bindung) - * [Anwendungs- oder Klassen-Scope](#anwendungs--oder-klassen-scope) - * [Anfrage- oder Instanz-Scope](#anfrage--oder-instanz-scope) - * [Delegation-Scope](#delegation-scope) - * [Kommandozeile](#kommandozeile) - * [Systemanforderungen](#systemanforderungen) - * [Der neuste Stand (The Bleeding Edge)](#der-neuste-stand-the-bleeding-edge) - * [Mit Bundler](#mit-bundler) - * [Eigenes Repository](#eigenes-repository) - * [Gem erstellen](#gem-erstellen) - * [Versions-Verfahren](#versions-verfahren) - * [Mehr](#mehr) - -## Routen - -In Sinatra wird eine Route durch eine HTTP-Methode und ein URL-Muster definiert. -Jeder dieser Routen wird ein Ruby-Block zugeordnet: - -```ruby -get '/' do - .. zeige etwas .. -end - -post '/' do - .. erstelle etwas .. -end - -put '/' do - .. update etwas .. -end - -delete '/' do - .. entferne etwas .. -end - -options '/' do - .. zeige, was wir können .. -end - -link '/' do - .. verbinde etwas .. -end - -unlink '/' do - .. trenne etwas .. -end -``` - -Die Routen werden in der Reihenfolge durchlaufen, in der sie definiert wurden. -Das erste Routen-Muster, das mit dem Request übereinstimmt, wird ausgeführt. - -Die Muster der Routen können benannte Parameter beinhalten, die über den -`params`-Hash zugänglich gemacht werden: - -```ruby -get '/hallo/:name' do - # passt auf "GET /hallo/foo" und "GET /hallo/bar" - # params[:name] ist dann 'foo' oder 'bar' - "Hallo #{params[:name]}!" -end -``` - -Man kann auf diese auch mit Block-Parametern zugreifen: - -```ruby -get '/hallo/:name' do |n| - # n entspricht hier params[:name] - "Hallo #{n}!" -end -``` - -Routen-Muster können auch mit sog. Splat- oder Wildcard-Parametern über das -`params[:splat]`-Array angesprochen werden: - -```ruby -get '/sag/*/zu/*' do - # passt z.B. auf /sag/hallo/zu/welt - params[:splat] # => ["hallo", "welt"] -end - -get '/download/*.*' do - # passt auf /download/pfad/zu/datei.xml - params[:splat] # => ["pfad/zu/datei", "xml"] -end -``` - -Oder mit Block-Parametern: - -```ruby -get '/download/*.*' do |pfad, endung| - [pfad, endung] # => ["Pfad/zu/Datei", "xml"] -end -``` - -Routen mit regulären Ausdrücken sind auch möglich: - -```ruby -get %r{/hallo/([\w]+)} do - "Hallo, #{params[:captures].first}!" -end -``` - -Und auch hier können Block-Parameter genutzt werden: - -```ruby -get %r{/hallo/([\w]+)} do |c| - "Hallo, #{c}!" -end -``` - -Routen-Muster können auch mit optionalen Parametern ausgestattet werden: - -```ruby -get '/posts.?:format?' do - # passt auf "GET /posts" sowie jegliche Erweiterung - # wie "GET /posts.json", "GET /posts.xml" etc. -end -``` - -Anmerkung: Solange man den sog. Path Traversal Attack-Schutz nicht deaktiviert -(siehe weiter unten), kann es sein, dass der Request-Pfad noch vor dem -Abgleich mit den Routen modifiziert wird. - -### Bedingungen - -An Routen können eine Vielzahl von Bedingungen geknüpft werden, die erfüllt -sein müssen, damit der Block ausgeführt wird. Möglich wäre etwa eine -Einschränkung des User-Agents über die interne Bedingung `:agent`: - -```ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "Du verwendest Songbird Version #{params[:agent][0]}" -end -``` - -Wird Songbird als Browser nicht verwendet, springt Sinatra zur nächsten Route: - -```ruby -get '/foo' do - # passt auf andere Browser -end -``` - -Andere mitgelieferte Bedingungen sind `:host_name` und `:provides`: - -```ruby -get '/', :host_name => /^admin\./ do - "Adminbereich, Zugriff verweigert!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -Eigene Bedingungen können relativ einfach hinzugefügt werden: - -```ruby -set(:wahrscheinlichkeit) { |value| condition { rand <= value } } - -get '/auto_gewinnen', :wahrscheinlichkeit => 0.1 do - "Du hast gewonnen!" -end - -get '/auto_gewinnen' do - "Tut mir leid, verloren." -end -``` - -Bei Bedingungen, die mehrere Werte annehmen können, sollte ein Splat verwendet -werden: - -```ruby -set(:auth) do |*roles| # <- hier kommt der Splat ins Spiel - condition do - unless logged_in? && roles.any? {|role| current_user.in_role? role } - redirect "/login/", 303 - end - end -end - -get "/mein/account/", :auth => [:user, :admin] do - "Mein Account" -end - -get "/nur/admin/", :auth => :admin do - "Nur Admins dürfen hier rein!" -end -``` - -### Rückgabewerte - -Durch den Rückgabewert eines Routen-Blocks wird mindestens der Response-Body -festgelegt, der an den HTTP-Client, bzw. die nächste Rack-Middleware, -weitergegeben wird. Im Normalfall handelt es sich hierbei, wie in den -vorangehenden Beispielen zu sehen war, um einen String. Es werden allerdings -auch andere Werte akzeptiert. - -Es kann jedes gültige Objekt zurückgegeben werden, bei dem es sich entweder um -einen Rack-Rückgabewert, einen Rack-Body oder einen HTTP-Status-Code handelt: - -* Ein Array mit drei Elementen: `[Status (Fixnum), Headers (Hash), - Response-Body (antwortet auf #each)]`. -* Ein Array mit zwei Elementen: `[Status (Fixnum), Response-Body (antwortet - auf #each)]`. -* Ein Objekt, das auf `#each` antwortet und den an diese Methode übergebenen - Block nur mit Strings als Übergabewerte aufruft. -* Ein Fixnum, das den Status-Code festlegt. - -Damit lässt sich relativ einfach Streaming implementieren: - -```ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -Ebenso kann die `stream`-Helfer-Methode (s.u.) verwendet werden, die Streaming -direkt in die Route integriert. - -### Eigene Routen-Muster - -Wie oben schon beschrieben, ist Sinatra von Haus aus mit Unterstützung für -String-Muster und Reguläre Ausdrücke zum Abgleichen von Routen ausgestattet. -Das muss aber noch nicht alles sein, es können ohne großen Aufwand eigene -Routen-Muster erstellt werden: - -```ruby -class AllButPattern - Match = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Match.new([]) - end - - def match(str) - @captures unless @except === str - end -end - -def all_but(pattern) - AllButPattern.new(pattern) -end - -get all_but("/index") do - # ... -end -``` - -Beachte, dass das obige Beispiel etwas übertrieben wirkt. Es geht auch einfacher: - -```ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -Oder unter Verwendung eines negativen look ahead: - -```ruby -get %r{^(?!/index$)} do - # ... -end -``` - -## Statische Dateien - -Statische Dateien werden im `./public`-Ordner erwartet. Es ist möglich, -einen anderen Ort zu definieren, indem man die `:public_folder`-Option setzt: - -```ruby -set :public_folder, File.dirname(__FILE__) + '/static' -``` - -Zu beachten ist, dass der Ordnername `public` nicht Teil der URL ist. Die Datei -`./public/css/style.css` ist unter `http://example.com/css/style.css` zu finden. - -Um den `Cache-Control`-Header mit Informationen zu versorgen, verwendet man -die `:static_cache_control`-Einstellung (s.u.). - -## Views/Templates - -Alle Templatesprachen verwenden ihre eigene Renderingmethode, die jeweils -einen String zurückgibt: - -```ruby -get '/' do - erb :index -end -``` - -Dieses Beispiel rendert `views/index.erb`. - -Anstelle eines Templatenamens kann man auch direkt die Templatesprache verwenden: - -```ruby -get '/' do - code = "<%= Time.now %>" - erb code -end -``` - -Templates nehmen ein zweite Argument an, den Options-Hash: - -```ruby -get '/' do - erb :index, :layout => :post -end -``` - -Dieses Beispiel rendert `views/index.erb` eingebettet in `views/post.erb` -(Voreinstellung ist `views/layout.erb`, sofern es vorhanden ist.) - -Optionen, die Sinatra nicht versteht, werden an das Template weitergereicht: - -```ruby -get '/' do - haml :index, :format => :html5 -end -``` - -Für alle Templates können auch Einstellungen, die für alle Routen gelten, -festgelegt werden: - -```ruby -set :haml, :format => :html5 - -get '/' do - haml :index -end -``` - -Optionen, die an die Rendermethode weitergegeben werden, überschreiben die -Einstellungen, die mit `set` festgelegt wurden. - -Einstellungen: - -
-
locals
-
Liste von lokalen Variablen, die an das Dokument weitergegeben werden. - Praktisch für Partials: - - erb "<%= foo %>", :locals => {:foo => "bar"}
- -
default_encoding
-
Gibt die Stringkodierung an, die verwendet werden soll. Voreingestellt - auf settings.default_encoding.
- -
views
-
Ordner, aus dem die Templates geladen werden. Voreingestellt auf - settings.views.
- -
layout
-
Legt fest, ob ein Layouttemplate verwendet werden soll oder nicht - (true oderfalse). Ist es ein Symbol, dann legt es fest, - welches Template als Layout verwendet wird: - - erb :index, :layout => !request.xhr?
- -
content_type
-
Content-Typ den das Template ausgibt. Voreinstellung hängt von der - Templatesprache ab.
- -
scope
-
Scope, in dem das Template gerendert wird. Liegt standardmäßig innerhalb - der App-Instanz. Wird Scope geändert, sind Instanzvariablen und - Helfermethoden nicht verfügbar.
- -
layout_engine
-
Legt fest, welcher Renderer für das Layout verantwortlich ist. Hilfreich - für Sprachen, die sonst keine Templates unterstützen. Voreingestellt auf - den Renderer, der für das Template verwendet wird: - - set :rdoc, :layout_engine => :erb
- -
layout_options
-
Besondere Einstellungen, die nur für das Rendering verwendet werden: - - set :rdoc, :layout_options => { :views => 'views/layouts' }
-
- -Sinatra geht davon aus, dass die Templates sich im `./views` Verzeichnis -befinden. Es kann jedoch ein anderer Ordner festgelegt werden: - -```ruby -set :views, settings.root + '/templates' -``` - -Es ist zu beachten, dass immer mit Symbolen auf Templates verwiesen werden muss, -auch dann, wenn sie sich in einem Unterordner befinden: - -```ruby -haml :'unterverzeichnis/template' -``` - -Rendering-Methoden rendern jeden String direkt. - -### Direkte Templates - -``` ruby -get '/' do - haml '%div.title Hallo Welt' -end -``` - -Hier wird der String direkt gerendert. - -### Verfügbare Templatesprachen - -Einige Sprachen haben mehrere Implementierungen. Um festzulegen, welche -verwendet wird (und dann auch Thread-sicher ist), verwendet man am besten zu -Beginn ein `'require'`: - -```ruby -require 'rdiscount' # oder require 'bluecloth' -get('/') { markdown :index } -``` - -#### Haml Templates - - - - - - - - - - - - - - -
Abhängigkeithaml
Dateierweiterung.haml
Beispielhaml :index, :format => :html5
- - -#### Erb Templates - - - - - - - - - - - - - - -
Abhängigkeiterubis oder erb - (Standardbibliothek von Ruby)
Dateierweiterungen.erb, .rhtml oder .erubis (nur Erubis)
Beispielerb :index
- - -#### Builder Templates - - - - - - - - - - - - - - -
Abhängigkeitbuilder
Dateierweiterung.builder
Beispielbuilder { |xml| xml.em "Hallo" }
- -Nimmt ebenso einen Block für Inline-Templates entgegen (siehe Beispiel). - -#### Nokogiri Templates - - - - - - - - - - - - - - -
Abhängigkeitnokogiri
Dateierweiterung.nokogiri
Beispielnokogiri { |xml| xml.em "Hallo" }
- -Nimmt ebenso einen Block für Inline-Templates entgegen (siehe Beispiel). - -#### Sass Templates - - - - - - - - - - - - - - -
Abhängigkeitsass
Dateierweiterung.sass
Beispielsass :stylesheet, :style => :expanded
- - -#### SCSS Templates - - - - - - - - - - - - - - -
Abhängigkeitsass
Dateierweiterung.scss
Beispielscss :stylesheet, :style => :expanded
- - -#### Less Templates - - - - - - - - - - - - - - -
Abhängigkeitless
Dateierweiterung.less
Beispielless :stylesheet
- - -#### Liquid Templates - - - - - - - - - - - - - - -
Abhängigkeitliquid
Dateierweiterung.liquid
Beispielliquid :index, :locals => { :key => 'Wert' }
- -Da man aus dem Liquid-Template heraus keine Ruby-Methoden aufrufen kann -(ausgenommen `yield`), wird man üblicherweise locals verwenden wollen, mit -denen man Variablen weitergibt. - -#### Markdown Templates - - - - - - - - - - - - - - -
AbhängigkeitEine der folgenden Bibliotheken: - RDiscount, - RedCarpet, - BlueCloth, - kramdown oder - maruku -
Dateierweiterungen.markdown, .mkd und .md
Beispielmarkdown :index, :layout_engine => :erb
- -Da man aus den Markdown-Templates heraus keine Ruby-Methoden aufrufen und auch -keine locals verwenden kann, wird man Markdown üblicherweise in Kombination -mit anderen Renderern verwenden wollen: - -```ruby -erb :overview, :locals => { :text => markdown(:einfuehrung) } -``` - -Beachte, dass man die `markdown`-Methode auch aus anderen Templates heraus -aufrufen kann: - -```ruby -%h1 Gruß von Haml! -%p= markdown(:Grüße) -``` - -Da man Ruby nicht von Markdown heraus aufrufen kann, können auch Layouts nicht -in Markdown geschrieben werden. Es ist aber möglich, einen Renderer für die -Templates zu verwenden und einen anderen für das Layout, indem die -`:layout_engine`-Option verwendet wird. - -#### Textile Templates - - - - - - - - - - - - - - -
AbhängigkeitRedCloth
Dateierweiterung.textile
Beispieltextile :index, :layout_engine => :erb
- -Da man aus dem Textile-Template heraus keine Ruby-Methoden aufrufen und auch -keine locals verwenden kann, wird man Textile üblicherweise in Kombination mit -anderen Renderern verwenden wollen: - -```ruby -erb :overview, :locals => { :text => textile(:einfuehrung) } -``` - -Beachte, dass man die `textile`-Methode auch aus anderen Templates heraus -aufrufen kann: - -```ruby -%h1 Gruß von Haml! -%p= textile(:Grüße) -``` - -Da man Ruby nicht von Textile heraus aufrufen kann, können auch Layouts nicht -in Textile geschrieben werden. Es ist aber möglich, einen Renderer für die -Templates zu verwenden und einen anderen für das Layout, indem die -`:layout_engine`-Option verwendet wird. - -#### RDoc Templates - - - - - - - - - - - - - - -
Abhängigkeitrdoc
Dateierweiterung.rdoc
Beispieltextile :README, :layout_engine => :erb
- -Da man aus dem RDoc-Template heraus keine Ruby-Methoden aufrufen und auch -keine locals verwenden kann, wird man RDoc üblicherweise in Kombination mit -anderen Renderern verwenden wollen: - -```ruby -erb :overview, :locals => { :text => rdoc(:einfuehrung) } -``` - -Beachte, dass man die `rdoc`-Methode auch aus anderen Templates heraus -aufrufen kann: - -```ruby -%h1 Gruß von Haml! -%p= rdoc(:Grüße) -``` - -Da man Ruby nicht von RDoc heraus aufrufen kann, können auch Layouts nicht in -RDoc geschrieben werden. Es ist aber möglich, einen Renderer für die Templates -zu verwenden und einen anderen für das Layout, indem die -`:layout_engine`-Option verwendet wird. - -#### Radius Templates - - - - - - - - - - - - - - -
Abhängigkeitradius
Dateierweiterung.radius
Beispielradius :index, :locals => { :key => 'Wert' }
- -Da man aus dem Radius-Template heraus keine Ruby-Methoden aufrufen kann, wird -man üblicherweise locals verwenden wollen, mit denen man Variablen weitergibt. - -#### Markaby Templates - - - - - - - - - - - - - - -
Abhängigkeitmarkaby
Dateierweiterung.mab
Beispielmarkaby { h1 "Willkommen!" }
- -Nimmt ebenso einen Block für Inline-Templates entgegen (siehe Beispiel). - -#### RABL Templates - - - - - - - - - - - - - - -
Abhängigkeitrabl
Dateierweiterung.rabl
Beispielrabl :index
- -#### Slim Templates - - - - - - - - - - - - - - -
Abhängigkeitslim
Dateierweiterung.slim
Beispielslim :index
- -#### Creole Templates - - - - - - - - - - - - - - -
Abhängigkeitcreole
Dateierweiterung.creole
Beispielcreole :wiki, :layout_engine => :erb
- -Da man aus dem Creole-Template heraus keine Ruby-Methoden aufrufen und auch -keine locals verwenden kann, wird man Creole üblicherweise in Kombination mit -anderen Renderern verwenden wollen: - -```ruby -erb :overview, :locals => { :text => creole(:einfuehrung) } -``` - -Beachte, dass man die `creole`-Methode auch aus anderen Templates heraus -aufrufen kann: - -```ruby -%h1 Gruß von Haml! -%p= creole(:Grüße) -``` - -Da man Ruby nicht von Creole heraus aufrufen kann, können auch Layouts nicht in -Creole geschrieben werden. Es ist aber möglich, einen Renderer für die Templates -zu verwenden und einen anderen für das Layout, indem die `:layout_engine`-Option -verwendet wird. - -#### CoffeeScript Templates - - - - - - - - - - - - - -
Abhängigkeitcoffee-script - und eine Möglichkeit JavaScript auszuführen. -
Dateierweiterung.coffee
Beispielcoffee :index
- -#### Stylus Templates - - - - - - - - - - - - - - -
Abhängigkeit - - Stylus - und eine Möglichkeit - - JavaScript auszuführen - . -
Dateierweiterung.styl
Beispielstylus :index
- -Um Stylus-Templates ausführen zu können, müssen `stylus` und `stylus/tilt` -zuerst geladen werden: - -``` ruby -require 'sinatra' -require 'stylus' -require 'stylus/tilt' - -get '/' do - stylus :example -end -``` - -#### Yajl Templates - - - - - - - - - - - - - - -
Abhängigkeityajl-ruby
Dateierweiterung.yajl
Beispiel - - yajl :index, - :locals => { :key => 'qux' }, - :callback => 'present', - :variable => 'resource' - -
- -Die Template-Quelle wird als Ruby-String evaluiert. Die daraus resultierende -json Variable wird mit Hilfe von `#to_json` umgewandelt: - -``` ruby -json = { :foo => 'bar' } -json[:baz] = key -``` - -Die `:callback` und `:variable` Optionen können mit dem gerenderten Objekt -verwendet werden: - -``` ruby -var resource = {"foo":"bar","baz":"qux"}; present(resource); -``` - -#### WLang Templates - - - - - - - - - - - - - - -
Abhängigkeitwlang
Dateierweiterung.wlang
Beispielwlang :index, :locals => { :key => 'value' }
- -Ruby-Methoden in wlang aufzurufen entspricht nicht den idiomatischen Vorgaben -von wlang, es bietet sich deshalb an, `:locals` zu verwenden. Layouts, die -wlang und `yield` verwenden, werden aber trotzdem unterstützt. - -Rendert den eingebetteten Template-String. - -### Auf Variablen in Templates zugreifen - -Templates werden in demselben Kontext ausgeführt wie Routen. Instanzvariablen -in Routen sind auch direkt im Template verfügbar: - -```ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.name' -end -``` - -Oder durch einen expliziten Hash von lokalen Variablen: - -```ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= bar.name', :locals => { :bar => foo } -end -``` - -Dies wird typischerweise bei Verwendung von Subtemplates (partials) in anderen -Templates eingesetzt. - -### Templates mit `yield` und verschachtelte Layouts - -Ein Layout ist üblicherweise ein Template, das ein `yield` aufruft. Ein solches -Template kann entweder wie oben beschrieben über die `:template` Option -verwendet werden oder mit einem Block gerendert werden: - -``` ruby -erb :post, :layout => false do - erb :index -end -``` - -Dieser Code entspricht weitestgehend `erb :index, :layout => :post`. - -Blöcke an Render-Methoden weiterzugeben ist besonders bei verschachtelten -Layouts hilfreich: - -``` ruby -erb :main_layout, :layout => false do - erb :admin_layout do - erb :user - end -end -``` - -Der gleiche Effekt kann auch mit weniger Code erreicht werden: - -``` ruby -erb :admin_layout, :layout => :main_layout do - erb :user -end -``` - -Zur Zeit nehmen folgende Renderer Blöcke an: `erb`, `haml`, `liquid`, `slim ` -und `wlang`. - -Das gleich gilt auch für die allgemeine `render` Methode. - -### Inline-Templates - -Templates können auch am Ende der Datei definiert werden: - -```ruby -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Hallo Welt!!!!! -``` - -Anmerkung: Inline-Templates, die in der Datei definiert sind, die `require -'sinatra'` aufruft, werden automatisch geladen. Um andere Inline-Templates in -anderen Dateien aufzurufen, muss explizit `enable :inline_templates` verwendet -werden. - -### Benannte Templates - -Templates können auch mit der Top-Level `template`-Methode definiert werden: - -```ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Hallo Welt!' -end - -get '/' do - haml :index -end -``` - -Wenn ein Template mit dem Namen "layout" existiert, wird es bei jedem Aufruf -verwendet. Durch `:layout => false` kann das Ausführen verhindert werden: - -```ruby -get '/' do - haml :index, :layout => !request.xhr? - # !request.xhr? prüft, ob es sich um einen asynchronen Request handelt. - # wenn nicht, dann verwende ein Layout (negiert durch !) -end -``` - -### Dateiendungen zuordnen - -Um eine Dateiendung einer Template-Engine zuzuordnen, kann `Tilt.register` -genutzt werden. Wenn etwa die Dateiendung `tt` für Textile-Templates genutzt -werden soll, lässt sich dies wie folgt bewerkstelligen: - -```ruby -Tilt.register :tt, Tilt[:textile] -``` - -### Eine eigene Template-Engine hinzufügen - -Zu allererst muss die Engine bei Tilt registriert und danach eine -Rendering-Methode erstellt werden: - -```ruby -Tilt.register :mtt, MeineTolleTemplateEngine - -helpers do - def mtt(*args) render(:mtt, *args) end -end - -get '/' do - mtt :index -end -``` - -Dieser Code rendert `./views/application.mtt`. Siehe -[github.com/rtomayko/tilt](https://github.com/rtomayko/tilt), um mehr über -Tilt zu erfahren. - -## Filter - -Before-Filter werden vor jedem Request in demselben Kontext, wie danach die -Routen, ausgeführt. So können etwa Request und Antwort geändert werden. -Gesetzte Instanzvariablen in Filtern können in Routen und Templates verwendet -werden: - -```ruby -before do - @note = 'Hi!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @note #=> 'Hi!' - params[:splat] #=> 'bar/baz' -end -``` - -After-Filter werden nach jedem Request in demselben Kontext ausgeführt und -können ebenfalls Request und Antwort ändern. In Before-Filtern gesetzte -Instanzvariablen können in After-Filtern verwendet werden: - -```ruby -after do - puts response.status -end -``` - -Filter können optional auch mit einem Muster ausgestattet werden, das auf den -Request-Pfad passen muss, damit der Filter ausgeführt wird: - -```ruby -before '/protected/*' do - authenticate! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -``` - -Ähnlich wie Routen können Filter auch mit weiteren Bedingungen eingeschränkt -werden: - -```ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'example.com' do - # ... -end -``` - -## Helfer - -Durch die Top-Level `helpers`-Methode werden sogenannte Helfer-Methoden -definiert, die in Routen und Templates verwendet werden können: - -```ruby -helpers do - def bar(name) - "#{name}bar" - end -end - -get '/:name' do - bar(params[:name]) -end -``` - -### Sessions verwenden -Sessions werden verwendet, um Zustände zwischen den Requests zu speichern. Sind -sie aktiviert, kann ein Session-Hash je Benutzer-Session verwendet werden: - -```ruby -enable :sessions - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -Beachte, dass `enable :sessions` alle Daten in einem Cookie speichert. Unter -Umständen kann dies negative Effekte haben, z.B. verursachen viele Daten -höheren, teilweise überflüssigen Traffic. Um das zu vermeiden, kann eine Rack- -Session-Middleware verwendet werden. Dabei wird auf `enable :sessions` -verzichtet und die Middleware wie üblich im Programm eingebunden: - -```ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -Um die Sicherheit zu erhöhen, werden Cookies, die Session-Daten führen, mit -einem sogenannten Session-Secret signiert. Da sich dieses Geheimwort bei jedem -Neustart der Applikation automatisch ändert, ist es sinnvoll, ein eigenes zu -wählen, damit sich alle Instanzen der Applikation dasselbe Session-Secret -teilen: - -```ruby -set :session_secret, 'super_geheimes_Gegeimnis' -``` - -Zur weiteren Konfiguration kann man einen Hash mit Optionen in den `sessions` -Einstellungen ablegen. - -```ruby -set :sessions, :domain => 'foo.com' -``` - -### Anhalten - -Zum sofortigen Stoppen eines Request in einem Filter oder einer Route: - -```ruby -halt -``` - -Der Status kann beim Stoppen mit angegeben werden: - -```ruby -halt 410 -``` - -Oder auch den Response-Body: - -```ruby -halt 'Hier steht der Body' -``` - -Oder beides: - -```ruby -halt 401, 'verschwinde!' -``` - -Sogar mit Headern: - -```ruby -halt 402, {'Content-Type' => 'text/plain'}, 'Rache' -``` - -Natürlich ist es auch möglich, ein Template mit `halt` zu verwenden: - -```ruby -halt erb(:error) -``` - -### Weiterspringen - -Eine Route kann mittels `pass` zu der nächsten passenden Route springen: - -```ruby -get '/raten/:wer' do - pass unless params[:wer] == 'Frank' - 'Du hast mich!' -end - -get '/raten/*' do - 'Du hast mich nicht!' -end -``` - -Der Block wird sofort verlassen und es wird nach der nächsten treffenden Route -gesucht. Ein 404-Fehler wird zurückgegeben, wenn kein treffendes Routen-Muster -gefunden wird. - -### Eine andere Route ansteuern - -Wenn nicht zu einer anderen Route gesprungen werden soll, sondern nur das -Ergebnis einer anderen Route gefordert wird, kann `call` für einen internen -Request verwendet werden: - -```ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do - "bar" -end -``` - -Beachte, dass in dem oben angegeben Beispiel die Performance erheblich erhöht -werden kann, wenn `"bar"` in eine Helfer-Methode umgewandelt wird, auf die -`/foo` und `/bar` zugreifen können. - -Wenn der Request innerhalb derselben Applikations-Instanz aufgerufen und keine -Kopie der Instanz erzeugt werden soll, kann `call!` anstelle von `call` -verwendet werden. - -### Body, Status-Code und Header setzen - -Es ist möglich und empfohlen, den Status-Code sowie den Response-Body mit einem -Returnwert in der Route zu setzen. In manchen Situationen kann es jedoch sein, -dass der Body an anderer Stelle während der Ausführung gesetzt werden soll. -Dafür kann man die Helfer-Methode `body` einsetzen. Ist sie gesetzt, kann sie zu -einem späteren Zeitpunkt aufgerufen werden: - -```ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -``` - -Ebenso ist es möglich, einen Block an `body` weiterzureichen, der dann vom -Rack-Handler ausgeführt wird (lässt sich z.B. zur Umsetzung von Streaming -einsetzen, siehe auch "Rückgabewerte"). - -Vergleichbar mit `body` lassen sich auch Status-Code und Header setzen: - -```ruby -get '/foo' do - status 418 - headers \ - "Allow" => "BREW, POST, GET, PROPFIND, WHEN", - "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - halt "Ich bin ein Teekesselchen" -end -``` - -Genau wie bei `body` liest ein Aufrufen von `headers` oder `status` ohne -Argumente den aktuellen Wert aus. - -### Response-Streams - -In manchen Situationen sollen Daten bereits an den Client zurückgeschickt -werden, bevor ein vollständiger Response bereit steht. Manchmal will man die -Verbindung auch erst dann beenden und Daten so lange an den Client -zurückschicken, bis er die Verbindung abbricht. Für diese Fälle gibt es die -`stream`-Helfer-Methode, die es einem erspart eigene Lösungen zu schreiben: - -```ruby -get '/' do - stream do |out| - out << "Das ist ja mal wieder fanta -\n" - sleep 0.5 - out << " (bitte warten…) \n" - sleep 1 - out << "- stisch!\n" - end -end -``` - -Damit lassen sich Streaming-APIs realisieren, sog. -[Server Sent Events](http://dev.w3.org/html5/eventsource/), die als Basis für -[WebSockets](http://en.wikipedia.org/wiki/WebSocket) dienen. Ebenso können sie -verwendet werden, um den Durchsatz zu erhöhen, wenn ein Teil der Daten von -langsamen Ressourcen abhängig ist. - -Es ist zu beachten, dass das Verhalten beim Streaming, insbesondere die Anzahl -nebenläufiger Anfragen, stark davon abhängt, welcher Webserver für die -Applikation verwendet wird. Einige Server, z.B. WEBRick, unterstützen -Streaming nicht oder nur teilweise. Sollte der Server Streaming nicht -unterstützen, wird ein vollständiger Response-Body zurückgeschickt, sobald der -an `stream` weitergegebene Block abgearbeitet ist. Mit Shotgun funktioniert -Streaming z.B. überhaupt nicht. - -Ist der optionale Parameter `keep_open` aktiviert, wird beim gestreamten Objekt -`close` nicht aufgerufen und es ist einem überlassen dies an einem beliebigen -späteren Zeitpunkt nachholen. Die Funktion ist jedoch nur bei Event-gesteuerten -Serven wie Thin oder Rainbows möglich, andere Server werden trotzdem den Stream -beenden: - -```ruby -# Durchgehende Anfrage (long polling) - -set :server, :thin -connections = [] - -get '/subscribe' do - # Client-Registrierung beim Server, damit Events mitgeteilt werden können - stream(:keep_open) { |out| connections << out } - - # tote Verbindungen entfernen - connections.reject!(&:closed?) - - # Rückmeldung - "Angemeldet" -end - -post '/message' do - connections.each do |out| - # Den Client über eine neue Nachricht in Kenntnis setzen - # notify client that a new message has arrived - out << params[:message] << "\n" - - # Den Client zur erneuten Verbindung auffordern - out.close - end - - # Rückmeldung - "Mitteiling erhalten" -end -``` - -### Logger - -Im Geltungsbereich eines Request stellt die `logger` Helfer-Methode eine `Logger` -Instanz zur Verfügung: - -```ruby -get '/' do - logger.info "es passiert gerade etwas" - # ... -end -``` - -Der Logger übernimmt dabei automatisch alle im Rack-Handler eingestellten -Log-Vorgaben. Ist Loggen ausgeschaltet, gibt die Methode ein Leerobjekt zurück. -In den Routen und Filtern muss man sich also nicht weiter darum kümmern. - -Beachte, dass das Loggen standardmäßig nur für `Sinatra::Application` -voreingestellt ist. Wird über `Sinatra::Base` vererbt, muss es erst aktiviert -werden: - -```ruby -class MyApp < Sinatra::Base - configure :production, :development do - enable :logging - end -end -``` - -Damit auch keine Middleware das Logging aktivieren kann, muss die `logging` -Einstellung auf `nil` gesetzt werden. Das heißt aber auch, dass `logger` in -diesem Fall `nil` zurückgeben wird. Üblicherweise wird das eingesetzt, wenn ein -eigener Logger eingerichtet werden soll. Sinatra wird dann verwenden, was in -`env['rack.logger']` eingetragen ist. - -### Mime-Types - -Wenn `send_file` oder statische Dateien verwendet werden, kann es vorkommen, -dass Sinatra den Mime-Typ nicht kennt. Registriert wird dieser mit `mime_type` -per Dateiendung: - -```ruby -configure do - mime_type :foo, 'text/foo' -end -``` - -Es kann aber auch der `content_type`-Helfer verwendet werden: - -```ruby -get '/' do - content_type :foo - "foo foo foo" -end -``` - -### URLs generieren - -Zum Generieren von URLs sollte die `url`-Helfer-Methode genutzen werden, so z.B. -beim Einsatz von Haml: - -```ruby -%a{:href => url('/foo')} foo -``` - -Soweit vorhanden, wird Rücksicht auf Proxys und Rack-Router genommen. - -Diese Methode ist ebenso über das Alias `to` zu erreichen (siehe Beispiel unten). - -### Browser-Umleitung - -Eine Browser-Umleitung kann mithilfe der `redirect`-Helfer-Methode erreicht -werden: - -```ruby -get '/foo' do - redirect to('/bar') -end -``` - -Weitere Parameter werden wie Argumente der `halt`-Methode behandelt: - -```ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'Hier bist du falsch' -``` - -Ebenso leicht lässt sich ein Schritt zurück mit dem Alias `redirect back` -erreichen: - -```ruby -get '/foo' do - "mach was" -end - -get '/bar' do - mach_was - redirect back -end -``` - -Um Argumente an ein Redirect weiterzugeben, können sie entweder dem Query -übergeben: - -```ruby -redirect to('/bar?summe=42') -``` - -oder eine Session verwendet werden: - -```ruby -enable :sessions - -get '/foo' do - session[:secret] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secret] -end -``` - -### Cache einsetzen - -Ein sinnvolles Einstellen von Header-Daten ist die Grundlage für ein -ordentliches HTTP-Caching. - -Der Cache-Control-Header lässt sich ganz einfach einstellen: - -```ruby -get '/' do - cache_control :public - "schon gecached!" -end -``` - -Profitipp: Caching im before-Filter aktivieren - -```ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -``` - -Bei Verwendung der `expires`-Helfermethode zum Setzen des gleichnamigen Headers, -wird `Cache-Control` automatisch eigestellt: - -```ruby -before do - expires 500, :public, :must_revalidate -end -``` - -Um alles richtig zu machen, sollten auch `etag` oder `last_modified` verwendet -werden. Es wird empfohlen, dass diese Helfer aufgerufen werden **bevor** die -eigentliche Arbeit anfängt, da sie sofort eine Antwort senden, wenn der Client -eine aktuelle Version im Cache vorhält: - -```ruby -get '/article/:id' do - @article = Article.find params[:id] - last_modified @article.updated_at - etag @article.sha1 - erb :article -end -``` - -ebenso ist es möglich einen -[schwachen ETag](http://de.wikipedia.org/wiki/HTTP_ETag) zu verwenden: - -```ruby -etag @article.sha1, :weak -``` - -Diese Helfer führen nicht das eigentliche Caching aus, sondern geben die dafür -notwendigen Informationen an den Cache weiter. Für schnelle Reverse-Proxy -Cache-Lösungen bietet sich z.B. -[rack-cache](https://github.com/rtomayko/rack-cache) an: - -```ruby -require "rack/cache" -require "sinatra" - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hello" -end -``` - -Um den `Cache-Control`-Header mit Informationen zu versorgen, verwendet man die -`:static_cache_control`-Einstellung (s.u.). - -Nach RFC 2616 sollte sich die Anwendung anders verhalten, wenn ein If-Match oder -ein If-None_match Header auf `*` gesetzt wird in Abhängigkeit davon, ob die -Resource bereits existiert. Sinatra geht davon aus, dass Ressourcen bei sicheren -Anfragen (z.B. bei get oder Idempotenten Anfragen wie put) bereits existieren, -wobei anderen Ressourcen (besipielsweise bei post), als neue Ressourcen -behandelt werden. Dieses Verhalten lässt sich mit der `:new_resource` Option -ändern: - -```ruby -get '/create' do - etag '', :new_resource => true - Article.create - erb :new_article -end -``` - -Soll das schwache ETag trotzdem verwendet werden, verwendet man die `:kind` -Option: - -```ruby -etag '', :new_resource => true, :kind => :weak -``` - -### Dateien versenden - -Zum Versenden von Dateien kann die `send_file`-Helfer-Methode verwendet werden: - -```ruby -get '/' do - send_file 'foo.png' -end -``` - -Für `send_file` stehen einige Hash-Optionen zur Verfügung: - -```ruby -send_file 'foo.png', :type => :jpg -``` - -
-
filename
-
Dateiname als Response. Standardwert ist der eigentliche Dateiname.
- -
last_modified
-
Wert für den Last-Modified-Header, Standardwert ist mtime der - Datei.
- -
type
-
Content-Type, der verwendet werden soll. Wird, wenn nicht angegeben, von - der Dateiendung abgeleitet.
- -
disposition
-
Verwendet für Content-Disposition. Mögliche Werte sind: nil - (Standard), :attachment und :inline.
- -
length
-
Content-Length-Header. Standardwert ist die Dateigröße.
-
- -Soweit vom Rack-Handler unterstützt, werden neben der Übertragung über den -Ruby-Prozess auch andere Möglichkeiten genutzt. Bei Verwendung der -`send_file`-Helfer-Methode kümmert sich Sinatra selbstständig um die -Range-Requests. - -### Das Request-Objekt - -Auf das `request`-Objekt der eigehenden Anfrage kann vom Anfrage-Scope aus -zugegriffen werden: - -```ruby -# App läuft unter http://example.com/example -get '/foo' do - t = %w[text/css text/html application/javascript] - request.accept # ['text/html', '*/*'] - request.accept? 'text/xml' # true - request.preferred_type(t) # 'text/html' - request.body # Request-Body des Client (siehe unten) - request.scheme # "http" - request.script_name # "/example" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # Länge des request.body - request.media_type # Medientypus von request.body - request.host # "example.com" - request.get? # true (ähnliche Methoden für andere Verben) - request.form_data? # false - request["irgendein_param"] # Wert von einem Parameter; [] ist die Kurzform für den params Hash - request.referrer # Der Referrer des Clients oder '/' - request.user_agent # User-Agent (verwendet in der :agent Bedingung) - request.cookies # Hash des Browser-Cookies - request.xhr? # Ist das hier ein Ajax-Request? - request.url # "http://example.com/example/foo" - request.path # "/example/foo" - request.ip # IP-Adresse des Clients - request.secure? # false (true wenn SSL) - request.forwarded? # true (Wenn es hinter einem Reverse-Proxy verwendet wird) - request.env # vollständiger env-Hash von Rack übergeben -end -``` - -Manche Optionen, wie etwa `script_name` oder `path_info`, sind auch -schreibbar: - -```ruby -before { request.path_info = "/" } - -get "/" do - "Alle Anfragen kommen hier an!" -end -``` - -Der `request.body` ist ein IO- oder StringIO-Objekt: - -```ruby -post "/api" do - request.body.rewind # falls schon jemand davon gelesen hat - daten = JSON.parse request.body.read - "Hallo #{daten['name']}!" -end -``` - -### Anhänge - -Damit der Browser erkennt, dass ein Response gespeichert und nicht im Browser -angezeigt werden soll, kann der `attachment`-Helfer verwendet werden: - -```ruby -get '/' do - attachment - "Speichern!" -end -``` - -Ebenso kann eine Dateiname als Parameter hinzugefügt werden: - -```ruby -get '/' do - attachment "info.txt" - "Speichern!" -end -``` - -### Umgang mit Datum und Zeit - -Sinatra bietet eine `time_for`-Helfer-Methode, die aus einem gegebenen Wert ein -Time-Objekt generiert. Ebenso kann sie nach `DateTime`, `Date` und ähnliche -Klassen konvertieren: - -```ruby -get '/' do - pass if Time.now > time_for('Dec 23, 2012') - "noch Zeit" -end -``` - -Diese Methode wird intern für +expires, `last_modiefied` und ihresgleichen -verwendet. Mit ein paar Handgriffen lässt sich diese Methode also in ihrem -Verhalten erweitern, indem man `time_for` in der eigenen Applikation -überschreibt: - -```ruby -helpers do - def time_for(value) - case value - when :yesterday then Time.now - 24*60*60 - when :tomorrow then Time.now + 24*60*60 - else super - end - end -end - -get '/' do - last_modified :yesterday - expires :tomorrow - "Hallo" -end -``` - -### Nachschlagen von Template-Dateien - -Die `find_template`-Helfer-Methode wird genutzt, um Template-Dateien zum Rendern -aufzufinden: - -```ruby -find_template settings.views, 'foo', Tilt[:haml] do |file| - puts "könnte diese hier sein: #{file}" -end -``` - -Das ist zwar nicht wirklich brauchbar, aber wenn man sie überschreibt, kann sie -nützlich werden, um eigene Nachschlage-Mechanismen einzubauen. Zum Beispiel -dann, wenn mehr als nur ein view-Verzeichnis verwendet werden soll: - -```ruby -set :views, ['views', 'templates'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -``` - -Ein anderes Beispiel wäre, verschiedene Vereichnisse für verschiedene Engines -zu verwenden: - -```ruby -set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:default] - super(folder, name, engine, &block) - end -end -``` - -Ebensogut könnte eine Extension aber auch geschrieben und mit anderen geteilt -werden! - -Beachte, dass `find_template` nicht prüft, ob eine Datei tatsächlich existiert. -Es wird lediglich der angegebene Block aufgerufen und nach allen möglichen -Pfaden gesucht. Das ergibt kein Performance-Problem, da `render` `block` -verwendet, sobald eine Datei gefunden wurde. Ebenso werden Template-Pfade samt -Inhalt gecached, solange nicht im Entwicklungsmodus gearbeitet wird. Das sollte -im Hinterkopf behalten werden, wenn irgendwelche verrückten Methoden -zusammenbastelt werden. - -### Konfiguration - -Wird einmal beim Starten in jedweder Umgebung ausgeführt: - -```ruby -configure do - # setze eine Option - set :option, 'wert' - - # setze mehrere Optionen - set :a => 1, :b => 2 - - # das gleiche wie `set :option, true` - enable :option - - # das gleiche wie `set :option, false` - disable :option - - # dynamische Einstellungen mit Blöcken - set(:css_dir) { File.join(views, 'css') } -end -``` - -Läuft nur, wenn die Umgebung (RACK_ENV-Umgebungsvariable) auf `:production` -gesetzt ist: - -```ruby -configure :production do - ... -end -``` - -Läuft nur, wenn die Umgebung auf `:production` oder auf `:test` gesetzt ist: - -```ruby -configure :production, :test do - ... -end -``` - -Diese Einstellungen sind über `settings` erreichbar: - -```ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -``` - -#### Einstellung des Angriffsschutzes - -Sinatra verwendet -[Rack::Protection](https://github.com/rkh/rack-protection#readme), um die -Anwendung vor häufig vorkommenden Angriffen zu schützen. Diese Voreinstellung -lässt sich selbstverständlich deaktivieren, der damit verbundene -Geschwindigkeitszuwachs steht aber in keinem Verhätnis zu den möglichen -Risiken. - -```ruby -disable :protection -``` - -Um einen bestimmten Schutzmechanismus zu deaktivieren, fügt man `protection` -einen Hash mit Optionen hinzu: - -```ruby -set :protection, :except => :path_traversal -``` - -Neben Strings akzeptiert `:except` auch Arrays, um gleich mehrere -Schutzmechanismen zu deaktivieren: - -```ruby -set :protection, :except => [:path_traversal, :session_hijacking] -``` - -#### Mögliche Einstellungen - -
-
absolute_redirects
-
Wenn ausgeschaltet, wird Sinatra relative Redirects zulassen. Jedoch ist - Sinatra dann nicht mehr mit RFC 2616 (HTTP 1.1) konform, das nur absolute - Redirects zulässt. Sollte eingeschaltet werden, wenn die Applikation hinter - einem Reverse-Proxy liegt, der nicht ordentlich eingerichtet ist. Beachte, - dass die url-Helfer-Methode nach wie vor absolute URLs erstellen - wird, es sei denn, es wird als zweiter Parameter false angegeben. - Standardmäßig nicht aktiviert.
- -
add_charsets
-
Mime-Types werden hier automatisch der Helfer-Methode - content_type zugeordnet. Es empfielt sich, Werte hinzuzufügen statt - sie zu überschreiben: settings.add_charsets << "application/foobar" -
- -
app_file
-
Pfad zur Hauptdatei der Applikation. Wird verwendet, um das Wurzel-, - Inline-, View- und öffentliche Verzeichnis des Projekts festzustellen.
- -
bind
-
IP-Address, an die gebunden wird (Standardwert: 0.0.0.0 - oder localhost). Wird nur für den eingebauten Server - verwendet.
- -
default_encoding
-
Das Encoding, falls keines angegeben wurde. Standardwert ist - "utf-8".
- -
dump_errors
-
Fehler im Log anzeigen.
- -
environment
-
Momentane Umgebung. Standardmäßig auf content_type oder - "development" eingestellt, soweit ersteres nicht vorhanden.
- -
logging
-
Den Logger verwenden.
- -
lock
-
Jeder Request wird gelocked. Es kann nur ein Request pro Ruby-Prozess - gleichzeitig verarbeitet werden. Eingeschaltet, wenn die Applikation - threadsicher ist. Standardmäßig nicht aktiviert.
- -
method_override
-
Verwende _method, um put/delete-Formulardaten in Browsern zu - verwenden, die dies normalerweise nicht unterstützen.
- -
port
-
Port für die Applikation. Wird nur im internen Server verwendet.
- -
prefixed_redirects
-
Entscheidet, ob request.script_name in Redirects eingefügt wird - oder nicht, wenn kein absoluter Pfad angegeben ist. Auf diese Weise verhält - sich redirect '/foo' so, als wäre es ein redirect - to('/foo'). Standardmäßig nicht aktiviert.
- -
protection
-
Legt fest, ob der Schutzmechanismus für häufig Vorkommende Webangriffe - auf Webapplikationen aktiviert wird oder nicht. Weitere Informationen im - vorhergehenden Abschnitt.
- -
public_folder
-
Das öffentliche Verzeichnis, aus dem Daten zur Verfügung gestellt werden - können. Wird nur dann verwendet, wenn statische Daten zur Verfügung gestellt - werden können (s.u. static Option). Leitet sich von der - app_file Einstellung ab, wenn nicht gesetzt.
- -
public_dir
-
Alias für public_folder, s.o.
- -
reload_templates
-
Im development-Modus aktiviert.
- -
root
-
Wurzelverzeichnis des Projekts. Leitet sich von der app_file - Einstellung ab, wenn nicht gesetzt.
- -
raise_errors
-
Einen Ausnahmezustand aufrufen. Beendet die Applikation. Ist automatisch - aktiviert, wenn die Umgebung auf "test" eingestellt ist. Ansonsten - ist diese Option deaktiviert.
- -
run
-
Wenn aktiviert, wird Sinatra versuchen, den Webserver zu starten. Nicht - verwenden, wenn Rackup oder anderes verwendet werden soll.
- -
running
-
Läuft der eingebaute Server? Diese Einstellung nicht ändern!
- -
server
-
Server oder Liste von Servern, die als eingebaute Server zur Verfügung - stehen. Die Reihenfolge gibt die Priorität vor, die Voreinstellung hängt von - der verwendenten Ruby Implementierung ab.
- -
sessions
-
Sessions auf Cookiebasis mittels - Rack::Session::Cookieaktivieren. Für weitere Infos bitte in der - Sektion ‘Sessions verwenden’ nachschauen.
- -
show_exceptions
-
Bei Fehlern einen Stacktrace im Browseranzeigen. Ist automatisch - aktiviert, wenn die Umgebung auf "development" eingestellt ist. - Ansonsten ist diese Option deaktiviert. Kann auch auf :after_handler - gestellt werden, um eine anwendungsspezifische Fehlerbehandlung auszulösen, - bevor der Fehlerverlauf im Browser angezeigt wird.
- -
static
-
Entscheidet, ob Sinatra statische Dateien zur Verfügung stellen soll oder - nicht. Sollte nicht aktiviert werden, wenn ein Server verwendet wird, der - dies auch selbstständig erledigen kann. Deaktivieren wird die Performance - erhöhen. Standardmäßig aktiviert.
- -
static_cache_control
-
Wenn Sinatra statische Daten zur Verfügung stellt, können mit dieser - Einstellung die Cache-Control Header zu den Responses hinzugefügt - werden. Die Einstellung verwendet dazu die cache_control - Helfer-Methode. Standardmäßig deaktiviert. Ein Array wird verwendet, um - mehrere Werte gleichzeitig zu übergeben: set :static_cache_control, - [:public, :max_age => 300]
- -
threaded
-
Wird es auf true gesetzt, wird Thin aufgefordert - EventMachine.defer zur Verarbeitung des Requests einzusetzen.
- -
views
-
Verzeichnis der Views. Leitet sich von der app_file Einstellung - ab, wenn nicht gesetzt.
- -
x_cascade
-
Einstellung, ob der X-Cascade Header bei fehlender Route gesetzt wird oder - nicht. Standardeinstellung ist true.
-
- -## Umgebungen - -Es gibt drei voreingestellte Umgebungen in Sinatra: `"development"`, -`"production"` und `"test"`. Umgebungen können über die `RACK_ENV` -Umgebungsvariable gesetzt werden. Die Standardeinstellung ist `"development"`. -In diesem Modus werden alle Templates zwischen Requests neu geladen. Dazu gibt -es besondere Fehlerseiten für 404 Stati und Fehlermeldungen. In `"production"` -und `"test"` werden Templates automatisch gecached. - -Um die Anwendung in einer anderen Umgebung auszuführen kann man die `-e` -Option verwenden: - -```shell -ruby my_app.rb -e [ENVIRONMENT] -``` - -In der Anwendung kann man die die Methoden `development?`, `test?` und -`production?` verwenden, um die aktuelle Umgebung zu erfahren. - -## Fehlerbehandlung - -Error-Handler laufen in demselben Kontext wie Routen und Filter, was bedeutet, -dass alle Goodies wie `haml`, `erb`, `halt`, etc. verwendet werden können. - -### Nicht gefunden - -Wenn eine `Sinatra::NotFound`-Exception geworfen wird oder der Statuscode 404 -ist, wird der `not_found`-Handler ausgeführt: - -```ruby -not_found do - 'Seite kann nirgendwo gefunden werden.' -end -``` - -### Fehler - -Der `error`-Handler wird immer ausgeführt, wenn eine Exception in einem -Routen-Block oder in einem Filter geworfen wurde. Die Exception kann über die -`sinatra.error`-Rack-Variable angesprochen werden: - -```ruby -error do - 'Entschuldige, es gab einen hässlichen Fehler - ' + env['sinatra.error'].name -end -``` - -Benutzerdefinierte Fehler: - -```ruby -error MeinFehler do - 'Au weia, ' + env['sinatra.error'].message -end -``` - -Dann, wenn das passiert: - -```ruby -get '/' do - raise MeinFehler, 'etwas Schlimmes ist passiert' -end -``` - -bekommt man dieses: - -```shell -Au weia, etwas Schlimmes ist passiert -``` - -Alternativ kann ein Error-Handler auch für einen Status-Code definiert werden: - -```ruby -error 403 do - 'Zugriff verboten' -end - -get '/geheim' do - 403 -end -``` - -Oder ein Status-Code-Bereich: - -```ruby -error 400..510 do - 'Hallo?' -end -``` - -Sinatra setzt verschiedene `not_found`- und `error`-Handler in der -Development-Umgebung ein, um hilfreiche Debugging Informationen und Stack Traces -anzuzeigen. - -## Rack-Middleware - -Sinatra baut auf [Rack](http://rack.rubyforge.org/), einem minimalistischen -Standard-Interface für Ruby-Webframeworks. Eines der interessantesten Features -für Entwickler ist der Support von Middlewares, die zwischen den Server und -die Anwendung geschaltet werden und so HTTP-Request und/oder Antwort -überwachen und/oder manipulieren können. - -Sinatra macht das Erstellen von Middleware-Verkettungen mit der -Top-Level-Methode `use` zu einem Kinderspiel: - -```ruby -require 'sinatra' -require 'meine_middleware' - -use Rack::Lint -use MeineMiddleware - -get '/hallo' do - 'Hallo Welt' -end -``` - -Die Semantik von `use` entspricht der gleichnamigen Methode der -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html)-DSL -(meist verwendet in Rackup-Dateien). Ein Beispiel dafür ist, dass die -`use`-Methode mehrere/verschiedene Argumente und auch Blöcke entgegennimmt: - -```ruby -use Rack::Auth::Basic do |username, password| - username == 'admin' && password == 'geheim' -end -``` - -Rack bietet eine Vielzahl von Standard-Middlewares für Logging, Debugging, -URL-Routing, Authentifizierung und Session-Verarbeitung. Sinatra verwendet -viele von diesen Komponenten automatisch, abhängig von der Konfiguration. So -muss `use` häufig nicht explizit verwendet werden. - -Hilfreiche Middleware gibt es z.B. hier: -[rack](https://github.com/rack/rack/tree/master/lib/rack), -[rack-contrib](https://github.com/rack/rack-contrib#readme), -oder im [Rack wiki](https://github.com/rack/rack/wiki/List-of-Middleware). - -## Testen - -Sinatra-Tests können mit jedem auf Rack aufbauendem Test-Framework geschrieben -werden. [Rack::Test](http://rdoc.info/github/brynary/rack-test/master/frames) -wird empfohlen: - -```ruby -require 'my_sinatra_app' -require 'test/unit' -require 'rack/test' - -class MyAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_my_default - get '/' - assert_equal 'Hallo Welt!', last_response.body - end - - def test_with_params - get '/meet', :name => 'Frank' - assert_equal 'Hallo Frank!', last_response.body - end - - def test_with_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "Du verwendest Songbird!", last_response.body - end -end -``` - -Hinweis: Wird Sinatra modular verwendet, muss Sinatra::Application mit -dem Namen der Applikations-Klasse ersetzt werden. - -## Sinatra::Base - Middleware, Bibliotheken und modulare Anwendungen - -Das Definieren einer Top-Level-Anwendung funktioniert gut für -Mikro-Anwendungen, hat aber Nachteile, wenn wiederverwendbare Komponenten wie -Middleware, Rails Metal, einfache Bibliotheken mit Server-Komponenten oder -auch Sinatra-Erweiterungen geschrieben werden sollen. - -Das Top-Level geht von einer Konfiguration für eine Mikro-Anwendung aus (wie -sie z.B. bei einer einzelnen Anwendungsdatei, `./public` und `./views` Ordner, -Logging, Exception-Detail-Seite, usw.). Genau hier kommt `Sinatra::Base` ins -Spiel: - -```ruby -require 'sinatra/base' - -class MyApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Hallo Welt!' - end -end -``` - -Die MyApp-Klasse ist eine unabhängige Rack-Komponente, die als Middleware, -Endpunkt oder via Rails Metal verwendet werden kann. Verwendet wird sie durch -`use` oder `run` von einer Rackup-`config.ru`-Datei oder als Server-Komponente -einer Bibliothek: - -```ruby -MyApp.run! :host => 'localhost', :port => 9090 -``` - -Die Methoden der `Sinatra::Base`-Subklasse sind genau dieselben wie die der -Top-Level-DSL. Die meisten Top-Level-Anwendungen können mit nur zwei -Veränderungen zu `Sinatra::Base` konvertiert werden: - -* Die Datei sollte `require 'sinatra/base'` anstelle von `require - 'sinatra/base'` aufrufen, ansonsten werden alle von Sinatras DSL-Methoden - in den Top-Level-Namespace importiert. -* Alle Routen, Error-Handler, Filter und Optionen der Applikation müssen in - einer Subklasse von `Sinatra::Base` definiert werden. - - -`Sinatra::Base` ist ein unbeschriebenes Blatt. Die meisten Optionen sind per -Standard deaktiviert. Das betrifft auch den eingebauten Server. Siehe -[Optionen und Konfiguration](http://sinatra.github.com/configuration.html) für -Details über mögliche Optionen. - -### Modularer vs. klassischer Stil - -Entgegen häufiger Meinungen gibt es nichts gegen den klassischen Stil -einzuwenden. Solange es die Applikation nicht beeinträchtigt, besteht kein -Grund, eine modulare Applikation zu erstellen. - -Der größte Nachteil der klassischen Sinatra Anwendung gegenüber einer -modularen ist die Einschränkung auf eine Sinatra Anwendung pro Ruby-Prozess. -Sollen mehrere zum Einsatz kommen, muss auf den modularen Stil umgestiegen -werden. Dabei ist es kein Problem klassische und modulare Anwendungen -miteinander zu vermischen. - -Bei einem Umstieg, sollten einige Unterschiede in den Einstellungen beachtet -werden: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SzenarioClassicModular
app_fileSinatra ladende DateiSinatra::Base subklassierende Datei
run$0 == app_filefalse
loggingtruefalse
method_overridetruefalse
inline_templatestruefalse
statictruefalse
- -### Eine modulare Applikation bereitstellen - -Es gibt zwei übliche Wege, eine modulare Anwendung zu starten. Zum einen über -`run!`: - -```ruby -# mein_app.rb -require 'sinatra/base' - -class MeinApp < Sinatra::Base - # ... Anwendungscode hierhin ... - - # starte den Server, wenn die Ruby-Datei direkt ausgeführt wird - run! if app_file == $0 -end -``` - -Starte mit: - -```shell -ruby mein_app.rb -``` - -Oder über eine `config.ru`-Datei, die es erlaubt, einen beliebigen -Rack-Handler zu verwenden: - -```ruby -# config.ru (mit rackup starten) -require './mein_app' -run MeineApp -``` - -Starte: - -```shell -rackup -p 4567 -``` - -### Eine klassische Anwendung mit einer config.ru verwenden - -Schreibe eine Anwendungsdatei: - -```ruby -# app.rb -require 'sinatra' - -get '/' do - 'Hallo Welt!' -end -``` - -sowie eine dazugehörige `config.ru`-Datei: - -```ruby -require './app' -run Sinatra::Application -``` - -### Wann sollte eine config.ru-Datei verwendet werden? - -Anzeichen dafür, dass eine `config.ru`-Datei gebraucht wird: - -* Es soll ein anderer Rack-Handler verwendet werden (Passenger, Unicorn, - Heroku, ...). -* Es gibt mehr als nur eine Subklasse von `Sinatra::Base`. -* Sinatra soll als Middleware verwendet werden, nicht als Endpunkt. - - -**Es gibt keinen Grund, eine `config.ru`-Datei zu verwenden, nur weil eine -Anwendung im modularen Stil betrieben werden soll. Ebenso wird keine Anwendung -mit modularem Stil benötigt, um eine `config.ru`-Datei zu verwenden.** - -### Sinatra als Middleware nutzen - -Es ist nicht nur möglich, andere Rack-Middleware mit Sinatra zu nutzen, es -kann außerdem jede Sinatra-Anwendung selbst als Middleware vor jeden -beliebigen Rack-Endpunkt gehangen werden. Bei diesem Endpunkt muss es sich -nicht um eine andere Sinatra-Anwendung handeln, es kann jede andere -Rack-Anwendung sein (Rails/Ramaze/Camping/...): - -```ruby -require 'sinatra/base' - -class LoginScreen < Sinatra::Base - enable :sessions - - get('/login') { haml :login } - - post('/login') do - if params[:name] == 'admin' && params[:password] == 'admin' - session['user_name'] = params[:name] - else - redirect '/login' - end - end -end - -class MyApp < Sinatra::Base - # Middleware wird vor Filtern ausgeführt - use LoginScreen - - before do - unless session['user_name'] - halt "Zugriff verweigert, bitte einloggen." - end - end - - get('/') { "Hallo #{session['user_name']}." } -end -``` - -### Dynamische Applikationserstellung - -Manche Situationen erfordern die Erstellung neuer Applikationen zur Laufzeit, -ohne dass sie einer Konstanten zugeordnet werden. Dies lässt sich mit -`Sinatra.new` erreichen: - -```ruby -require 'sinatra/base' -my_app = Sinatra.new { get('/') { "hallo" } } -my_app.run! -``` - -Die Applikation kann mit Hilfe eines optionalen Parameters erstellt werden: - -```ruby -# config.ru -require 'sinatra/base' - -controller = Sinatra.new do - enable :logging - helpers MyHelpers -end - -map('/a') do - run Sinatra.new(controller) { get('/') { 'a' } } -end - -map('/b') do - run Sinatra.new(controller) { get('/') { 'b' } } -end -``` - -Das ist besonders dann interessant, wenn Sinatra-Erweiterungen getestet werden -oder Sinatra in einer Bibliothek Verwendung findet. - -Ebenso lassen sich damit hervorragend Sinatra-Middlewares erstellen: - -```ruby -require 'sinatra/base' - -use Sinatra do - get('/') { ... } -end - -run RailsProject::Application -``` - -## Geltungsbereich und Bindung - -Der Geltungsbereich (Scope) legt fest, welche Methoden und Variablen zur -Verfügung stehen. - -### Anwendungs- oder Klassen-Scope - -Jede Sinatra-Anwendung entspricht einer `Sinatra::Base`-Subklasse. Falls die -Top- Level-DSL verwendet wird (`require 'sinatra'`), handelt es sich um -`Sinatra::Application`, andernfalls ist es jene Subklasse, die explizit -angelegt wurde. Auf Klassenebene stehen Methoden wie `get` oder `before` zur -Verfügung, es gibt aber keinen Zugriff auf das `request`-Object oder die -`session`, da nur eine einzige Klasse für alle eingehenden Anfragen genutzt -wird. - -Optionen, die via `set` gesetzt werden, sind Methoden auf Klassenebene: - -```ruby -class MyApp < Sinatra::Base - # Hey, ich bin im Anwendungsscope! - set :foo, 42 - foo # => 42 - - get '/foo' do - # Hey, ich bin nicht mehr im Anwendungs-Scope! - end -end -``` - -Im Anwendungs-Scope befindet man sich: - -* In der Anwendungs-Klasse. -* In Methoden, die von Erweiterungen definiert werden. -* Im Block, der an `helpers` übergeben wird. -* In Procs und Blöcken, die an `set` übergeben werden. -* Der an `Sinatra.new` übergebene Block - - -Auf das Scope-Objekt (die Klasse) kann wie folgt zugegriffen werden: - -* Über das Objekt, das an den `configure`-Block übergeben wird (`configure { - |c| ... }`). -* `settings` aus den anderen Scopes heraus. - - -### Anfrage- oder Instanz-Scope - -Für jede eingehende Anfrage wird eine neue Instanz der Anwendungs-Klasse -erstellt und alle Handler in diesem Scope ausgeführt. Aus diesem Scope heraus -kann auf `request` oder `session` zugegriffen und Methoden wie `erb` oder -`haml` aufgerufen werden. Außerdem kann mit der `settings`-Method auf den -Anwendungs-Scope zugegriffen werden: - -```ruby -class MyApp < Sinatra::Base - # Hey, ich bin im Anwendungs-Scope! - get '/neue_route/:name' do - # Anfrage-Scope für '/neue_route/:name' - @value = 42 - - settings.get "/#{params[:name]}" do - # Anfrage-Scope für "/#{params[:name]}" - @value # => nil (nicht dieselbe Anfrage) - end - - "Route definiert!" - end -end -``` - -Im Anfrage-Scope befindet man sich: - -* In get, head, post, put, delete, options, patch, link und unlink Blöcken -* In before und after Filtern -* In Helfer-Methoden -* In Templates - - -### Delegation-Scope - -Vom Delegation-Scope aus werden Methoden einfach an den Klassen-Scope -weitergeleitet. Dieser verhält sich jedoch nicht 100%ig wie der Klassen-Scope, -da man nicht die Bindung der Klasse besitzt: Nur Methoden, die explizit als -delegierbar markiert wurden, stehen hier zur Verfügung und es kann nicht auf -die Variablen des Klassenscopes zugegriffen werden (mit anderen Worten: es -gibt ein anderes `self`). Weitere Delegationen können mit -`Sinatra::Delegator.delegate :methoden_name` hinzugefügt werden. - -Im Delegation-Scop befindet man sich: - -* Im Top-Level, wenn `require 'sinatra'` aufgerufen wurde. -* In einem Objekt, das mit dem `Sinatra::Delegator`-Mixin erweitert wurde. - - -Schau am besten im Code nach: Hier ist [Sinatra::Delegator -mixin](http://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1064 -) definiert und wird in den [globalen Namespace -eingebunden](http://github.com/sinatra/sinatra/blob/master/lib/sinatra/main.rb - -## Kommandozeile - -Sinatra-Anwendungen können direkt von der Kommandozeile aus gestartet werden: - -```shell -ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-h HOST] [-s HANDLER] -``` - -Die Optionen sind: - -``` --h # Hilfe --p # Port setzen (Standard ist 4567) --h # Host setzen (Standard ist 0.0.0.0) --e # Umgebung setzen (Standard ist development) --s # Rack-Server/Handler setzen (Standard ist thin) --x # Mutex-Lock einschalten (Standard ist off) -``` - -## Systemanforderungen - -Die folgenden Versionen werden offiziell unterstützt: - -
-
Ruby 1.8.7
-
1.8.7 wird vollständig unterstützt, ein Wechsel zu JRuby oder Rubinius wird -aber empfohlen. Ruby 1.8.7 wird noch bis Sinatra 2.0 unterstützt werden. Frühere -Versionen von Ruby sind nicht kompatibel mit Sinatra.
- -
Ruby 1.9.2
-
1.9.2 wird mindestens bis Sinatra 1.5 voll unterstützt. Version 1.9.2p0 -sollte nicht verwendet werden, da unter Sinatra immer wieder Segfaults -auftreten.
- -
Ruby 1.9.3
-
1.9.3 wird vollständig unterstützt und empfohlen. Achtung, bei einem -Upgrade von einer früheren Version von Ruby zu Ruby 1.9.3 werden alle Sessions -ungültig. Ruby 1.9.3 wird bis Sinatra 2.0 unterstützt werden.
- -
Rubinius
-
Rubinius (Version >= 2.x) wird offiziell unterstützt. Es wird empfohlen, den -Puma Server zu installieren (gem install puma -)
- -
JRuby
-
Aktuelle JRuby Versionen werden offiziell unterstützt. Es wird empfohlen, -keine C-Erweiterungen zu verwenden und als Server Trinidad zu verwenden -(gem install trinidad).
-
- -Die nachfolgend aufgeführten Ruby-Implementierungen werden offiziell nicht von -Sinatra unterstützt, funktionieren aber normalerweise: - -* Ruby Enterprise Edition -* Ältere Versionen von JRuby und Rubinius -* MacRuby (gem install control_tower wird empfohlen), Maglev, IronRuby -* Ruby 1.9.0 und 1.9.1 - -Nicht offiziell unterstützt bedeutet, dass wenn Sachen nicht funktionieren, -wir davon ausgehen, dass es nicht an Sinatra sondern an der jeweiligen -Implementierung liegt. - -Im Rahmen unserer CI (Kontinuierlichen Integration) wird bereits ruby-head -(das kommende Ruby 2.1.0) mit eingebunden. Es kann davon ausgegangen -werden, dass Sinatra Ruby 2.1.0 vollständig unterstützen wird. - -Sinatra sollte auf jedem Betriebssystem laufen, dass einen funktionierenden -Ruby-Interpreter aufweist. - -Sinatra läuft aktuell nicht unter Cardinal, SmallRuby, BlueRuby oder Ruby <= 1.8.7. - -## Der neuste Stand (The Bleeding Edge) - -Um auf dem neusten Stand zu bleiben, kann der Master-Branch verwendet werden. -Er sollte recht stabil sein. Ebenso gibt es von Zeit zu Zeit prerelease Gems, -die so installiert werden: - -```shell -gem install sinatra --pre -``` - -### Mit Bundler - -Wenn die Applikation mit der neuesten Version von Sinatra und -[Bundler](http://gembundler.com/) genutzt werden soll, empfehlen wir den -nachfolgenden Weg. - -Soweit Bundler noch nicht installiert ist: - -```shell -gem install bundler -``` - -Anschließend wird eine `Gemfile`-Datei im Projektverzeichnis mit folgendem -Inhalt erstellt: - -```ruby -source :rubygems -gem 'sinatra', :git => "git://github.com/sinatra/sinatra.git" - -# evtl. andere Abhängigkeiten -gem 'haml' # z.B. wenn du Haml verwendest... -gem 'activerecord', '~> 3.0' # ...oder ActiveRecord 3.x -``` - -Beachte: Hier sollten alle Abhängigkeiten eingetragen werden. Sinatras eigene, -direkte Abhängigkeiten (Tilt und Rack) werden von Bundler automatisch aus dem -Gemfile von Sinatra hinzugefügt. - -Jetzt kannst du deine Applikation starten: - -```shell -bundle exec ruby myapp.rb -``` - -### Eigenes Repository -Um auf dem neuesten Stand von Sinatras Code zu sein, kann eine lokale Kopie -angelegt werden. Gestartet wird in der Anwendung mit dem `sinatra/lib`-Ordner -im `LOAD_PATH`: - -```shell -cd myapp -git clone git://github.com/sinatra/sinatra.git -ruby -Isinatra/lib myapp.rb -``` - -Alternativ kann der `sinatra/lib`-Ordner zum `LOAD_PATH` in der Anwendung -hinzugefügt werden: - -```ruby -$LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib' -require 'rubygems' -require 'sinatra' - -get '/ueber' do - "Ich laufe auf Version " + Sinatra::VERSION -end -``` - -Um Sinatra-Code von Zeit zu Zeit zu aktualisieren: - -```shell -cd myproject/sinatra -git pull -``` - -### Gem erstellen - -Aus der eigenen lokalen Kopie kann nun auch ein globales Gem gebaut werden: - -```shell -git clone git://github.com/sinatra/sinatra.git -cd sinatra -rake sinatra.gemspec -rake install -``` - -Falls Gems als Root installiert werden sollen, sollte die letzte Zeile -folgendermaßen lauten: - -```shell -sudo rake install -``` - -## Versions-Verfahren - -Sinatra folgt dem sogenannten [Semantic Versioning](http://semver.org/), d.h. -SemVer und SemVerTag. - -## Mehr - -* [Projekt-Website](http://sinatra.github.com/) - Ergänzende Dokumentation, - News und Links zu anderen Ressourcen. -* [Mitmachen](http://sinatra.github.com/contributing.html) - Einen Fehler - gefunden? Brauchst du Hilfe? Hast du einen Patch? -* [Issue-Tracker](http://github.com/sinatra/sinatra/issues) -* [Twitter](http://twitter.com/sinatra) -* [Mailing-Liste](http://groups.google.com/group/sinatrarb) -* [#sinatra](irc://chat.freenode.net/#sinatra) auf http://freenode.net Es - gibt dort auch immer wieder deutschsprachige Entwickler, die gerne weiterhelfen. -* [Sinatra Book](http://sinatra-book.gittr.com) Kochbuch Tutorial -* [Sinatra Recipes](http://recipes.sinatrarb.com/) Sinatra-Rezepte aus der - Community -* API Dokumentation für die [aktuelle - Version](http://rubydoc.info/gems/sinatra) oder für - [HEAD](http://rubydoc.info/github/sinatra/sinatra) auf http://rubydoc.info -* [CI Server](http://travis-ci.org/sinatra/sinatra) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.es.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.es.md deleted file mode 100644 index 4aa8716..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.es.md +++ /dev/null @@ -1,2786 +0,0 @@ -# Sinatra - -*Atención: Este documento es una traducción de la versión en inglés y puede estar desactualizado.* - -Sinatra es un -[DSL](http://es.wikipedia.org/wiki/Lenguaje_específico_del_dominio) para -crear aplicaciones web rápidamente en Ruby con un mínimo esfuerzo: - -``` ruby -# miapp.rb -require 'sinatra' - -get '/' do - 'Hola mundo!' -end -``` - -Instalar la gema y correr la aplicación con: - -``` shell -gem install sinatra -ruby miapp.rb -``` - -Ver en . - -Se recomienda ejecutar `gem install thin`, porque Sinatra lo utilizará si está disponible. - -## Rutas - -En Sinatra, una ruta es un método HTTP junto a un patrón de un URL. -Cada ruta está asociada a un bloque: - -``` ruby -get '/' do - .. mostrar algo .. -end - -post '/' do - .. crear algo .. -end - -put '/' do - .. reemplazar algo .. -end - -patch '/' do - .. modificar algo .. -end - -delete '/' do - .. aniquilar algo .. -end - -options '/' do - .. informar algo .. -end - -link '/' do - .. afiliar a algo .. -end - -unlink '/' do - .. separar algo .. -end - -``` - -Las rutas son comparadas en el orden en el que son definidas. La primera ruta -que coincide con la petición es escogida. - -Los patrones de las rutas pueden incluir parámetros nombrados, accesibles a -través del hash `params`: - -``` ruby -get '/hola/:nombre' do - # coincide con "GET /hola/foo" y "GET /hola/bar" - # params[:nombre] es 'foo' o 'bar' - "Hola #{params[:nombre]}!" -end -``` - -También puede acceder a los parámetros nombrados usando parámetros de bloque: - -``` ruby -get '/hola/:nombre' do |n| - # coincide con "GET /hola/foo" y "GET /hola/bar" - # params[:nombre] es 'foo' o 'bar' - # n almacena params[:nombre] - "Hola #{n}!" -end -``` - -Los patrones de ruta también pueden incluir parámetros splat (o wildcard), -accesibles a través del arreglo `params[:splat]`: - -``` ruby -get '/decir/*/al/*' do - # coincide con /decir/hola/al/mundo - params[:splat] # => ["hola", "mundo"] -end - -get '/descargar/*.*' do - # coincide con /descargar/path/al/archivo.xml - params[:splat] # => ["path/al/archivo", "xml"] -end -``` - -O, con parámetros de bloque: - -``` ruby -get '/descargar/*.*' do |path, ext| - [path, ext] # => ["path/al/archivo", "xml"] -end -``` - -Rutas con Expresiones Regulares: - -``` ruby -get %r{/hola/([\w]+)} do - "Hola, #{params[:captures].first}!" -end -``` - -O con un parámetro de bloque: - -``` ruby -get %r{/hola/([\w]+)} do |c| - "Hola, #{c}!" -end -``` - -Los patrones de ruta pueden contener parámetros opcionales: - -``` ruby -get '/posts.?:formato?' do - # coincide con "GET /posts" y además admite cualquier extensión, por - # ejemplo, "GET /posts.json", "GET /posts.xml", etc. -end -``` - -A propósito, a menos que desactives la protección para el ataque *path -traversal* (ver más abajo), el path de la petición puede ser modificado -antes de que se compare con los de tus rutas. - -## Condiciones - -Las rutas pueden incluir una variedad de condiciones de selección, como por -ejemplo el user agent: - -``` ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "Estás usando la versión de Songbird #{params[:agent][0]}" -end - -get '/foo' do - # Coincide con browsers que no sean songbird -end -``` - -Otras condiciones disponibles son `host_name` y `provides`: - -``` ruby -get '/', :host_name => /^admin\./ do - "Área de Administración, Acceso denegado!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -Puede definir sus propias condiciones fácilmente: - -``` ruby -set(:probabilidad) { |valor| condition { rand <= valor } } - -get '/gana_un_auto', :probabilidad => 0.1 do - "Ganaste!" -end - -get '/gana_un_auto' do - "Lo siento, perdiste." -end -``` - -Si su condición acepta más de un argumento, puede pasarle un arreglo. Al -definir la condición, se puede utilizar el operador splat en -la lista de parámetros: - -``` ruby -set(:autorizar) do |*roles| # <- mirá el splat - condition do - unless sesion_iniciada? && roles.any? {|rol| usuario_actual.tiene_rol? rol } - redirect "/iniciar_sesion/", 303 - end - end -end - -get "/mi/cuenta/", :autorizar => [:usuario, :administrador] do - "Detalles de mi cuenta" -end - -get "/solo/administradores/", :autorizar => :administrador do - "Únicamente para administradores!" -end -``` - -### Valores de Retorno - -El valor de retorno de un bloque de ruta que determina al menos el cuerpo de la -respuesta que se le pasa al cliente HTTP o al siguiente middleware en la pila -de Rack. Lo más común es que sea un string, como en los ejemplos anteriores. -Sin embargo, otros valores también son aceptados. - -Puede devolver cualquier objeto que sea una respuesta Rack válida, un objeto -que represente el cuerpo de una respuesta Rack o un código de estado HTTP: - -* Un arreglo con tres elementos: `[estado (Fixnum), cabeceras (Hash), cuerpo de - la respuesta (responde a #each)]` -* Un arreglo con dos elementos: `[estado (Fixnum), cuerpo de la respuesta - (responde a #each)]` -* Un objeto que responde a `#each` y que le pasa únicamente strings al bloque - dado -* Un Fixnum representando el código de estado - -De esa manera, podemos fácilmente implementar un ejemplo de streaming: - -``` ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -### Comparadores de Rutas Personalizados - -Como se mostró anteriormente, Sinatra permite utilizar strings y expresiones -regulares para definir las rutas. Sin embargo, la cosa no termina ahí. Podés -definir tus propios comparadores muy fácilmente: - -``` ruby -class PatronCualquieraMenos - Match = Struct.new(:captures) - - def initialize(excepto) - @excepto = excepto - @capturas = Match.new([]) - end - - def match(str) - @capturas unless @excepto === str - end -end - -def cualquiera_menos(patron) - PatronCualquieraMenos.new(patron) -end - -get cualquiera_menos("/index") do - # ... -end -``` - -Tenga en cuenta que el ejemplo anterior es un poco rebuscado. Un resultado -similar puede conseguirse más sencillamente: - -``` ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -O, usando un lookahead negativo: - -``` ruby -get %r{^(?!/index$)} do - # ... -end -``` - -### Archivos Estáticos - -Los archivos estáticos son servidos desde el directorio público -`./public`. Puede especificar una ubicación diferente ajustando la -opción `:public_folder`: - -``` ruby -set :public_folder, File.dirname(__FILE__) + '/estaticos' -``` - -Note que el nombre del directorio público no está incluido en la URL. Por -ejemplo, el archivo `./public/css/style.css` se accede a través de -`http://ejemplo.com/css/style.css`. - -Use la configuración `:static_cache_control` para agregar el encabezado -`Cache-Control` (ver la sección de configuración para más detalles). - -### Vistas / Plantillas - -Cada lenguaje de plantilla se expone a través de un método de renderizado que -lleva su nombre. Estos métodos simplemente devuelven un string: - -``` ruby -get '/' do - erb :index -end -``` - -Renderiza `views/index.erb`. - -En lugar del nombre de la plantilla podés proporcionar directamente el -contenido de la misma: - -``` ruby -get '/' do - codigo = "<%= Time.now %>" - erb codigo -end -``` - -Los métodos de renderizado, aceptan además un segundo argumento, el hash de -opciones: - -``` ruby -get '/' do - erb :index, :layout => :post -end -``` - -Renderiza `views/index.erb` embebido en `views/post.erb` (por -defecto, la plantilla `:index` es embebida en `views/layout.erb` siempre y -cuando este último archivo exista). - -Cualquier opción que Sinatra no entienda le será pasada al motor de renderizado -de la plantilla: - -``` ruby -get '/' do - haml :index, :format => :html5 -end -``` - -Además, puede definir las opciones para un lenguaje de plantillas de forma -general: - -``` ruby -set :haml, :format => :html5 - -get '/' do - haml :index -end -``` - -Las opciones pasadas al método de renderizado tienen precedencia sobre las -definidas mediante `set`. - -Opciones disponibles: - -
- -
locals
-
- Lista de variables locales pasadas al documento. Resultan muy útiles cuando - se combinan con parciales. - Ejemplo: erb "<%= foo %>", :locals => {:foo => "bar"} -
- -
default_encoding
-
- Encoding utilizado cuando el de un string es dudoso. Por defecto toma el - valor de settings.default_encoding. -
- -
views
-
- Directorio desde donde se cargan las vistas. Por defecto toma el valor de - settings.views. -
- -
layout
-
- Si es true o false indica que se debe usar, o no, un layout, - respectivamente. También puede ser un símbolo que especifique qué plantilla - usar. Ejemplo: erb :index, :layout => !request.xhr? -
- -
content_type
-
- Content-Type que produce la plantilla. El valor por defecto depende de cada - lenguaje de plantillas. -
- -
scope
-
- Ámbito en el que se renderiza la plantilla. Por defecto utiliza la instancia - de la aplicación. Tené en cuenta que si cambiás esta opción las variables de - instancia y los helpers van a dejar de estar disponibles. -
- -
layout_engine
-
- Motor de renderizado de plantillas que usa para el layout. Resulta - conveniente para lenguajes que no soportan layouts. Por defecto toma el valor - del motor usado para renderizar la plantilla. - Ejemplo: set :rdoc, :layout_engine => :erb -
- -
- Se asume que las plantillas están ubicadas directamente bajo el directorio - ./views. Para usar un directorio de vistas diferente: - set :views, settings.root + '/plantillas' -
- -
- Es importante acordarse que siempre tenés que referenciar a las plantillas con - símbolos, incluso cuando se encuentran en un subdirectorio (en este caso - tenés que usar: `:'subdir/plantilla'` o `'subdir/plantilla'.to_sym`). Tenés que - usar un símbolo porque los métodos de renderización van a renderizar - directamente cualquier string que se les pase como argumento. -
-
- -### Lenguajes de Plantillas Disponibles - -Algunos lenguajes tienen varias implementaciones. Para especificar que -implementación usar (y para ser thread-safe), deberías requerirla antes de -usarla: - -``` ruby -require 'rdiscount' # o require 'bluecloth' -get('/') { markdown :index } -``` - -### Plantillas Haml - - - - - - - - - - - - - - -
Dependenciashaml
Expresiones de Archivo.haml
Ejemplohaml :index, :format => :html5
- -### Plantillas Erb - - - - - - - - - - - - - - -
Dependencias - erubis - o erb (incluida en Ruby) -
Extensiones de Archivo.erb, .rhtml o .erubis (solamente con Erubis)
Ejemploerb :index
- -### Plantillas Builder - - - - - - - - - - - - - - -
Dependencias - builder -
Extensiones de Archivo.builder
Ejemplobuilder { |xml| xml.em "hola" }
- -Además, acepta un bloque con la definición de la plantilla (ver el ejemplo). - -### Plantillas Nokogiri - - - - - - - - - - - - - - -
Dependenciasnokogiri
Extensiones de Archivo.nokogiri
Ejemplonokogiri { |xml| xml.em "hola" }
- -Además, acepta un bloque con la definición de la plantilla (ver el ejemplo). - -### Plantillas Sass - - - - - - - - - - - - - - -
Dependenciassass
Extensiones de Archivo.sass
Ejemplosass :stylesheet, :style => :expanded
- -### Plantillas SCSS - - - - - - - - - - - - - - -
Dependenciassass
Extensiones de Archivo.scss
Ejemploscss :stylesheet, :style => :expanded
- -### Plantillas Less - - - - - - - - - - - - - - -
Dependenciasless
Extensiones de Archivo.less
Ejemploless :stylesheet
- -### Plantillas Liquid - - - - - - - - - - - - - - -
Dependenciasliquid
Extensiones de Archivo.liquid
Ejemploliquid :index, :locals => { :clave => 'valor' }
- -Como no va a poder llamar a métodos de Ruby (excepto por `yield`) desde una -plantilla Liquid, casi siempre va a querer pasarle locales. - -### Plantillas Markdown - - - - - - - - - - - - - - -
Dependencias - RDiscount, - RedCarpet, - BlueCloth, - kramdown o - maruku -
Extensiones de Archivo.markdown, .mkd y .md
Ejemplomarkdown :index, :layout_engine => :erb
- -No es posible llamar métodos desde markdown, ni pasarle locales. Por lo tanto, -generalmente va a usarlo en combinación con otro motor de renderizado: - -``` ruby -erb :resumen, :locals => { :texto => markdown(:introduccion) } -``` - -Tenga en cuenta que también podés llamar al método `markdown` desde otras -plantillas: - -``` ruby -%h1 Hola Desde Haml! -%p= markdown(:saludos) -``` - -Como no puede utilizar Ruby desde Markdown, no puede usar layouts escritos en -Markdown. De todos modos, es posible usar un motor de renderizado para el -layout distinto al de la plantilla pasando la opción `:layout_engine`. - -### Plantillas Textile - - - - - - - - - - - - - - -
DependenciasRedCloth
Extensiones de Archivo.textile
Ejemplotextile :index, :layout_engine => :erb
- -No es posible llamar métodos desde textile, ni pasarle locales. Por lo tanto, -generalmente vas a usarlo en combinación con otro motor de renderizado: - -``` ruby -erb :resumen, :locals => { :texto => textile(:introduccion) } -``` - -Tené en cuenta que también podés llamar al método `textile` desde otras -plantillas: - -``` ruby -%h1 Hola Desde Haml! -%p= textile(:saludos) -``` - -Como no podés utilizar Ruby desde Textile, no podés usar layouts escritos en -Textile. De todos modos, es posible usar un motor de renderizado para el -layout distinto al de la plantilla pasando la opción `:layout_engine`. - -### Plantillas RDoc - - - - - - - - - - - - - - -
DependenciasRDoc
Extensiones de Archivo.rdoc
Ejemplordoc :README, :layout_engine => :erb
- -No es posible llamar métodos desde rdoc, ni pasarle locales. Por lo tanto, -generalmente vas a usarlo en combinación con otro motor de renderizado: - -``` ruby -erb :resumen, :locals => { :texto => rdoc(:introduccion) } -``` - -Tené en cuenta que también podés llamar al método `rdoc` desde otras -plantillas: - -``` ruby -%h1 Hola Desde Haml! -%p= rdoc(:saludos) -``` - -Como no podés utilizar Ruby desde RDoc, no podés usar layouts escritos en RDoc. -De todos modos, es posible usar un motor de renderizado para el layout distinto -al de la plantilla pasando la opción `:layout_engine`. - -### Plantillas Radius - - - - - - - - - - - - - - -
DependenciasRadius
Extensiones de Archivo.radius
Ejemploradius :index, :locals => { :clave => 'valor' }
- -Desde que no se puede utilisar métodos de Ruby (excepto por `yield`) de una -plantilla Radius, casi siempre se necesita pasar locales. - -### Plantillas Markaby - - - - - - - - - - - - - - -
DependenciasMarkaby
Extensiones de Archivo.mab
Ejemplomarkaby { h1 "Bienvenido!" }
- -Además, acepta un bloque con la definición de la plantilla (ver el ejemplo). - -### Plantillas RABL - - - - - - - - - - - - - - -
DependenciasRabl
Extensiones de Archivo.rabl
Ejemplorabl :index
- -### Plantillas Slim - - - - - - - - - - - - - - -
DependenciasSlim Lang
Extensiones de Archivo.slim
Ejemploslim :index
- -### Plantillas Creole - - - - - - - - - - - - - - -
DependenciasCreole
Extensiones de Archivo.creole
Ejemplocreole :wiki, :layout_engine => :erb
- -No es posible llamar métodos desde creole, ni pasarle locales. Por lo tanto, -generalmente va a usarlo en combinación con otro motor de renderizado: - -``` ruby -erb :resumen, :locals => { :texto => cerole(:introduccion) } -``` - -Debe tomar en cuenta que también puede llamar al método `creole` desde otras -plantillas: - -``` ruby -%h1 Hola Desde Haml! -%p= creole(:saludos) -``` - -Como no podés utilizar Ruby desde Creole, no podés usar layouts escritos en -Creloe. De todos modos, es posible usar un motor de renderizado para el layout -distinto al de la plantilla pasando la opción `:layout_engine`. - -### Plantillas CoffeeScript - - - - - - - - - - - - - - -
Dependencias - - CoffeeScript - y un - - mecanismo para ejecutar javascript - -
Extensiones de Archivo.coffee
Ejemplocoffee :index
- -### Plantillas Stylus - - - - - - - - - - - - - - -
Dependencias - - Stylus - y un - - mecanismo para ejecutar javascript - -
Extensiones de Archivo.styl
Ejemplostylus :index
- -### Plantillas Yajl - - - - - - - - - - - - - - -
Dependenciasyajl-ruby
Extensiones de Archivo.yajl
Ejemplo - - yajl :index, - :locals => { :key => 'qux' }, - :callback => 'present', - :variable => 'resource' - -
- -El contenido de La plantilla se evalúa como código Ruby, y la variable `json` es convertida a JSON mediante `#to_json`. - -``` ruby -json = { :foo => 'bar' } -json[:baz] = key -``` - -Las opciones `:callback` y `:variable` se pueden utilizar para decorar el objeto renderizado: - -``` ruby -var resource = {"foo":"bar","baz":"qux"}; present(resource); -``` - -### Plantillas WLang - - - - - - - - - - - - - - -
Dependenciaswlang
Extensiones de Archivo.wlang
Ejemplowlang :index, :locals => { :clave => 'valor' }
- -Como no vas a poder llamar a métodos de Ruby (excepto por `yield`) desde una -plantilla WLang, casi siempre vas a querer pasarle locales. - -### Plantillas Embebidas - -``` ruby -get '/' do - haml '%div.titulo Hola Mundo' -end -``` - -Renderiza el template embebido en el string. - -### Accediendo a Variables en Plantillas - -Las plantillas son evaluadas dentro del mismo contexto que los manejadores de -ruta. Las variables de instancia asignadas en los manejadores de ruta son -accesibles directamente por las plantillas: - -``` ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.nombre' -end -``` - -O es posible especificar un Hash de variables locales explícitamente: - -``` ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= bar.nombre', :locals => { :bar => foo } -end -``` - -Esto es usado típicamente cuando se renderizan plantillas como parciales desde -adentro de otras plantillas. - -### Plantillas Inline - -Las plantillas pueden ser definidas al final del archivo fuente: - -``` ruby -require 'rubygems' -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.titulo Hola mundo!!!!! -``` - -NOTA: únicamente las plantillas inline definidas en el archivo fuente que -requiere sinatra son cargadas automáticamente. Llamá `enable -:inline_templates` explícitamente si tenés plantillas inline en otros -archivos fuente. - -### Plantillas Nombradas - -Las plantillas también pueden ser definidas usando el método top-level -`template`: - -``` ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.titulo Hola Mundo!' -end - -get '/' do - haml :index -end -``` - -Si existe una plantilla con el nombre "layout", va a ser usada cada vez que -una plantilla es renderizada. Podés desactivar los layouts individualmente -pasando `:layout => false` o globalmente con -`set :haml, :layout => false`: - -``` ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -### Asociando Extensiones de Archivo - -Para asociar una extensión de archivo con un motor de renderizado, usá -`Tilt.register`. Por ejemplo, si querés usar la extensión `tt` para -las plantillas Textile, podés hacer lo siguiente: - -``` ruby -Tilt.register :tt, Tilt[:textile] -``` - -### Agregando Tu Propio Motor de Renderizado - -Primero, registrá tu motor con Tilt, y después, creá tu método de renderizado: - -``` ruby -Tilt.register :mipg, MiMotorParaPlantillaGenial - -helpers do - def mypg(*args) render(:mypg, *args) end -end - -get '/' do - mypg :index -end -``` - -Renderiza `./views/index.mypg`. Mirá https://github.com/rtomayko/tilt -para aprender más de Tilt. - -## Filtros - -Los filtros `before` son evaluados antes de cada petición dentro del mismo -contexto que las rutas. Pueden modificar la petición y la respuesta. Las -variables de instancia asignadas en los filtros son accesibles por las rutas y -las plantillas: - -``` ruby -before do - @nota = 'Hey!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @nota #=> 'Hey!' - params[:splat] #=> 'bar/baz' -end -``` - -Los filtros `after` son evaluados después de cada petición dentro del mismo -contexto y también pueden modificar la petición y la respuesta. Las variables -de instancia asignadas en los filtros `before` y en las rutas son accesibles por -los filtros `after`: - -``` ruby -after do - puts response.status -end -``` - -Nota: A menos que uses el método `body` en lugar de simplemente devolver un -string desde una ruta, el cuerpo de la respuesta no va a estar disponible en -un filtro after, debido a que todavía no se ha generado. - -Los filtros aceptan un patrón opcional, que cuando está presente causa que los -mismos sean evaluados únicamente si el path de la petición coincide con ese -patrón: - -``` ruby -before '/protegido/*' do - autenticar! -end - -after '/crear/:slug' do |slug| - session[:ultimo_slug] = slug -end -``` - -Al igual que las rutas, los filtros también pueden aceptar condiciones: - -``` ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'ejemplo.com' do - # ... -end -``` - -## Ayudantes - -Usá el método top-level *helpers* para definir métodos ayudantes que -pueden ser utilizados dentro de los manejadores de rutas y las plantillas: - -``` ruby -helpers do - def bar(nombre) - "#{nombre}bar" - end -end - -get '/:nombre' do - bar(params[:nombre]) -end -``` - -Por cuestiones organizativas, puede resultar conveniente organizar los métodos -ayudantes en distintos módulos: - -``` ruby -module FooUtils - def foo(nombre) "#{nombre}foo" end -end - -module BarUtils - def bar(nombre) "#{nombre}bar" end -end - -helpers FooUtils, BarUtils -``` - -El efecto de utilizar *helpers* de esta manera es el mismo que resulta de -incluir los módulos en la clase de la aplicación. - -### Usando Sesiones - -Una sesión es usada para mantener el estado a través de distintas peticiones. -Cuando están activadas, proporciona un hash de sesión para cada sesión de usuario: - -``` ruby -enable :sessions - -get '/' do - "valor = " << session[:valor].inspect -end - -get '/:valor' do - session[:valor] = params[:valor] -end -``` - -Tené en cuenta que `enable :sessions` guarda todos los datos en una -cookie, lo cual no es siempre deseable (guardar muchos datos va a incrementar -el tráfico, por citar un ejemplo). Podés usar cualquier middleware Rack para -manejar sesiones, de la misma manera que usarías cualquier otro middleware, -pero con la salvedad de que *no* tenés que llamar a `enable :sessions`: - -``` ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "valor = " << session[:valor].inspect -end - -get '/:valor' do - session[:valor] = params[:valor] -end -``` - -Para incrementar la seguridad, los datos de la sesión almacenados en -la cookie son firmados con un secreto de sesión. Este secreto, es -generado aleatoriamente por Sinatra. De cualquier manera, hay que -tener en cuenta que cada vez que inicies la aplicación se va a generar -uno nuevo. Así, si querés que todas las instancias de tu aplicación -compartan un único secreto, tenés que definirlo vos: - -``` ruby -set :session_secret, 'super secreto' -``` - -Si necesitás una configuración más específica, `sessions` acepta un -Hash con opciones: - -``` ruby -set :sessions, :domain => 'foo.com' -``` - -### Interrupción - -Para detener inmediatamente una petición dentro de un filtro o una ruta usá: - -``` ruby -halt -``` - -También podés especificar el estado: - -``` ruby -halt 410 -``` - -O el cuerpo: - -``` ruby -halt 'esto va a ser el cuerpo' -``` - -O los dos: - -``` ruby -halt 401, 'salí de acá!' -``` - -Con cabeceras: - -``` ruby -halt 402, { 'Content-Type' => 'text/plain' }, 'venganza' -``` - -Obviamente, es posible utilizar `halt` con una plantilla: - -``` ruby -halt erb(:error) -``` - -### Paso - -Una ruta puede pasarle el procesamiento a la siguiente ruta que coincida con -la petición usando `pass`: - -``` ruby -get '/adivina/:quien' do - pass unless params[:quien] == 'Franco' - 'Adivinaste!' -end - -get '/adivina/*' do - 'Erraste!' -end -``` - -Se sale inmediatamente del bloque de la ruta y se le pasa el control a la -siguiente ruta que coincida. Si no coincide ninguna ruta, se devuelve 404. - -### Ejecutando Otra Ruta - -Cuando querés obtener el resultado de la llamada a una ruta, `pass` no te va a -servir. Para lograr esto, podés usar `call`: - -``` ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do - "bar" -end -``` - -Notá que en el ejemplo anterior, es conveniente mover `"bar"` a un -helper, y llamarlo desde `/foo` y `/bar`. Así, vas a simplificar -las pruebas y a mejorar el rendimiento. - -Si querés que la petición se envíe a la misma instancia de la aplicación en -lugar de a otra, usá `call!` en lugar de `call`. - -En la especificación de Rack podés encontrar más información sobre -`call`. - -### Asignando el Código de Estado, los Encabezados y el Cuerpo de una Respuesta - -Es posible, y se recomienda, asignar el código de estado y el cuerpo de una -respuesta con el valor de retorno de una ruta. De cualquier manera, en varios -escenarios, puede que sea conveniente asignar el cuerpo en un punto arbitrario -del flujo de ejecución con el método `body`. A partir de ahí, podés usar ese -mismo método para acceder al cuerpo de la respuesta: - -``` ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -``` - -También es posible pasarle un bloque a `body`, que será ejecutado por el Rack -handler (podés usar esto para implementar streaming, mirá "Valores de retorno"). - -De manera similar, también podés asignar el código de estado y encabezados: - -``` ruby -get '/foo' do - status 418 - headers \ - "Allow" => "BREW, POST, GET, PROPFIND, WHEN", - "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - body "I'm a tea pot!" -end -``` - -También, al igual que `body`, tanto `status` como `headers` pueden utilizarse -para obtener sus valores cuando no se les pasa argumentos. - -### Streaming De Respuestas - -A veces vas a querer empezar a enviar la respuesta a pesar de que todavía no -terminaste de generar su cuerpo. También es posible que, en algunos casos, -quieras seguir enviando información hasta que el cliente cierre la conexión. -Cuando esto ocurra, el `stream` helper te va a ser de gran ayuda: - -``` ruby -get '/' do - stream do |out| - out << "Esto va a ser legen -\n" - sleep 0.5 - out << " (esperalo) \n" - sleep 1 - out << "- dario!\n" - end -end -``` - -Podés implementar APIs de streaming, -[Server-Sent Events](http://dev.w3.org/html5/eventsource/) y puede ser usado -como base para [WebSockets](http://es.wikipedia.org/wiki/WebSockets). También -puede ser usado para incrementar el throughput si solo una parte del contenido -depende de un recurso lento. - -Hay que tener en cuenta que el comportamiento del streaming, especialmente el -número de peticiones concurrentes, depende del servidor web utilizado para -servir la aplicación. Puede que algunos servidores, como es el caso de -WEBRick, no soporten streaming directamente, así el cuerpo de la respuesta será -enviado completamente de una vez cuando el bloque pasado a `stream` finalice su -ejecución. Si estás usando Shotgun, el streaming no va a funcionar. - -Cuando se pasa `keep_open` como parámetro, no se va a enviar el mensaje -`close` al objeto de stream. Queda en vos cerrarlo en el punto de ejecución -que quieras. Nuevamente, hay que tener en cuenta que este comportamiento es -posible solo en servidores que soporten eventos, como Thin o Rainbows. El -resto de los servidores van a cerrar el stream de todos modos: - -``` ruby -set :server, :thin -conexiones = [] - -get '/' do - # mantenemos abierto el stream - stream(:keep_open) { |salida| conexiones << salida } -end - -post '/' do - # escribimos a todos los streams abiertos - conexiones.each { |salida| salida << params[:mensaje] << "\n" } - "mensaje enviado" -end -``` - -### Log (Registro) - -En el ámbito de la petición, el helper `logger` (registrador) expone -una instancia de `Logger`: - -``` ruby -get '/' do - logger.info "cargando datos" - # ... -end -``` - -Este logger tiene en cuenta la configuración de logueo de tu Rack -handler. Si el logueo está desactivado, este método va a devolver un -objeto que se comporta como un logger pero que en realidad no hace -nada. Así, no vas a tener que preocuparte por esta situación. - -Tené en cuenta que el logueo está habilitado por defecto únicamente -para `Sinatra::Application`. Si heredaste de -`Sinatra::Base`, probablemente quieras habilitarlo manualmente: - -``` ruby -class MiApp < Sinatra::Base - configure :production, :development do - enable :logging - end -end -``` - -Para evitar que se inicialice cualquier middleware de logging, configurá -`logging` a `nil`. Tené en cuenta que, cuando hagas esto, `logger` va a -devolver `nil`. Un caso común es cuando querés usar tu propio logger. Sinatra -va a usar lo que encuentre en `env['rack.logger']`. - -### Tipos Mime - -Cuando usás `send_file` o archivos estáticos tal vez tengas tipos mime -que Sinatra no entiende. Usá `mime_type` para registrarlos a través de la -extensión de archivo: - -``` ruby -configure do - mime_type :foo, 'text/foo' -end -``` - -También lo podés usar con el ayudante `content_type`: - -``` ruby -get '/' do - content_type :foo - "foo foo foo" -end -``` - -### Generando URLs - -Para generar URLs deberías usar el método `url`. Por ejemplo, en Haml: - -``` ruby -%a{:href => url('/foo')} foo -``` - -Tiene en cuenta proxies inversos y encaminadores de Rack, si están presentes. - -Este método también puede invocarse mediante su alias `to` (mirá un ejemplo -a continuación). - -### Redirección del Navegador - -Podés redireccionar al navegador con el método `redirect`: - -``` ruby -get '/foo' do - redirect to('/bar') -end -``` - -Cualquier parámetro adicional se utiliza de la misma manera que los argumentos -pasados a `halt`: - -``` ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'te confundiste de lugar, compañero' -``` - -También podés redireccionar fácilmente de vuelta hacia la página desde donde -vino el usuario con `redirect back`: - -``` ruby -get '/foo' do - "hacer algo" -end - -get '/bar' do - hacer_algo - redirect back -end -``` - -Para pasar argumentos con una redirección, podés agregarlos a la cadena de -búsqueda: - -``` ruby -redirect to('/bar?suma=42') -``` - -O usar una sesión: - -``` ruby -enable :sessions - -get '/foo' do - session[:secreto] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secreto] -end -``` - -### Cache Control - -Asignar tus encabezados correctamente es el cimiento para realizar un cacheo -HTTP correcto. - -Podés asignar el encabezado Cache-Control fácilmente: - -``` ruby -get '/' do - cache_control :public - "cachealo!" -end -``` - -Pro tip: configurar el cacheo en un filtro `before`: - -``` ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -``` - -Si estás usando el helper `expires` para definir el encabezado correspondiente, -`Cache-Control` se va a definir automáticamente: - -``` ruby -before do - expires 500, :public, :must_revalidate -end -``` - -Para usar cachés adecuadamente, deberías considerar usar `etag` o -`last_modified`. Es recomendable que llames a estos helpers *antes* de hacer -cualquier trabajo pesado, ya que van a enviar la respuesta inmediatamente si -el cliente ya tiene la versión actual en su caché: - -``` ruby -get '/articulo/:id' do - @articulo = Articulo.find params[:id] - last_modified @articulo.updated_at - etag @articulo.sha1 - erb :articulo -end -``` - -También es posible usar una -[weak ETag](http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation): - -``` ruby -etag @articulo.sha1, :weak -``` - -Estos helpers no van a cachear nada por vos, sino que van a facilitar la -información necesaria para poder hacerlo. Si estás buscando soluciones rápidas -de cacheo con proxys reversos, mirá -[rack-cache](https://github.com/rtomayko/rack-cache): - -``` ruby -require "rack/cache" -require "sinatra" - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hola" -end -``` - -Usá la configuración `:static_cache_control` para agregar el encabezado -`Cache-Control` a archivos estáticos (ver la sección de configuración -para más detalles). - -De acuerdo con la RFC 2616 tu aplicación debería comportarse diferente si a las -cabeceras If-Match o If-None-Match se le asigna el valor `*` cuando el -recurso solicitado ya existe. Sinatra asume para peticiones seguras (como get) -e idempotentes (como put) que el recurso existe, mientras que para el resto -(como post) asume que no. Podes cambiar este comportamiento con la opción -`:new_resource`: - -``` ruby -get '/crear' do - etag '', :new_resource => true - Articulo.create - erb :nuevo_articulo -end -``` - -Si querés seguir usando una weak ETag, indicalo con la opción `:kind`: - -``` ruby -etag '', :new_resource => true, :kind => :weak -``` - -### Enviando Archivos - -Para enviar archivos, podés usar el método `send_file`: - -``` ruby -get '/' do - send_file 'foo.png' -end -``` - -Además acepta un par de opciones: - -``` ruby -send_file 'foo.png', :type => :jpg -``` - -Estas opciones son: - -[filename] - nombre del archivo devuelto, por defecto es el nombre real del archivo. - -[last_modified] - valor para el encabezado Last-Modified, por defecto toma el mtime del archivo. - -[type] - el content type que se va a utilizar, si no está presente se intenta adivinar - a partir de la extensión del archivo. - -[disposition] - se utiliza para el encabezado Content-Disposition, y puede tomar alguno de los - siguientes valores: `nil` (por defecto), `:attachment` e - `:inline` - -[length] - encabezado Content-Length, por defecto toma el tamaño del archivo. - -[status] - código de estado devuelto. Resulta útil al enviar un archivo estático como una - página de error. - -Si el Rack handler lo soporta, se intentará no transmitir directamente desde el -proceso de Ruby. Si usás este método, Sinatra se va a encargar automáticamente -peticiones de rango. - -### Accediendo al objeto de la petición - -El objeto de la petición entrante puede ser accedido desde el nivel de la -petición (filtros, rutas y manejadores de errores) a través del método -`request`: - -``` ruby -# app corriendo en http://ejemplo.com/ejemplo -get '/foo' do - t = %w[text/css text/html application/javascript] - request.accept # ['text/html', '*/*'] - request.accept? 'text/xml' # true - request.preferred_type(t) # 'text/html' - request.body # cuerpo de la petición enviado por el cliente (ver más abajo) - request.scheme # "http" - request.script_name # "/ejemplo" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # longitud de request.body - request.media_type # tipo de medio de request.body - request.host # "ejemplo.com" - request.get? # true (hay métodos análogos para los otros verbos) - request.form_data? # false - request["UNA_CABECERA"] # valor de la cabecera UNA_CABECERA - request.referrer # la referencia del cliente o '/' - request.user_agent # user agent (usado por la condición :agent) - request.cookies # hash de las cookies del browser - request.xhr? # es una petición ajax? - request.url # "http://ejemplo.com/ejemplo/foo" - request.path # "/ejemplo/foo" - request.ip # dirección IP del cliente - request.secure? # false (sería true sobre ssl) - request.forwarded? # true (si se está corriendo atrás de un proxy reverso) - requuest.env # hash de entorno directamente entregado por Rack -end -``` - -Algunas opciones, como `script_name` o `path_info` pueden -también ser escritas: - -``` ruby -before { request.path_info = "/" } - -get "/" do - "todas las peticiones llegan acá" -end -``` - -El objeto `request.body` es una instancia de IO o StringIO: - -``` ruby -post "/api" do - request.body.rewind # en caso de que alguien ya lo haya leído - datos = JSON.parse request.body.read - "Hola #{datos['nombre']}!" -end -``` - -### Archivos Adjuntos - -Podés usar el método helper `attachment` para indicarle al navegador que -almacene la respuesta en el disco en lugar de mostrarla en pantalla: - -``` ruby -get '/' do - attachment - "guardalo!" -end -``` - -También podés pasarle un nombre de archivo: - -``` ruby -get '/' do - attachment "info.txt" - "guardalo!" -end -``` - -### Fecha y Hora - -Sinatra pone a tu disposición el helper `time_for`, que genera un objeto `Time` -a partir del valor que recibe como argumento. Este valor puede ser un -`String`, pero también es capaz de convertir objetos `DateTime`, `Date` y de -otras clases similares: - -``` ruby -get '/' do - pass if Time.now > time_for('Dec 23, 2012') - "todavía hay tiempo" -end -``` - -Este método es usado internamente por métodos como `expires` y `last_modified`, -entre otros. Por lo tanto, es posible extender el comportamiento de estos -métodos sobreescribiendo `time_for` en tu aplicación: - -``` ruby -helpers do - def time_for(value) - case value - when :ayer then Time.now - 24*60*60 - when :mañana then Time.now + 24*60*60 - else super - end - end -end - -get '/' do - last_modified :ayer - expires :mañana - "hola" -end -``` - -### Buscando los Archivos de las Plantillas - -El helper `find_template` se utiliza para encontrar los archivos de las -plantillas que se van a renderizar: - -``` ruby -find_template settings.views, 'foo', Tilt[:haml] do |archivo| - puts "podría ser #{archivo}" -end -``` - -Si bien esto no es muy útil, lo interesante es que podés sobreescribir este -método, y así enganchar tu propio mecanismo de búsqueda. Por ejemplo, para -poder utilizar más de un directorio de vistas: - -``` ruby -set :views, ['vistas', 'plantillas'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -``` - -Otro ejemplo consiste en usar directorios diferentes para los distintos motores -de renderizado: - -``` ruby -set :views, :sass => 'vistas/sass', :haml => 'plantillas', :defecto => 'vistas' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:defecto] - super(folder, name, engine, &block) - end -end -``` - -¡Es muy fácil convertir estos ejemplos en una extensión y compartirla! - -Notá que `find_template` no verifica si un archivo existe realmente, sino -que llama al bloque que recibe para cada path posible. Esto no representa un -problema de rendimiento debido a que `render` va a usar `break` ni bien -encuentre un archivo que exista. Además, las ubicaciones de las plantillas (y -su contenido) se cachean cuando no estás en el modo de desarrollo. Es bueno -tener en cuenta lo anteiror si escribís un método medio loco. - -## Configuración - -Ejecutar una vez, en el inicio, en cualquier entorno: - -``` ruby -configure do - # asignando una opción - set :opcion, 'valor' - - # asignando varias opciones - set :a => 1, :b => 2 - - # atajo para `set :opcion, true` - enable :opcion - - # atajo para `set :opcion, false` - disable :opcion - - # también podés tener configuraciones dinámicas usando bloques - set(:css_dir) { File.join(views, 'css') } -end -``` - -Ejecutar únicamente cuando el entorno (la variable de entorno RACK_ENV) es -`:production`: - -``` ruby -configure :production do - ... -end -``` - -Ejecutar cuando el entorno es `:production` o `:test`: - -``` ruby -configure :production, :test do - ... -end -``` - -Podés acceder a estas opciones utilizando el método `settings`: - -``` ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -``` - -### Configurando la Protección de Ataques - -Sinatra usa [Rack::Protection](https://github.com/rkh/rack-protection#readme) -para defender a tu aplicación de los ataques más comunes. Si por algún motivo, -querés desactivar esta funcionalidad, podés hacerlo como se indica a -continuación (tené en cuenta que tu aplicación va a quedar expuesta a un -montón de vulnerabilidades bien conocidas): - -``` ruby -disable :protection -``` - -También es posible desactivar una única capa de defensa: - -``` ruby -set :protection, :except => :path_traversal -``` - -O varias: - -``` ruby -set :protection, :except => [:path_traversal, :session_hijacking] -``` - -### Configuraciones Disponibles - -
-
absolute_redirects
-
- Si está deshabilitada, Sinatra va a permitir - redirecciones relativas, sin embargo, como consecuencia - de esto, va a dejar de cumplir con el RFC 2616 (HTTP - 1.1), que solamente permite redirecciones absolutas. - - Activalo si tu apliación está corriendo atrás de un proxy - reverso que no se ha configurado adecuadamente. Notá que - el helper url va a seguir produciendo URLs absolutas, a - menos que le pasés false como segundo parámetro. - - Deshabilitada por defecto. -
- -
add_charsets
-
- Tipos mime a los que el helper content_type les - añade automáticamente el charset. - - En general, no deberías asignar directamente esta opción, - sino añadirle los charsets que quieras: - settings.add_charsets << "application/foobar" -
- -
app_file
-
- Path del archivo principal de la aplicación, se utiliza - para detectar la raíz del proyecto, el directorio de las - vistas y el público, así como las plantillas inline. -
- -
bind
-
- Dirección IP que utilizará el servidor integrado (por - defecto: 0.0.0.0). -
- -
default_encoding
-
- Encoding utilizado cuando el mismo se desconoce (por - defecto "utf-8"). -
- -
dump_errors
-
- Mostrar errores en el log. -
- -
environment
-
- Entorno actual, por defecto toma el valor de - ENV['RACK_ENV'], o "development" si no - está disponible. -
- -
logging
-
- Define si se utiliza el logger. -
- -
lock
-
- Coloca un lock alrededor de cada petición, procesando - solamente una por proceso. - - Habilitá esta opción si tu aplicación no es thread-safe. - Se encuentra deshabilitada por defecto. -
- -
method_override
-
- Utiliza el parámetro _method para permtir - formularios put/delete en navegadores que no los - soportan. -
- -
port
-
- Puerto en el que escuchará el servidor integrado. -
- -
prefixed_redirects
-
- Define si inserta request.script_name en las - redirecciones cuando no se proporciona un path absoluto. - De esta manera, cuando está habilitada, - redirect '/foo' se comporta de la misma manera - que redirect to('/foo'). Se encuentra - deshabilitada por defecto. -
- -
protection
-
- Define si deben activarse las protecciones para los - ataques web más comunes. Para más detalles mirá la - sección sobre la configuración de protección de ataques - más arriba. -
- -
public_dir
-
- Alias para public_folder, que se encuentra a - continuación. -
- -
public_folder
-
- Path del directorio desde donde se sirven los archivos - públicos. Solo se utiliza cuando se sirven archivos - estáticos (ver la opción static). Si no - está presente, se infiere del valor de la opción - app_file. -
- -
reload_templates
-
- Define si se recargan las plantillas entre peticiones. - - Se encuentra activado en el entorno de desarrollo. -
- -
root
-
- Path del directorio raíz del proyecto. Si no está - presente, se infiere del valor de la opción - app_file. -
- -
raise_errors
-
- Elevar excepciones (detiene la aplicación). Se - encuentra activada por defecto cuando el valor de - environment es "test". En caso - contrario estará desactivada. -
- -
run
-
- Cuando está habilitada, Sinatra se va a encargar de - iniciar el servidor web, no la habilites cuando estés - usando rackup o algún otro medio. -
- -
running
-
- Indica si el servidor integrado está ejecutandose, ¡no - cambiés esta configuración!. -
- -
server
-
- Servidor, o lista de servidores, para usar como servidor - integrado. Por defecto: ['thin', 'mongrel', 'webrick'], - el orden establece la prioridad. -
- -
sessions
-
- Habilita el soporte de sesiones basadas en cookies a - través de Rack::Session::Cookie. Ver la - sección 'Usando Sesiones' para más información. -
- -
show_exceptions
-
- Muestra un stack trace en el navegador cuando ocurre una - excepción. Se encuentra activada por defecto cuando el - valor de environment es "development". - En caso contrario estará desactivada. -
- -
static
-
- Define si Sinatra debe encargarse de servir archivos - estáticos. - - Deshabilitala cuando uses un servidor capaz de - hacerlo por sí solo, porque mejorará el - rendimiento. Se encuentra habilitada por - defecto en el estilo clásico y desactivado en el - el modular. -
- -
static_cache_control
-
- Cuando Sinatra está sirviendo archivos estáticos, y - está opción está habilitada, les va a agregar encabezados - Cache-Control a las respuestas. Para esto - utiliza el helper cache_control. Se encuentra - deshabilitada por defecto. Notar que es necesario - utilizar un array cuando se asignan múltiples valores: - set :static_cache_control, [:public, :max_age => 300]. -
- -
views
-
- Path del directorio de las vistas. Si no está presente, - se infiere del valor de la opción app_file. -
-
- -## Entornos - -Existen tres entornos (`environments`) predefinidos: `development`, -`production` y `test`. El entorno por defecto es -`development` y tiene algunas particularidades: - -* Se recargan las plantillas entre una petición y la siguiente, a diferencia -de `production` y `test`, donde se cachean. -* Se instalan manejadores de errores `not_found` y `error` -especiales que muestran un stack trace en el navegador cuando son disparados. - -Para utilizar alguno de los otros entornos puede asignarse el valor -correspondiente a la variable de entorno `RACK_ENV`, o bien utilizar la opción -`-e` al ejecutar la aplicación: - -``` shell -ruby mi_app.rb -e -``` - -Los métodos `development?`, `test?` y `production?` te permiten conocer el -entorno actual. - -## Manejo de Errores - -Los manejadores de errores se ejecutan dentro del mismo contexto que las rutas -y los filtros `before`, lo que significa que podés usar, por ejemplo, -`haml`, `erb`, `halt`, etc. - -### No encontrado (Not Found) - -Cuando se eleva una excepción `Sinatra::NotFound`, o el código de -estado de la respuesta es 404, el manejador `not_found` es invocado: - -``` ruby -not_found do - 'No existo' -end -``` - -### Error - -El manejador `error` es invocado cada vez que una excepción es elevada -desde un bloque de ruta o un filtro. El objeto de la excepción se puede -obtener de la variable Rack `sinatra.error`: - -``` ruby -error do - 'Disculpá, ocurrió un error horrible - ' + env['sinatra.error'].name -end -``` - -Errores personalizados: - -``` ruby -error MiErrorPersonalizado do - 'Lo que pasó fue...' + env['sinatra.error'].message -end -``` - -Entonces, si pasa esto: - -``` ruby -get '/' do - raise MiErrorPersonalizado, 'algo malo' -end -``` - -Obtenés esto: - - Lo que pasó fue... algo malo - -También, podés instalar un manejador de errores para un código de estado: - -``` ruby -error 403 do - 'Acceso prohibido' -end - -get '/secreto' do - 403 -end -``` - -O un rango: - -``` ruby -error 400..510 do - 'Boom' -end -``` - -Sinatra instala manejadores `not_found` y `error` especiales -cuando se ejecuta dentro del entorno de desarrollo "development". - -## Rack Middleware - -Sinatra corre sobre Rack[http://rack.rubyforge.org/], una interfaz minimalista -que es un estándar para frameworks webs escritos en Ruby. Una de las -características más interesantes de Rack para los desarrolladores de aplicaciones -es el soporte de "middleware" -- componentes que se ubican entre el servidor y -tu aplicación, supervisando y/o manipulando la petición/respuesta HTTP para -proporcionar varios tipos de funcionalidades comunes. - -Sinatra hace muy sencillo construir tuberías de Rack middleware a través del -método top-level `use`: - -``` ruby -require 'sinatra' -require 'mi_middleware_personalizado' - -use Rack::Lint -use MiMiddlewarePersonalizado - -get '/hola' do - 'Hola Mundo' -end -``` - -La semántica de `use` es idéntica a la definida para el DSL -Rack::Builder[http://rack.rubyforge.org/doc/classes/Rack/Builder.html] (más -frecuentemente usado en archivos rackup). Por ejemplo, el método `use` -acepta argumentos múltiples/variables así como bloques: - -``` ruby -use Rack::Auth::Basic do |nombre_de_usuario, password| - nombre_de_usuario == 'admin' && password == 'secreto' -end -``` - -Rack es distribuido con una variedad de middleware estándar para logging, -debugging, enrutamiento URL, autenticación, y manejo de sesiones. Sinatra -usa muchos de estos componentes automáticamente de acuerdo a su configuración -para que típicamente no tengas que usarlas (con `use`) explícitamente. - -Podés encontrar middleware útil en -[rack](https://github.com/rack/rack/tree/master/lib/rack), -[rack-contrib](https://github.com/rack/rack-contrib#readme), -o en la [Rack wiki](https://github.com/rack/rack/wiki/List-of-Middleware). - -## Pruebas - -Las pruebas para las aplicaciones Sinatra pueden ser escritas utilizando -cualquier framework o librería de pruebas basada en Rack. Se recomienda usar -[Rack::Test](http://rdoc.info/github/brynary/rack-test/master/frames): - -``` ruby -require 'mi_app_sinatra' -require 'test/unit' -require 'rack/test' - -class MiAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_mi_defecto - get '/' - assert_equal 'Hola Mundo!', last_response.body - end - - def test_con_parametros - get '/saludar', :name => 'Franco' - assert_equal 'Hola Frank!', last_response.body - end - - def test_con_entorno_rack - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "Estás usando Songbird!", last_response.body - end -end -``` - -## Sinatra::Base - Middleware, Librerías, y Aplicaciones Modulares - -Definir tu aplicación en el top-level funciona bien para micro-aplicaciones -pero trae inconvenientes considerables a la hora de construir componentes -reutilizables como Rack middleware, Rails metal, librerías simples con un -componente de servidor, o incluso extensiones de Sinatra. El DSL de top-level -asume una configuración apropiada para micro-aplicaciones (por ejemplo, un -único archivo de aplicación, los directorios `./public` y -`./views`, logging, página con detalles de excepción, etc.). Ahí es -donde `Sinatra::Base` entra en el juego: - -``` ruby -require 'sinatra/base' - -class MiApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Hola Mundo!' - end -end -``` - -Las subclases de `Sinatra::Base` tienen disponibles exactamente los -mismos métodos que los provistos por el DSL de top-level. La mayoría de las -aplicaciones top-level se pueden convertir en componentes -`Sinatra::Base` con dos modificaciones: - -* Tu archivo debe requerir `sinatra/base` en lugar de `sinatra`; de otra - manera, todos los métodos del DSL de sinatra son importados dentro del - espacio de nombres principal. -* Poné las rutas, manejadores de errores, filtros y opciones de tu aplicación - en una subclase de `Sinatra::Base`. - -`Sinatra::Base` es una pizarra en blanco. La mayoría de las opciones están -desactivadas por defecto, incluyendo el servidor incorporado. Mirá -[Opciones y Configuraciones](http://sinatra.github.com/configuration.html) -para detalles sobre las opciones disponibles y su comportamiento. - -### Estilo Modular vs. Clásico - -Contrariamente a la creencia popular, no hay nada de malo con el estilo clásico. -Si se ajusta a tu aplicación, no es necesario que la cambies a una modular. - -Las desventaja de usar el estilo clásico en lugar del modular consiste en que -solamente podés tener una aplicación Sinatra por proceso Ruby. Si tenés -planificado usar más, cambiá al estilo modular. Al mismo tiempo, tené en -cuenta que no hay ninguna razón por la cuál no puedas mezclar los estilos -clásico y modular. - -A continuación se detallan las diferencias (sutiles) entre las configuraciones -de ambos estilos: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ConfiguraciónClásicaModular
app_filearchivo que carga sinatraarchivo con la subclase de Sinatra::Base
run$0 == app_filefalse
loggingtruefalse
method_overridetruefalse
inline_templatestruefalse
statictruefalse
- -### Sirviendo una Aplicación Modular - -Las dos opciones más comunes para iniciar una aplicación modular son, iniciarla -activamente con `run!`: - -``` ruby -# mi_app.rb -require 'sinatra/base' - -class MiApp < Sinatra::Base - # ... código de la app ... - - # iniciar el servidor si el archivo fue ejecutado directamente - run! if app_file == $0 -end -``` - -Iniciar con: - -``` shell -ruby mi_app.rb -``` - -O, con un archivo `config.ru`, que permite usar cualquier handler Rack: - -``` ruby -# config.ru -require './mi_app' -run MiApp -``` - -Después ejecutar: - -``` shell -rackup -p 4567 -``` - -### Usando una Aplicación Clásica con un Archivo config.ru - -Escribí el archivo de tu aplicación: - -``` ruby -# app.rb -require 'sinatra' - -get '/' do - 'Hola mundo!' -end -``` - -Y el `config.ru` correspondiente: - -``` ruby -require './app' -run Sinatra::Application -``` - -### ¿Cuándo Usar config.ru? - -Indicadores de que probablemente querés usar `config.ru`: - -* Querés realizar el deploy con un hanlder Rack distinto (Passenger, Unicorn, - Heroku, ...). -* Querés usar más de una subclase de `Sinatra::Base`. -* Querés usar Sinatra únicamente para middleware, pero no como un endpoint. - -No hay necesidad de utilizar un archivo `config.ru` exclusivamente -porque tenés una aplicación modular, y no necesitás una aplicación modular para -iniciarla con `config.ru`. - -### Utilizando Sinatra como Middleware - -Sinatra no solo es capaz de usar otro Rack middleware, sino que a su vez, -cualquier aplicación Sinatra puede ser agregada delante de un endpoint Rack -como middleware. Este endpoint puede ser otra aplicación Sinatra, o cualquier -aplicación basada en Rack (Rails/Ramaze/Camping/...): - -``` ruby -require 'sinatra/base' - -class PantallaDeLogin < Sinatra::Base - enable :sessions - - get('/login') { haml :login } - - post('/login') do - if params[:nombre] == 'admin' && params[:password] == 'admin' - session['nombre_de_usuario'] = params[:nombre] - else - redirect '/login' - end - end -end - -class MiApp < Sinatra::Base - # el middleware se ejecutará antes que los filtros - use PantallaDeLogin - - before do - unless session['nombre_de_usuario'] - halt "Acceso denegado, por favor iniciá sesión." - end - end - - get('/') { "Hola #{session['nombre_de_usuario']}." } -end -``` - -### Creación Dinámica de Aplicaciones - -Puede que en algunas ocasiones quieras crear nuevas aplicaciones en -tiempo de ejecución sin tener que asignarlas a una constante. Para -esto tenés `Sinatra.new`: - -``` ruby -require 'sinatra/base' -mi_app = Sinatra.new { get('/') { "hola" } } -mi_app.run! -``` - -Acepta como argumento opcional una aplicación desde la que se -heredará: - -``` ruby -# config.ru -require 'sinatra/base' - -controller = Sinatra.new do - enable :logging - helpers MisHelpers -end - -map('/a') do - run Sinatra.new(controller) { get('/') { 'a' } } -end - -map('/b') do - run Sinatra.new(controller) { get('/') { 'b' } } -end -``` - -Construir aplicaciones de esta forma resulta especialmente útil para -testear extensiones Sinatra o para usar Sinatra en tus librerías. - -Por otro lado, hace extremadamente sencillo usar Sinatra como -middleware: - -``` ruby -require 'sinatra/base' - -use Sinatra do - get('/') { ... } -end - -run ProyectoRails::Application -``` - -## Ámbitos y Ligaduras - -El ámbito en el que te encontrás determina que métodos y variables están -disponibles. - -### Ámbito de Aplicación/Clase - -Cada aplicación Sinatra es una subclase de `Sinatra::Base`. Si estás -usando el DSL de top-level (`require 'sinatra'`), entonces esta clase es -`Sinatra::Application`, de otra manera es la subclase que creaste -explícitamente. Al nivel de la clase tenés métodos como `get` o `before`, pero -no podés acceder a los objetos `request` o `session`, ya que hay una única -clase de la aplicación para todas las peticiones. - -Las opciones creadas utilizando `set` son métodos al nivel de la clase: - -``` ruby -class MiApp < Sinatra::Base - # Ey, estoy en el ámbito de la aplicación! - set :foo, 42 - foo # => 42 - - get '/foo' do - # Hey, ya no estoy en el ámbito de la aplicación! - end -end -``` - -Tenés la ligadura al ámbito de la aplicación dentro de: - -* El cuerpo de la clase de tu aplicación -* Métodos definidos por extensiones -* El bloque pasado a `helpers` -* Procs/bloques usados como el valor para `set` - -Este ámbito puede alcanzarse de las siguientes maneras: - -* A través del objeto pasado a los bloques de configuración (`configure { |c| ...}`) -* Llamando a `settings` desde dentro del ámbito de la petición - -### Ámbito de Petición/Instancia - -Para cada petición entrante, una nueva instancia de la clase de tu aplicación -es creada y todos los bloques de rutas son ejecutados en ese ámbito. Desde este -ámbito podés acceder a los objetos `request` y `session` o llamar a los métodos -de renderización como `erb` o `haml`. Podés acceder al ámbito de la aplicación -desde el ámbito de la petición utilizando `settings`: - -``` ruby -class MiApp < Sinatra::Base - # Ey, estoy en el ámbito de la aplicación! - get '/definir_ruta/:nombre' do - # Ámbito de petición para '/definir_ruta/:nombre' - @valor = 42 - - settings.get("/#{params[:nombre]}") do - # Ámbito de petición para "/#{params[:nombre]}" - @valor # => nil (no es la misma petición) - end - - "Ruta definida!" - end -end -``` - -Tenés la ligadura al ámbito de la petición dentro de: - -* bloques pasados a get/head/post/put/delete/options -* filtros before/after -* métodos ayudantes -* plantillas/vistas - -### Ámbito de Delegación - -El ámbito de delegación solo reenvía métodos al ámbito de clase. De cualquier -manera, no se comporta 100% como el ámbito de clase porque no tenés la ligadura -de la clase: únicamente métodos marcados explícitamente para delegación están -disponibles y no compartís variables/estado con el ámbito de clase (léase: -tenés un `self` diferente). Podés agregar delegaciones de método llamando a -`Sinatra::Delegator.delegate :nombre_del_metodo`. - -Tenés la ligadura al ámbito de delegación dentro de: - -* La ligadura del top-level, si hiciste `require "sinatra"` -* Un objeto extendido con el mixin `Sinatra::Delegator` - -Hechale un vistazo al código: acá está el -[Sinatra::Delegator mixin](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633) -que [extiende el objeto main](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30). - -## Línea de Comandos - -Las aplicaciones Sinatra pueden ser ejecutadas directamente: - -``` shell -ruby miapp.rb [-h] [-x] [-e ENTORNO] [-p PUERTO] [-o HOST] [-s MANEJADOR] -``` - -Las opciones son: - -``` --h # ayuda --p # asigna el puerto (4567 es usado por defecto) --o # asigna el host (0.0.0.0 es usado por defecto) --e # asigna el entorno (development es usado por defecto) --s # especifica el servidor/manejador rack (thin es usado por defecto) --x # activa el mutex lock (está desactivado por defecto) -``` - -## Versiones de Ruby Soportadas - -Las siguientes versiones de Ruby son soportadas oficialmente: - -
-
Ruby 1.8.7
-
- 1.8.7 es soportado completamente. Sin embargo, si no hay nada que te lo - prohiba, te recomendamos que uses 1.9.2 o cambies a JRuby o Rubinius. No se - dejará de dar soporte a 1.8.7 hasta Sinatra 2.0 y Ruby 2.0, aunque si se - libera la versión 1.8.8 de Ruby las cosas podrían llegar a cambiar. Sin - embargo, que eso ocurra es muy poco probable, e incluso el caso de que lo - haga, puede que se siga dando soporte a 1.8.7. Hemos dejado de soportar - Ruby 1.8.6. Si querés ejecutar Sinatra sobre 1.8.6, podés utilizar la - versión 1.2, pero tené en cuenta que una vez que Sinatra 1.4.0 sea liberado, - ya no se corregirán errores por más que se reciban reportes de los mismos. -
- -
Ruby 1.9.2
-
- 1.9.2 es soportado y recomendado. No uses 1.9.2p0, porque se producen fallos - de segmentación cuando se ejecuta Sinatra. El soporte se mantendrá al menos - hasta que se libere la versión 1.9.4/2.0 de Ruby. El soporte para la última - versión de la serie 1.9 se mantendrá mientras lo haga el core team de Ruby. -
- -
Ruby 1.9.3
-
- 1.9.3 es soportado y recomendado. Tené en cuenta que el cambio a 1.9.3 desde - una versión anterior va a invalidar todas las sesiones. -
- -
Rubinius
-
- Rubinius es soportado oficialmente (Rubinius >= 1.2.4). Todo funciona - correctamente, incluyendo los lenguajes de plantillas. La próxima versión, - 2.0, también es soportada, incluyendo el modo 1.9. -
- -
JRuby
-
- JRuby es soportado oficialmente (JRuby >= 1.6.7). No se conocen problemas - con librerías de plantillas de terceras partes. Sin embargo, si elegís usar - JRuby, deberías examinar sus Rack handlers porque el servidor web Thin no es - soportado completamente. El soporte de JRuby para extensiones C se encuentra - en una etapa experimental, sin embargo, de momento solamente RDiscount, - Redcarpet, RedCloth y Yajl, así como Thin y Mongrel se ven afectadas. -
-
- -Siempre le prestamos atención a las nuevas versiones de Ruby. - -Las siguientes implementaciones de Ruby no se encuentran soportadas -oficialmente. De cualquier manera, pueden ejecutar Sinatra: - -* Versiones anteriores de JRuby y Rubinius -* Ruby Enterprise Edition -* MacRuby, Maglev e IronRuby -* Ruby 1.9.0 y 1.9.1 (pero no te recomendamos que los uses) - -No estar soportada oficialmente, significa que si las cosas solamente se rompen -ahí y no en una plataforma soportada, asumimos que no es nuestro problema sino -el suyo. - -Nuestro servidor CI también se ejecuta sobre ruby-head (que será la próxima -versión 2.1.0) y la rama 1.9.4. Como están en movimiento constante, no podemos -garantizar nada. De todas formas, podés contar con que tanto 1.9.4-p0 como -2.1.0-p0 sea soportadas. - -Sinatra debería funcionar en cualquier sistema operativo soportado por la -implementación de Ruby elegida. - -En este momento, no vas a poder ejecutar Sinatra en Cardinal, SmallRuby, -BlueRuby o cualquier versión de Ruby anterior a 1.8.7. - -## A la Vanguardia - -Si querés usar el código de Sinatra más reciente, sentite libre de ejecutar -tu aplicación sobre la rama master, en general es bastante estable. - -También liberamos prereleases de vez en cuando, así, podés hacer: - -``` shell -gem install sinatra --pre -``` - -Para obtener algunas de las últimas características. - -### Con Bundler - -Esta es la manera recomendada para ejecutar tu aplicación sobre la última -versión de Sinatra usando [Bundler](http://gembundler.com/). - -Primero, instalá bundler si no lo hiciste todavía: - -``` shell -gem install bundler -``` - -Después, en el directorio de tu proyecto, creá un archivo `Gemfile`: - -``` ruby -source :rubygems -gem 'sinatra', :git => "git://github.com/sinatra/sinatra.git" - -# otras dependencias -gem 'haml' # por ejemplo, si usás haml -gem 'activerecord', '~> 3.0' # quizás también necesités ActiveRecord 3.x -``` - -Tené en cuenta que tenés que listar todas las dependencias directas de tu -aplicación. No es necesario listar las dependencias de Sinatra (Rack y Tilt) -porque Bundler las agrega directamente. - -Ahora podés arrancar tu aplicación así: - -``` shell -bundle exec ruby miapp.rb -``` - -### Con Git - -Cloná el repositorio localmente y ejecutá tu aplicación, asegurándote que el -directorio `sinatra/lib` esté en el `$LOAD_PATH`: - -``` shell -cd miapp -git clone git://github.com/sinatra/sinatra.git -ruby -Isinatra/lib miapp.rb -``` - -Para actualizar el código fuente de Sinatra en el futuro: - -``` shell -cd miapp/sinatra -git pull -``` - -### Instalación Global - -Podés construir la gem vos mismo: - -``` shell -git clone git://github.com/sinatra/sinatra.git -cd sinatra -rake sinatra.gemspec -rake install -``` - -Si instalás tus gems como root, el último paso debería ser - -``` shell -sudo rake install -``` - -## Versionado - -Sinatra utiliza el [Versionado Semántico](http://semver.org/), -siguiendo las especificaciones SemVer y SemVerTag. - -## Lecturas Recomendadas - -* [Sito web del proyecto](http://www.sinatrarb.com/) - Documentación - adicional, noticias, y enlaces a otros recursos. -* [Contribuyendo](http://www.sinatrarb.com/contributing) - ¿Encontraste un - error?. ¿Necesitás ayuda?. ¿Tenés un parche?. -* [Seguimiento de problemas](http://github.com/sinatra/sinatra/issues) -* [Twitter](http://twitter.com/sinatra) -* [Lista de Correo](http://groups.google.com/group/sinatrarb/topics) -* [IRC: #sinatra](irc://chat.freenode.net/#sinatra) en http://freenode.net -* [Sinatra Book](http://sinatra-book.gittr.com) Tutorial (en inglés). -* [Sinatra Recipes](http://recipes.sinatrarb.com/) Recetas contribuidas - por la comunidad (en inglés). -* Documentación de la API para la - [última versión liberada](http://rubydoc.info/gems/sinatra) o para la - [rama de desarrollo actual](http://rubydoc.info/github/sinatra/sinatra) - en http://rubydoc.info/ -* [Servidor de CI](http://travis-ci.org/sinatra/sinatra) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.fr.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.fr.md deleted file mode 100644 index adc39f4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.fr.md +++ /dev/null @@ -1,2924 +0,0 @@ -# Sinatra -*Attention : Ce document correspond à la traduction de la version anglaise et -il n'est peut être plus à jour.* - -Sinatra est un [DSL](http://fr.wikipedia.org/wiki/Langage_dédié) pour -créer rapidement et facilement des applications web en Ruby : - -``` ruby -# mon_application.rb -require 'sinatra' - -get '/' do - 'Bonjour le monde !' -end -``` - -Installez la gem Sinatra : - -``` shell -gem install sinatra -``` - -Puis lancez votre programme : - -``` shell -ruby mon_application.rb -``` - -Le résultat est visible sur : http://localhost:4567 - -Il est recommandé d'exécuter également `gem install thin`, pour que -Sinatra utilise le server Thin quand il est disponible. - -## Table des matières - -* [Sinatra](#sinatra) - * [Table des matières](#table-des-matières) - * [Routes](#routes) - * [Conditions](#conditions) - * [Valeurs de retour](#valeurs-de-retour) - * [Masques de route spécifiques](#masques-de-route-spécifiques) - * [Fichiers statiques](#fichiers-statiques) - * [Vues / Templates](#vues--templates) - * [Templates littéraux](#templates-littéraux) - * [Langages de template disponibles](#langages-de-template-disponibles) - * [Templates Haml](#templates-haml) - * [Templates Erb](#templates-erb) - * [Templates Builder](#templates-builder) - * [Templates Nokogiri](#templates-nokogiri) - * [Templates Sass](#templates-sass) - * [Templates SCSS](#templates-scss) - * [Templates Less](#templates-less) - * [Templates Liquid](#templates-liquid) - * [Templates Markdown](#templates-markdown) - * [Templates Textile](#templates-textile) - * [Templates RDoc](#templates-rdoc) - * [Templates Radius](#templates-radius) - * [Templates Markaby](#templates-markaby) - * [Templates RABL](#templates-rabl) - * [Templates Slim](#templates-slim) - * [Templates Creole](#templates-creole) - * [Templates CoffeeScript](#templates-coffeescript) - * [Templates Stylus](#templates-stylus) - * [Templates Yajl](#templates-yajl) - * [Templates WLang](#templates-wlang) - * [Accéder aux variables dans un Template](#accéder-aux-variables-dans-un-template) - * [Templates avec `yield` et layouts imbriqués](#templates-avec-yield-et-layouts-imbriqués) - * [Templates dans le fichier source](#templates-dans-le-fichier-source) - * [Templates nommés](#templates-nommés) - * [Associer des extensions de fichier](#associer-des-extensions-de-fichier) - * [Ajouter son propre moteur de rendu](#ajouter-son-propre-moteur-de-rendu) - * [Filtres](#filtres) - * [Helpers](#helpers) - * [Utiliser les sessions](#utiliser-les-sessions) - * [Halt](#halt) - * [Passer](#passer) - * [Déclencher une autre route](#déclencher-une-autre-route) - * [Définir le corps, le code retour et les entêtes](#définir-le-corps-le-code-retour-et-les-entêtes) - * [Faire du streaming](#faire-du-streaming) - * [Journalisation (Logging)](#journalisation-logging) - * [Types Mime](#types-mime) - * [Former des URLs](#former-des-urls) - * [Redirection du navigateur](#redirection-du-navigateur) - * [Contrôle du cache](#contrôle-du-cache) - * [Envoyer des fichiers](#envoyer-des-fichiers) - * [Accéder à l'objet requête](#accéder-à-lobjet-requête) - * [Fichiers joints](#fichiers-joints) - * [Gérer Date et Time](#gérer-date-et-time) - * [Chercher les fichiers de templates](#chercher-les-fichiers-de-templates) - * [Configuration](#configuration) - * [Se protéger des attaques](#se-protéger-des-attaques) - * [Paramètres disponibles](#paramètres-disponibles) - * [Environements](#environements) - * [Gérer les erreurs](#gérer-les-erreurs) - * [NotFound](#notfound) - * [Error](#error) - * [Les Middlewares Rack](#les-middlewares-rack) - * [Tester](#tester) - * [Sinatra::Base - Les Middlewares, Bibliothèques, et Applications Modulaires](#sinatrabase---les-middlewares-bibliothèques-et-applications-modulaires) - * [Style modulaire vs. style classique](#style-modulaire-vs-style-classique) - * [Servir une application modulaire](#servir-une-application-modulaire) - * [Utiliser une application de style classique avec un fichier config.ru](#utiliser-une-application-de-style-classique-avec-un-fichier-configru) - * [Quand utiliser un fichier config.ru ?](#quand-utiliser-un-fichier-configru-) - * [Utiliser Sinatra comme Middleware](#utiliser-sinatra-comme-middleware) - * [Création dynamique d'applications](#création-dynamique-dapplications) - * [Contextes et Binding](#contextes-et-binding) - * [Contexte de l'application/classe](#contexte-de-lapplicationclasse) - * [Contexte de la requête/instance](#contexte-de-la-requêteinstance) - * [Le contexte de délégation](#le-contexte-de-délégation) - * [Ligne de commande](#ligne-de-commande) - * [Configuration nécessaire](#configuration-nécessaire) - * [Essuyer les plâtres](#essuyer-les-plâtres) - * [Installer avec Bundler](#installer-avec-bundler) - * [Faire un clone local](#faire-un-clone-local) - * [Installer globalement](#installer-globalement) - * [Versions](#versions) - * [Mais encore](#mais-encore) - -## Routes - -Dans Sinatra, une route est une méthode HTTP couplée à un masque (pattern) -URL. Chaque route est associée à un bloc : - -``` ruby -get '/' do - .. montrer quelque chose .. -end - -post '/' do - .. créer quelque chose .. -end - -put '/' do - .. remplacer quelque chose .. -end - -patch '/' do - .. changer quelque chose .. -end - -delete '/' do - .. effacer quelque chose .. -end - -options '/' do - .. paramétrer quelque chose .. -end - -link '/' do - .. relier quelque chose .. -end - -unlink '/' do - .. séparer quelque chose .. -end -``` - -Les routes sont évaluées dans l'ordre où elles ont été définies. La première -route qui correspond à la requête est appelée. - -Les masques peuvent inclure des paramètres nommés, accessibles par -l'intermédiaire du hash `params` : - -``` ruby -get '/bonjour/:nom' do - # répond aux requêtes "GET /bonjour/foo" et "GET /bonjour/bar" - # params[:nom] est 'foo' ou 'bar' - "Bonjour #{params[:nom]} !" -end -``` - -Vous pouvez aussi accéder aux paramètres nommés directement grâce aux -paramètres du bloc comme ceci : - -``` ruby -get '/bonjour/:nom' do |n| - # répond aux requêtes "GET /bonjour/foo" et "GET /bonjour/bar" - # params[:nom] est 'foo' ou 'bar' - # n contient params[:nom] - "Bonjour #{n} !" -end -``` - -Une route peut contenir un splat (caractère joker), accessible par -l'intermédiaire du tableau `params[:splat]` : - -``` ruby -get '/dire/*/a/*' do - # répond à /dire/bonjour/a/monde - params[:splat] # => ["bonjour", "monde"] -end - -get '/telecharger/*.*' do - # répond à /telecharger/chemin/vers/fichier.xml - params[:splat] # => ["chemin/vers/fichier", "xml"] -end -``` - -Ou par l'intermédiaire des paramètres du bloc : - -``` ruby -get '/telecharger/*.*' do |chemin, ext| - [chemin, ext] # => ["path/to/file", "xml"] -end -``` - -Une route peut aussi être définie par une expression régulière : - -``` ruby -get %r{/bonjour/([\w]+)} do - "Bonjour, #{params[:captures].first} !" -end -``` - -Là encore on peut utiliser les paramètres de bloc : - -``` ruby -get %r{/bonjour/([\w]+)} do |c| - "Bonjour, #{c} !" -end -``` - -Les routes peuvent aussi comporter des paramètres optionnels : - -``` ruby -get '/posts.?:format?' do - # répond à "GET /posts" et aussi à "GET /posts.json", "GET /posts.xml" etc... -end -``` - -A ce propos, à moins d'avoir désactivé la protection contre les attaques par -"path transversal" (voir plus loin), l'URL demandée peut avoir été modifiée -avant d'être comparée à vos routes. - -## Conditions - -Les routes peuvent définir toutes sortes de conditions, comme par exemple le -"user agent" : - -``` ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "Vous utilisez Songbird version #{params[:agent][0]}" -end - -get '/foo' do - # Correspond à tous les autres navigateurs -end -``` - -Les autres conditions disponibles sont `host_name` et `provides` : - -``` ruby -get '/', :host_name => /^admin\./ do - "Zone Administrateur, Accès refusé !" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -Vous pouvez facilement définir vos propres conditions : - -``` ruby -set(:probability) { |value| condition { rand <= value } } - -get '/gagner_une_voiture', :probability => 0.1 do - "Vous avez gagné !" -end - -get '/gagner_une_voiture' do - "Désolé, vous avez perdu." -end -``` - -Utilisez un splat (caractère joker) dans le cas d'une condition qui prend -plusieurs valeurs : - -``` ruby -set(:auth) do |*roles| # <- ici on utilise un splat - condition do - unless logged_in? && roles.any? {|role| current_user.in_role? role } - redirect "/login/", 303 - end - end -end - -get "/mon/compte/", :auth => [:user, :admin] do - "Informations sur votre compte" -end - -get "/reserve/aux/admins/", :auth => :admin do - "Seuls les administrateurs sont acceptés ici !" -end -``` - -## Valeurs de retour - -La valeur renvoyée par le bloc correspondant à une route constitue le corps de -la réponse qui sera transmise au client HTTP ou du moins au prochain middleware -dans la pile Rack. Le plus souvent, il s'agit d'une chaîne de caractères, -comme dans les exemples précédents. Cependant, d'autres valeurs sont -acceptées. - -Vous pouvez renvoyer n'importe quel objet qu'il s'agisse d'une réponse Rack -valide, d'un corps de réponse Rack ou d'un code statut HTTP : - -* Un tableau de 3 éléments : `[code statut (Fixnum), entêtes (Hash), corps - de la réponse (répondant à #each)]` -* Un tableau de 2 élements : `[code statut (Fixnum), corps de la réponse - (répondant à #each)]` -* Un objet qui répond à `#each` et qui ne transmet que des chaînes de - caractères au bloc fourni -* Un Fixnum représentant le code statut - -Avec cela, on peut facilement implémenter un streaming par exemple : - -``` ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -Vous pouvez aussi utiliser le helper `stream` (présenté un peu plus loin) pour -éviter la surcharge et intégrer le traitement relatif au streaming dans le bloc -de code de la route. - -## Masques de route spécifiques - -Comme cela a été vu auparavant, Sinatra offre la possibilité d'utiliser des -masques sous forme de chaines de caractères ou des expressions régulières -pour définir les routes. Mais il est possible de faire bien plus. Vous pouvez -facilement définir vos propres masques : - -``` ruby -class MasqueToutSauf - Masque = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Masque.new([]) - end - - def match(str) - @caputres unless @except === str - end -end - -def tout_sauf(masque) - MasqueToutSauf.new(masque) -end - -get tout_sauf("/index") do - # ... -end -``` - -Notez que l'exemple ci-dessus est bien trop compliqué et que le même résultat -peut être obtenu avec : - -``` ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -Ou bien en utilisant la forme négative : - -``` ruby -get %r{^(?!/index$)} do - # ... -end -``` - -## Fichiers statiques - -Les fichiers du dossier `./public` sont servis de façon statique. Vous -avez la possibilité d'utiliser un autre répertoire en définissant le paramètre -`:public_folder` : - -``` ruby -set :public_folder, File.dirname(__FILE__) + '/statique' -``` - -Notez que le nom du dossier public n'apparait pas dans l'URL. Le fichier -`./public/css/style.css` sera appelé via l'URL : -`http://exemple.com/css/style.css`. - -Utilisez le paramètre `:static_cache_control` pour ajouter l'information -d'en-tête Cache-Control (voir plus loin). - -## Vues / Templates - -Chaqie langage de template est disponible via sa propre méthode de rendu, -lesquelles renvoient tout simplement une chaîne de caractères. - -``` ruby -get '/' do - erb :index -end -``` - -Ceci effectue le rendu de la vue `views/index.erb`. - -Plutôt que d'utiliser le nom d'un template, vous pouvez directement passer -le contenu du template : - -``` ruby -get '/' do - code = "<%= Time.now %>" - erb code -end -``` - -Les méthodes de templates acceptent un second paramètre, un hash d'options : - -``` ruby -get '/' do - erb :index, :layout => :post -end -``` - -Ceci effectuera le rendu de la vue `views/index.erb` en l'intégrant -au *layout* `views/post.erb` (les vues Erb sont intégrées par défaut -au *layout* `views/layout.erb` quand ce fichier existe). - -Toute option que Sinatra ne comprend pas sera passée au moteur de rendu : - -``` ruby -get '/' do - haml :index, :format => :html5 -end -``` - -Vous pouvez également définir des options par langage de template de façon -générale : - -``` ruby -set :haml, :format => html5 - -get '/' do - haml :index -end -``` - -Les options passées à la méthode de rendu prennent le pas sur les options -définies au moyen de `set`. - -Options disponibles : - -
-
locals
-
- Liste de variables locales passées au document. Pratique pour les vues - partielles. - Exemple : erb "<%= foo %>", :locals => {:foo => "bar"}. -
- -
default_encoding
-
- Encodage de caractères à utiliser en cas d'incertitude. Par défaut, c'est - settings.default_encoding. -
- -
views
-
- Dossier de vues dans lequel chercher les templates. Par défaut - settings.views. -
- -
layout
-
- S'il faut ou non utiliser un layout (true ou false). - Indique le template à utiliser lorsque c'est un symbole. Exemple : - erb :index, :layout => !request.xhr?. -
- -
content_type
-
- Content-Type que le template produit, dépend par défaut du langage de - template. -
- -
scope
-
- Contexte sous lequel effectuer le rendu du template. Par défaut il s'agit - de l'instance de l'application. Si vous changez cela, les variables - d'instance et les méthodes utilitaires ne seront pas disponibles. -
- -
layout_engine
-
- Moteur de rendu à utiliser pour le layout. Utile pour les langages ne - supportant pas les layouts. Il s'agit par défaut du moteur utilisé pour - le rendu du template. Exemple : set :rdoc, :layout_engine => :erb -
- -
layout_options
-
- Options spécifiques destinées au moteur de rendu. Exemple : set :rdoc, - :layout_options => { :views => 'views/layouts' } -
-
- -Les templates sont supposés se trouver directement dans le dossier -`./views`. Pour utiliser un dossier de vues différent : - -``` ruby -set :views, settings.root + '/templates' -``` - -Il est important de se souvenir que les templates sont toujours référencés -sous forme de symboles, même lorsqu'ils sont dans un sous-répertoire (dans -ce cas, utilisez `:'sous_repertoire/template'`). Il faut utiliser -un symbole car les méthodes de rendu évaluent le contenu des chaînes de -caractères au lieu de les considérer comme un chemin vers un fichier. - -### Templates littéraux - -``` ruby -get '/' do - haml '%div.title Bonjour le monde' -end -``` - -Générera le code du template spécifié dans la chaîne de caractères. - -### Langages de template disponibles - -Certains langages ont plusieurs implémentations. Pour préciser l'implémentation -à utiliser (et garantir l'aspect thread-safe), vous devez simplement l'avoir -chargée au préalable : - -``` ruby -require 'rdiscount' # ou require 'bluecloth' -get('/') { markdown :index } -``` - -#### Templates Haml - - - - - - - - - - - - - - -
Dépendanceshaml
Extensions de fichier.haml
Exemplehaml :index, :format => :html5
- -#### Templates Erb - - - - - - - - - - - - - - -
Dépendances - erubis - ou erb (inclus avec Ruby) -
Extensions de fichier.erb, .rhtml ou .erubis (Erubis seulement)
Exempleerb :index
- -#### Templates Builder - - - - - - - - - - - - - - -
Dépendances - builder -
Extensions de fichier.builder
Exemplebuilder { |xml| xml.em "salut" }
- -Ce moteur accepte également un bloc pour des templates en ligne (voir -exemple). - -#### Templates Nokogiri - - - - - - - - - - - - - - -
Dépendancesnokogiri
Extensions de fichier.nokogiri
Exemplenokogiri { |xml| xml.em "salut" } -
- -Ce moteur accepte également un bloc pour des templates en ligne (voir -exemple). - -#### Templates Sass - - - - - - - - - - - - - - -
Dépendancessass
Extensions de fichier.sass
Exemplesass :stylesheet, :style => :expanded
- -#### Templates SCSS - - - - - - - - - - - - - - -
Dépendancessass
Extensions de fichier.scss
Exemplescss :stylesheet, :style => :expanded

-
- -#### Templates Less - - - - - - - - - - - - - - -
Dépendancesless
Extensions de fichier.less
Exempleless :stylesheet -
- -#### Templates Liquid - - - - - - - - - - - - - - -
Dépendancesliquid
Extensions de fichier.liquid
Exempleliquid :index, :locals => { :key => 'value' }
- -Comme vous ne pouvez appeler de méthodes Ruby (autres que `yield`) -dans un template Liquid, vous aurez sûrement à lui passer des variables -locales. - -#### Templates Markdown - - - - - - - - - - - - - - - -

Dépendances

- Au choix : - RDiscount, - RedCarpet, - BlueCloth, - kramdown, - maruku -
Extensions de fichier.markdown, .mkd et .md
Exemplemarkdown :index, :layout_engine => :erb
- -Il n’est pas possible d’appeler des méthodes depuis markdown, ni de -lui passer des variables locales. Par conséquent, il sera souvent utilisé -en combinaison avec un autre moteur de rendu : - -``` ruby -erb :overview, :locals => { :text => markdown(:introduction) } -``` - -Notez que vous pouvez également appeler la méthode `markdown` au -sein d’autres templates : - -``` ruby -%h1 Hello From Haml ! -%p= markdown(:greetings) -``` - -Comme vous ne pouvez pas appeler de Ruby au sein de Markdown, vous ne -pouvez pas utiliser de layouts écrits en Markdown. Toutefois, il -est possible d’utiliser un moteur de rendu différent pour le template et -pour le layout en utilisant l’option `:layout_engine`. - -#### Templates Textile - - - - - - - - - - - - - - -
DépendancesRedCloth
Extensions de fichier.textile
Exempletextile :index, :layout_engine => :erb
- -Il n’est pas possible d’appeler des méthodes depuis textile, ni de lui -passer des variables locales. Par conséquent, il sera souvent utilisé en -combinaison avec un autre moteur de rendu : - -``` ruby -erb :overview, :locals => { :text => textile(:introduction) } -``` - -Notez que vous pouvez également appeler la méthode `textile` au -sein d’autres templates : - -``` ruby -%h1 Hello From Haml ! -%p= textile(:greetings) -``` - -Comme vous ne pouvez pas appeler de Ruby au sein de Textile, vous ne pouvez -pas utiliser de layouts écrits en Textile. Toutefois, il est -possible d’utiliser un moteur de rendu différent pour le template et -pour le layout en utilisant l’option `:layout_engine`. - -#### Templates RDoc - - - - - - - - - - - - - - -
DépendancesRDoc
Extensions de fichier.rdoc
Exemplerdoc :README, :layout_engine => :erb
- -Il n’est pas possible d’appeler des méthodes depuis rdoc, ni de lui -passer des variables locales. Par conséquent, il sera souvent utilisé en -combinaison avec un autre moteur de rendu : - -``` ruby -erb :overview, :locals => { :text => rdoc(:introduction) } -``` - -Notez que vous pouvez également appeler la méthode `rdoc` au sein -d’autres templates : - -``` ruby -%h1 Hello From Haml ! -%p= rdoc(:greetings) -``` - -Comme vous ne pouvez pas appeler de Ruby au sein de RDoc, vous ne pouvez -pas utiliser de layouts écrits en RDoc. Toutefois, il est -possible d’utiliser un moteur de rendu différent pour le template et -pour le layout en utilisant l’option `:layout_engine`. - -#### Templates Radius - - - - - - - - - - - - - -
DépendancesRadius
Extensions de fichier.radius
Exempleradius :index, :locals => { :key => 'value' }
- -Comme vous ne pouvez pas appeler de méthodes Ruby depuis un template -Radius, vous aurez sûrement à lui passer des variables locales. - -#### Templates Markaby - - - - - - - - - - - - - - -
DépendancesMarkaby
Extensions de fichier.mab
Exemplemarkaby { h1 "Bienvenue !" }
- -Ce moteur accepte également un bloc pour des templates en ligne (voir -exemple). - -#### Templates RABL - - - - - - - - - - - - - - -
DépendancesRabl
Extensions de fichier.rabl
Exemplerabl :index
- -#### Templates Slim - - - - - - - - - - - - - - -
DépendancesSlim Lang
Extensions de fichier.slim
Exempleslim :index
- -#### Templates Creole - - - - - - - - - - - - - - -
DépendancesCreole
Extensions de fichier.creole
Exemplecreole :wiki, :layout_engine => :erb
- -Il n'est pas possible d'appeler des méthodes depuis creole, ni de lui -passer des variables locales. Par conséquent, il sera souvent utilisé en -combinaison avec un autre moteur de rendu : - -``` ruby -erb :overview, :locals => { :text => markdown(:introduction) } -``` - -Notez que vous pouvez également appeler la méthode `creole` au sein d'autres -templates : - -``` ruby -%h1 Hello From Haml ! -%p= creole(:greetings) -``` - -Comme vous ne pouvez pas appeler de Ruby au sein de Creole, vous ne pouvez -pas utiliser de layouts écrits en Creole. Toutefois, il est possible -d'utiliser un moteur de rendu différent pour le template et pour le layout -en utilisant l'option `:layout_engine`. - -#### Templates CoffeeScript - - - - - - - - - - - - - - -
Dépendances - - CoffeeScript - - et un - - moyen d'exécuter javascript - -
Extensions de fichier.coffee
Exemplecoffee :index
- -#### Templates Stylus - - - - - - - - - - - - - - -
Dépendances - - Stylus - - et un - - moyen d'exécuter javascript - -
Extensions de fichier.styl
Exemplestylus :index
- -Avant de pouvoir utiliser des templates Stylus, vous devez auparavant charger -`stylus` et `stylus/tilt` : - -``` ruby -require 'sinatra' -require 'stylus' -require 'stylus/tilt' - -get '/' do - stylus :exemple -end -``` - -#### Templates Yajl - - - - - - - - - - - - - - -
Dépendances - yajl-ruby -
Extensions de fichier.yajl
Exempleyajl :index, :locals => { :key => 'qux' }, :callback => 'present', :variable => 'resource'

-
- -Le source du template est évalué en tant que chaine Ruby, puis la -variable json obtenue est convertie avec #to_json. - -``` ruby -json = { :foo => 'bar' } -json[:baz] = key -``` - -Les options `:callback` et `:variable` peuvent être utilisées pour décorer -l’objet retourné. - -``` ruby -var resource = {"foo":"bar","baz":"qux"}; present(resource); -``` - -#### Templates WLang - - - - - - - - - - - - - - -
Dépendanceswlang
Extensions de fichier.wlang
Exemplewlang :index, :locals => { :key => 'value' }
- -L’appel de code ruby au sein des templates n’est pas idiomatique en wlang. -L’écriture de templates sans logique est encouragé, via le passage de variables -locales. Il est néanmoins possible d’écrire un layout en wlang et d’y utiliser -`yield`. - -### Accéder aux variables dans un Template - -Un template est évalué dans le même contexte que l'endroit d'où il a été -appelé (gestionnaire de route). Les variables d'instance déclarées dans le -gestionnaire de route sont directement accessibles dans le template : - -``` ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.nom' -end -``` - -Alternativement, on peut passer un hash contenant des variables locales : - -``` ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= foo.nom', :locals => { :foo => foo } -end -``` - -Ceci est généralement utilisé lorsque l'on veut utiliser un template comme -partiel (depuis un autre template) et qu'il est donc nécessaire d'adapter les -noms de variables. - - -### Templates avec `yield` et layouts imbriqués - -En général, un layout est un simple template qui appelle `yield`. Ce genre de -template peut s'utiliser via l'option `:template` comme décrit précédemment ou -peut être rendu depuis un bloc : - -``` ruby -erb :post, :layout => false do - erb :index -end -``` - -Ce code est à globalement équivalent à `erb :index, :layout => :post`. - -Le fait de passer des blocs aux méthodes de rendu est particulièrement utile -pour gérer des templates imbriqués : - -``` ruby -erb :main_layout, :layout => false do - erb :admin_layout do - erb :user - end -end -``` - -Ce qui peut aussi être fait avec un peu moins de code : - -``` ruby -erb :admin_layout, :layout => :main_layout do - erb :user -end -``` - -Actuellement, les méthodes de rendu qui acceptent un bloc sont : `erb`, `haml`, -`liquid`, `slim ` et `wlang`. La méthode générale `render` accepte elle aussi -un bloc. - - -### Templates dans le fichier source - -Des templates peuvent être définis dans le fichier source comme ceci : - -``` ruby -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Bonjour le monde ! -``` - -NOTE : Les templates du fichier source qui contient `require 'sinatra'` -sont automatiquement chargés. Si vous avez des templates dans d'autres -fichiers source, il faut explicitement les déclarer avec -`enable :inline_templates`. - - -### Templates nommés - -Les templates peuvent aussi être définis grâce à la méthode de haut niveau `template` : - -``` ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Bonjour le monde !' -end - -get '/' do - haml :index -end -``` - -Si un template nommé "layout" existe, il sera utilisé à chaque fois qu'un -template sera affiché. Vous pouvez désactivez les layouts au cas par cas en -passant `:layout => false` ou bien les désactiver par défaut au moyen -de `set :haml, :layout => false` : - -``` ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -### Associer des extensions de fichier - -Pour associer une extension de fichier avec un moteur de rendu, utilisez -`Tilt.register`. Par exemple, si vous désirez utiliser l'extension -de fichier `tt` pour les templates Textile, vous pouvez faire comme suit : - -``` ruby -Tilt.register :tt, Tilt[:textile] -``` - -### Ajouter son propre moteur de rendu - -En premier lieu, déclarez votre moteur de rendu avec Tilt, ensuite créez -votre méthode de rendu : - -``` ruby -Tilt.register :monmoteur, MonMerveilleurMoteurDeRendu - -helpers do - def monmoteur(*args) render(:monmoteur, *args) end -end - -get '/' do - monmoteur :index -end -``` - -Utilisera `./views/index.monmoteur`. Voir [le dépôt Github](https://github.com/rtomayko/tilt) pour en savoir plus sur Tilt. - -## Filtres - -Les filtres before sont exécutés avant chaque requête, dans le même contexte -que les routes, et permettent de modifier la requête et sa réponse. Les -variables d'instance déclarées dans les filtres sont accessibles au niveau -des routes et des templates : - -``` ruby -before do - @note = 'Coucou !' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @note #=> 'Coucou !' - params[:splat] #=> 'bar/baz' -end -``` - -Les filtres after sont exécutés après chaque requête à l'intérieur du même -contexte et permettent de modifier la requête et sa réponse. Les variables -d'instance déclarées dans les filtres before ou les routes sont accessibles -au niveau des filtres after : - -``` ruby -after do - puts response.status -end -``` - -Note : Le corps de la réponse n'est pas disponible au niveau du filtre after -car il ne sera généré que plus tard (sauf dans le cas où vous utilisez la -méthode `body` au lieu de simplement renvoyer une chaine depuis vos routes). - -Les filtres peuvent être associés à un masque, ce qui permet de limiter leur -exécution aux cas où la requête correspond à ce masque : - -``` ruby -before '/secret/*' do - authentification! -end - -after '/faire/:travail' do |travail| - session[:dernier_travail] = travail -end -``` - -Tout comme les routes, les filtres acceptent également des conditions : - -``` ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'example.com' do - # ... -end -``` - -## Helpers - -Utilisez la méthode de haut niveau `helpers` pour définir des routines -qui seront accessibles dans vos gestionnaires de route et dans vos templates : - -``` ruby -helpers do - def bar(nom) - "#{nom}bar" - end -end - -get '/:nom' do - bar(params[:nom]) -end -``` - -Vous pouvez aussi définir les méthodes helper dans un module séparé : - -``` ruby -module FooUtils - def foo(nom) "#{nom}foo" end -end - -module BarUtils - def bar(nom) "#{nom}bar" end -end - -helpers FooUtils, BarUtils -``` - -Cela a le même résultat que d'inclure les modules dans la classe de -l'application. - -### Utiliser les sessions - -Une session est utilisée pour conserver un état entre les requêtes. Une fois -activées, vous avez un hash de session par session utilisateur : - -``` ruby -enable :sessions - -get '/' do - "valeur = " << session[:valeur].inspect -end - -get '/:value' do - session[:valeur] = params[:valeur] -end -``` - -Notez que `enable :sessions` enregistre en fait toutes les données dans -un cookie. Ce n'est pas toujours ce que vous voulez (enregistrer beaucoup de -données va augmenter le traffic par exemple). Vous pouvez utiliser n'importe -quel middleware Rack de session afin d'éviter cela. N'utilisez **pas** -`enable :sessions` dans ce cas mais chargez le middleware de votre -choix comme vous le feriez pour n'importe quel autre middleware : - -``` ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "valeur = " << session[:valeur].inspect -end - -get '/:value' do - session[:valeur] = params[:valeur] -end -``` - -Pour renforcer la sécurité, les données de session dans le cookie sont signées -avec une clé secrète de session. Une clé secrète est générée pour vous au -hasard par Sinatra. Toutefois, comme cette clé change à chaque démarrage de -votre application, vous pouvez définir cette clé vous-même afin que toutes -les instances de votre application la partage : - -``` ruby -set :session_secret, 'super secret' -``` - -Si vous souhaitez avoir plus de contrôle, vous pouvez également enregistrer un -hash avec des options lors de la configuration de `sessions` : - -``` ruby -set :sessions, :domain => 'foo.com' -``` - -Pour que les différents sous-domaines de foo.com puisse partager une session, -vous devez préfixer le domaine par *.* : - -``` ruby -set :sessions, :domain => '.foo.com' -``` - - -### Halt - -Pour arrêter immédiatement la requête dans un filtre ou un gestionnaire de -route : - -``` ruby -halt -``` - -Vous pouvez aussi passer le code retour ... - -``` ruby -halt 410 -``` - -Ou le texte ... - -``` ruby -halt 'Ceci est le texte' -``` - -Ou les deux ... - -``` ruby -halt 401, 'Partez !' -``` - -Ainsi que les entêtes ... - -``` ruby -halt 402, {'Content-Type' => 'text/plain'}, 'revanche' -``` - -Bien sûr il est possible de combiner un template avec `halt` : - -``` ruby -halt erb(:erreur) -``` - -### Passer - -Une route peut passer le relais aux autres routes qui correspondent également -avec `pass` : - -``` ruby -get '/devine/:qui' do - pass unless params[:qui] == 'Frank' - "Tu m'as eu !" -end - -get '/devine/*' do - 'Manqué !' -end -``` - -On sort donc immédiatement de ce gestionnaire et on continue à chercher, -dans les masques suivants, le prochain qui correspond à la requête. -Si aucun des masques suivants ne correspond, un code 404 est retourné. - -### Déclencher une autre route - -Parfois, `pass` n'est pas ce que vous recherchez, au lieu de cela vous -souhaitez obtenir le résultat d'une autre route. Pour cela, utilisez -simplement `call` : - -``` ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do - "bar" -end -``` - -Notez que dans l'exemple ci-dessus, vous faciliterez les tests et améliorerez -la performance en déplaçant simplement `"bar"` dans un helper -utilisé à la fois par `/foo` et `/bar`. - -Si vous souhiatez que la requête soit envoyée à la même instance de -l'application plutôt qu'à une copie, utilisez `call!` au lieu de -`call`. - -Lisez la spécification Rack si vous souhaitez en savoir plus sur -`call`. - -### Définir le corps, le code retour et les entêtes - -Il est possible et recommandé de définir le code retour et le corps de la -réponse au moyen de la valeur de retour d'un bloc définissant une route. -Quoiqu'il en soit, dans certains cas vous pourriez avoir besoin de définir -le coprs de la réponse à un moment arbitraire de l'exécution. Vous pouvez le -faire au moyen de la méthode `body`. Si vous faites ainsi, vous pouvez alors -utiliser cette même méthode pour accéder au corps de la réponse : - -``` ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -``` - -Il est également possible de passer un bloc à `body`, qui sera exécuté par le -gestionnaire Rack (ceci peut être utilisé pour implémenter un streaming, -voir "Valeurs de retour"). - -Pareillement au corps de la réponse, vous pouvez également définir le code -retour et les entêtes : - -``` ruby -get '/foo' do - status 418 - headers \ - "Allow" => "BREW, POST, GET, PROPFIND, WHEN", - "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - body "Je suis une théière !" -end -``` - -Comme `body` `headers` et `status` peuvent être utilisés sans arguments -pour accéder à leurs valeurs. - -### Faire du streaming - -Il y a des cas où vous voulez commencer à renvoyer des données pendant que -vous êtes en train de générer le reste de la réponse. Dans les cas les plus -extrèmes, vous souhaitez continuer à envoyer des données tant que le client -n'abandonne pas la connection. Vous pouvez alors utiliser le helper `stream` -pour éviter de créer votre propre système : - -``` ruby -get '/' do - stream do |out| - out << "Ca va être hallu -\n" - sleep 0.5 - out << " (attends la suite) \n" - sleep 1 - out << "- cinant !\n" - end -end -``` - -Cela permet d'implémenter des API de streaming ou de -[Server Sent Events](http://dev.w3.org/html5/eventsource/) et peut servir de -base pour des [WebSockets](http://en.wikipedia.org/wiki/WebSocket). Vous -pouvez aussi l'employer pour augmenter le débit quand une partie du contenu -provient d'une resource lente. - -Le fonctionnement du streaming, notamment le nombre de requêtes simultanées, -dépend énormément du serveur web utilisé. Certains ne prennent pas du tout en -charge le streaming (WEBRick par exemple). Lorsque le serveur ne gère pas le -streaming, la partie body de la réponse sera envoyée au client en une seule -fois, après que l'exécution du bloc passé au helper `stream` sera terminée. Le -streaming ne fonctionne pas du tout avec Shotgun. - -En utilisant le helper stream avec le paramètre `keep_open`, il n'appelera -pas la méthode `close` du flux, vous laissant la possibilité de le fermer à -tout moment au cours de l'exécution. Ceci ne fonctionne qu'avec les serveurs -evented (ie non threadés) tels que Thin et Rainbows. Les autres serveurs -fermeront malgré tout le flux : - -``` ruby -# interrogation prolongée - -set :server, :thin -connexions = [] - -get '/souscrire' do - # abonne un client aux évènements du serveur - stream(:keep_open) { |out| connexions << out } - - # purge les connexions abandonnées - connexions.reject!(&:closed?) - - # compte-rendu - "abonné" -end - -post '/message' do - connexions.each do |out| - # prévient le client qu'un nouveau message est arrivé - out << params[:message] << "\n" - - # indique au client de se connecter à nouveau - out.close - end - - # compte-rendu - "message reçu" -end -``` - -### Journalisation (Logging) - -Dans le contexte de la requête, la méthode utilitaire `logger` expose une -instance de `Logger` : - -``` ruby -get '/' do - logger.info "chargement des données" - # ... -end -``` - -Ce logger va automatiquement prendre en compte les paramètres de -configuration pour la journalisation de votre gestionnaire Rack. Si la -journalisation est désactivée, cette méthode renverra un objet factice et -vous n'avez pas à vous en inquiéter dans vos routes en le filtrant. - -Notez que la journalisation est seulement activée par défaut pour -`Sinatra::Application`, donc si vous héritez de `>Sinatra::Base`, -vous aurez à l'activer vous-même : - -``` ruby -class MonApp < Sinatra::Base - configure :production, :development do - enable :logging - end -end -``` - -Si vous souhaitez utiliser votre propre logger, vous devez définir le paramètre -`logging` à `nil` pour être certain qu'aucun middleware de logging ne sera -installé (notez toutefois que `logger` renverra alors `nil`). Dans ce cas, -Sinatra utilisera ce qui sera présent dans `env['rack.logger']`. - -### Types Mime - -Quand vous utilisez `send_file` ou des fichiers statiques, vous -pouvez rencontrer des types mime que Sinatra ne connaît pas. Utilisez -`mime_type` pour les déclarer par extension de fichier : - -``` ruby -configure do - mime_type :foo, 'text/foo' -end -``` - -Vous pouvez également les utiliser avec la méthode `content_type` : - -``` ruby -get '/' do - content_type :foo - "foo foo foo" -end -``` - -### Former des URLs - -Pour former des URLs, vous devriez utiliser la méthode `url`, par exemple en -Haml : - -``` ruby -%a{:href => url('/foo')} foo -``` - -Cela prend en compte les proxy inverse et les routeurs Rack, s'ils existent. - -Cette méthode est également disponible sous l'alias `to` (voir ci-dessous -pour un exemple). - -### Redirection du navigateur - -Vous pouvez déclencher une redirection du navigateur avec la méthode -`redirect` : - -``` ruby -get '/foo' do - redirect to('/bar') -end -``` - -Tout paramètre additionnel est géré comme des arguments pour la méthode -`halt` : - -``` ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'mauvais endroit mon pote' -``` - -Vous pouvez aussi rediriger vers la page dont l'utilisateur venait au moyen de -`redirect back` : - -``` ruby -get '/foo' do - "faire quelque chose" -end - -get '/bar' do - faire_quelque_chose - redirect back -end -``` - -Pour passer des arguments à une redirection, ajoutez-les soit à la requête : - -``` ruby -redirect to('/bar?sum=42') -``` - -Ou bien utilisez une session : - -``` ruby -enable :sessions - -get '/foo' do - session[:secret] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secret] -end -``` - -### Contrôle du cache - -Définir correctement vos entêtes à la base pour un bon cache HTTP. - -Vous pouvez facilement définir l'entête Cache-Control de la manière suivante : - -``` ruby -get '/' do - cache_control :public - "met le en cache !" -end -``` - -Conseil de pro : définir le cache dans un filtre before : - -``` ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -``` - -Si vous utilisez la méthode `expires` pour définir l'entête correspondant, -`Cache-Control` sera alors défini automatiquement : - -``` ruby -before do - expires 500, :public, :must_revalidate -end -``` - -Pour utiliser correctement les caches, vous devriez utiliser `etag` ou -`last_modified`. Il est recommandé d'utiliser ces méthodes *avant* de faire -d'importantes modifications, car elles vont immédiatement déclencher la réponse -si le client a déjà la version courante dans son cache : - -``` ruby -get '/article/:id' do - @article = Article.find params[:id] - last_modified @article.updated_at - etag @article.sha1 - erb :article -end -``` - -Il est également possible d'utiliser un -[weak ETag](http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation) : - -``` ruby -etag @article.sha1, :weak -``` - -Ces méthodes ne sont pas chargées de mettre des données en cache, mais elles -fournissent les informations nécessaires pour votre cache. Si vous êtes à la -recherche de solutions rapides pour un reverse-proxy de cache, essayez -[rack-cache](https://github.com/rtomayko/rack-cache) : - -``` ruby -require "rack/cache" -require "sinatra" - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hello" -end -``` - -Utilisez le paramètre `:static_cache_control` pour ajouter l'information -d'en-tête `Cache-Control` (voir plus loin). - -D'après la RFC 2616, votre application devrait se comporter différement lorsque -l'en-tête If-Match ou If-None-Match est défini à `*` en tenant compte du -fait que la resource demandée existe déjà ou pas. Sinatra considère que les -requêtes portant sur des resources sûres (tel que get) ou idempotentes (tel que -put) existent déjà et pour les autres resources (par exemple dans le cas -de requêtes post) qu'il s'agit de nouvelles resources. Vous pouvez modifier ce -comportement en passant une option `:new_resource` : - -``` ruby -get '/create' do - etag '', :new_resource => true - Article.create - erb :new_article -end -``` - -Si vous souhaitez utilisez un ETag faible, utilisez l'option :kind : - -``` ruby -etag '', :new_resource => true, :kind => :weak -``` - -### Envoyer des fichiers - -Pour envoyer des fichiers, vous pouvez utiliser la méthode `send_file` : - -``` ruby -get '/' do - send_file 'foo.png' -end -``` - -Quelques options sont également acceptées : - -``` ruby -send_file 'foo.png', :type => :jpg -``` - -Les options sont : - -
-
filename
-
- le nom du fichier dans la réponse, par défaut le nom du fichier envoyé. -
- -
last_modified
-
- valeur pour l’entête Last-Modified, par défaut la date de modification du - fichier -
- -
type
-
- type de contenu à utiliser, deviné à partir de l’extension de fichier si - absent -
- -
disposition
-
- utilisé pour Content-Disposition, les valuers possibles étant : nil - (par défaut), :attachment et :inline -
- -
length
-
entête Content-Length, par défaut la taille du fichier
- -
status
-
- code état à renvoyer. Utile quand un fichier statique sert de page d’erreur. -
-
- -Si le gestionnaire Rack le supporte, d'autres moyens que le streaming via le -processus Ruby seront utilisés. Si vous utilisez cette méthode, Sinatra gérera -automatiquement les requêtes de type range. - -### Accéder à l'objet requête - -L'objet correspondant à la requête envoyée peut être récupéré dans le contexte -de la requête (filtres, routes, gestionnaires d'erreur) au moyen de la méthode -`request` : - -``` ruby -# application tournant à l'adresse http://exemple.com/exemple -get '/foo' do - t = %w[text/css text/html application/javascript] - request.accept # ['text/html', '*/*'] - request.accept? 'text/xml' # true - request.preferred_type(t) # 'text/html' - request.body # corps de la requête envoyée par le client - # (voir ci-dessous) - request.scheme # "http" - request.script_name # "/exemple" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # taille de request.body - request.media_type # type de média pour request.body - request.host # "exemple.com" - request.get? # true (méthodes similaires pour les autres - # verbes HTTP) - request.form_data? # false - request["UN_ENTETE"] # valeur de l'entête UN_ENTETE - request.referrer # référant du client ou '/' - request.user_agent # user agent (utilisé par la condition :agent) - request.cookies # tableau contenant les cookies du navigateur - request.xhr? # requête AJAX ? - request.url # "http://exemple.com/exemple/foo" - request.path # "/exemple/foo" - request.ip # adresse IP du client - request.secure? # false - request.forwarded? # vrai (si on est derrière un proxy inverse) - request.env # tableau brut de l'environnement fourni par Rack -end -``` - -Certaines options, telles que `script_name` ou `path_info` -peuvent également être modifiées : - -``` ruby -before { request.path_info = "/" } - -get "/" do - "toutes les requêtes arrivent ici" -end -``` - -`request.body` est un objet IO ou StringIO : - -``` ruby -post "/api" do - request.body.rewind # au cas où il a déjà été lu - donnees = JSON.parse request.body.read - "Bonjour #{donnees['nom']} !" -end -``` - -### Fichiers joints - -Vous pouvez utiliser la méthode `attachment` pour indiquer au navigateur que -la réponse devrait être stockée sur le disque plutôt qu'affichée : - - -``` ruby -get '/' do - attachment - "enregistre-le !" -end -``` - -Vous pouvez également lui passer un nom de fichier : - -``` ruby -get '/' do - attachment "info.txt" - "enregistre-le !" -end -``` - -### Gérer Date et Time - -Sinatra fourni un helper `time_for` pour convertir une valeur donnée en -objet `Time`. Il peut aussi faire la conversion à partir d'objets `DateTime`, -`Date` ou de classes similaires : - -``` ruby -get '/' do - pass if Time.now > time_for('Dec 23, 2012') - "encore temps" -end -``` - -Cette méthode est utilisée en interne par `expires`, `last_modified` et -consorts. Par conséquent, vous pouvez très facilement étendre le -fonctionnement de ces méthodes en surchargeant le helper `time_for` dans -votre application : - -``` ruby -helpers do - def time_for(value) - case value - when :yesterday then Time.now - 24*60*60 - when :tomorrow then Time.now + 24*60*60 - else super - end - end -end - -get '/' do - last_modified :yesterday - expires :tomorrow - "salut" -end -``` - -### Chercher les fichiers de templates - -La méthode `find_template` est utilisée pour trouver les fichiers de -templates à générer : - -``` ruby -find_template settings.views, 'foo', Tilt[:haml] do |file| - puts "pourrait être #{file}" -end -``` - -Ce n'est pas très utilise. En revanche, il est utile de pouvoir surcharger -cette méthode afin de définir son propre mécanisme de recherche. Par exemple, -vous pouvez utiliser plus d'un répertoire de vues : - -``` ruby -set :views, ['views', 'templates'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -``` - -Un autre exemple est d'utiliser des répertoires différents pour des moteurs -de rendu différents : - -``` ruby -set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:default] - super(folder, name, engine, &block) - end -end -``` - -Vous pouvez également écrire cela dans une extension et la partager avec -d'autres ! - -Notez que `find_template` ne vérifie pas que le fichier existe mais -va plutôt exécuter le bloc pour tous les chemins possibles. Cela n'induit pas -un problème de performance dans le sens où `render` va utiliser `break` dès -qu'un fichier est trouvé. De plus, l'emplacement des templates (et leur -contenu) est mis en cache si vous n'êtes pas en mode développement. Vous -devriez garder cela en tête si vous écrivez une méthode vraiment dingue. - -## Configuration - -Lancé une seule fois au démarrage de tous les environnements : - -``` ruby -configure do - # définir un paramètre - set :option, 'value' - - # définir plusieurs paramètre - set :a => 1, :b => 2 - - # identique à "set :option, true" - enable :option - - # identique à "set :option, false"" - disable :option - - # vous pouvez également avoir des paramètres dynamiques avec des blocs - set(:css_dir) { File.join(views, 'css') } -end -``` - -Lancé si l'environnement (variable d'environnement RACK_ENV) est défini comme -`:production` : - -``` ruby - configure :production do - ... - end -``` - -Lancé si l'environnement est `:production` ou `:test` : - -``` ruby - configure :production, :test do - ... - end -``` - -Vous pouvez accéder à ces paramètres via `settings` : - -``` ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -``` - -### Se protéger des attaques - -Sinatra utilise [Rack::Protection](https://github.com/rkh/rack-protection#readme) -pour protéger votre application contre les principales attaques opportunistes. -Vous pouvez très simplement désactiver cette fonctionnalité (ce qui exposera -votre application à beaucoup de vulnerabilités courantes) : - -``` ruby -disable :protection -``` - -Pour désactiver seulement un type de protection, vous pouvez définir `protection` -avec un hash d'options : - -``` ruby -set :protection, :except => :path_traversal -``` - -Vous pouvez également lui passer un tableau pour désactiver plusieurs types de -protection : - -``` ruby -set :protection, :except => [:path_traversal, :session_hijacking] -``` - -Par défaut, il faut que `:sessions` soit activé pour que Sinatra mette en place -un système de protection au niveau de la session. Dans le cas où vous gérez -vous même les sessions, vous devez utiliser l'option `:session` pour que cela -soit le cas : - -``` ruby -use Rack::Session::Pool -set :protection, :session => true -``` - -### Paramètres disponibles - -
-
absolute_redirects
-
Si désactivé, Sinatra permettra les redirections relatives. Toutefois, - Sinatra ne sera plus conforme à la RFC 2616 (HTTP 1.1), qui n’autorise - que les redirections absolues.

- - Activez si votre application tourne derrière un proxy inverse qui n’a - pas été correctement configuré. Notez que la méthode url - continuera de produire des URLs absolues, sauf si vous lui passez - false comme second argument.

- -

Désactivé par défaut.

- -
add_charsets
-

types mime pour lesquels la méthode content_type va - automatiquement ajouter l’information du charset.

- -

Vous devriez lui ajouter des valeurs plutôt que de l’écraser :

- -
settings.add_charsets >> "application/foobar"
- -
app_file
-

chemin pour le fichier de l’application principale, utilisé pour - détecter la racine du projet, les dossiers public et vues, et les - templates en ligne.

- -
bind
-
adresse IP sur laquelle se brancher (par défaut : 0.0.0.0). Utiliser - seulement pour le serveur intégré.
- -
default_encoding
-
encodage à utiliser si inconnu (par défaut "utf-8")
- -
dump_errors
-
afficher les erreurs dans le log. -
- -
environment
-
environnement courant, par défaut ENV['RACK_ENV'], ou - "development" si absent.
- -
logging
-
utiliser le logger.
- -
lock
-

Place un lock autour de chaque requête, n’exécutant donc - qu’une seule requête par processus Ruby.

- -

Activé si votre application n’est pas thread-safe. Désactivé - par défaut.

- -
method_override
-
utilise la magie de _method afin de permettre des formulaires - put/delete dans des navigateurs qui ne le permettent pas. - -
-
port
-
port à écouter. Utiliser seulement pour le serveur intégré.
- -
prefixed_redirects
-
si oui ou non request.script_name doit être inséré dans les - redirections si un chemin non absolu est utilisé. Ainsi, redirect - '/foo' se comportera comme redirect to('/foo'). Désactivé - par défaut.
- -
protection
-
défini s’il faut activer ou non la protection contre les attaques web. - Voir la section protection précédente.
- -
public_dir
-
alias pour public_folder. Voir ci-dessous.
- -
public_folder
-
chemin pour le dossier à partir duquel les fichiers publics sont servis. - Utilisé seulement si les fichiers statiques doivent être servis (voir le - paramètre static). Si non défini, il découle du paramètre - app_file.
- -
reload_templates
-
si oui ou non les templates doivent être rechargés entre les requêtes. - Activé en mode développement.
- -
root
-
chemin pour le dossier racine du projet. Si non défini, il découle du - paramètre app_file.
- -
raise_errors
-
soulever les erreurs (ce qui arrêtera l’application). Désactivé par - défaut sauf lorsque environment est défini à - "test".
- -
run
-
si activé, Sinatra s’occupera de démarrer le serveur, ne pas activer si - vous utiliser rackup ou autres.
- -
running
-
est-ce que le serveur intégré est en marche ? ne changez pas ce - paramètre !
- -
server
-
serveur ou liste de serveurs à utiliser pour le serveur intégré. Par - défaut [‘thin’, ‘mongrel’, ‘webrick’], l’ordre indiquant la - priorité.
- -
sessions
-
active le support des sessions basées sur les cookies, en utilisant - Rack::Session::Cookie. Reportez-vous à la section ‘Utiliser les - sessions’ pour plus d’informations.
- -
show_exceptions
-
affiche la trace de l’erreur dans le navigateur lorsqu’une exception se - produit. Désactivé par défaut sauf lorsque environment est - défini à "development".
- -
static
-
Si oui ou non Sinatra doit s’occuper de servir les fichiers statiques. - Désactivez si vous utilisez un serveur capable de le gérer lui même. Le - désactiver augmentera la performance. Activé par défaut pour le style - classique, désactivé pour le style modulaire.
- -
static_cache_control
-
A définir quand Sinatra rend des fichiers statiques pour ajouter les - en-têtes Cache-Control. Utilise le helper cache_control. - Désactivé par défaut. Utiliser un array explicite pour définir des - plusieurs valeurs : set :static_cache_control, [:public, :max_age => - 300]
- -
threaded
-
à définir à true pour indiquer à Thin d’utiliser - EventMachine.defer pour traiter la requête.
- -
views
-
chemin pour le dossier des vues. Si non défini, il découle du paramètre - app_file.
- -
x_cascade
-
- Indique s'il faut ou non définir le header X-Cascade lorsqu'aucune route - ne correspond. Défini à true par défaut. -
-
- -## Environements - -Il existe trois environnements prédéfinis : `"development"`, -`"production"` et `"test"`. Les environements peuvent être -sélectionné via la variable d'environnement `RACK_ENV`. Sa valeur par défaut -est `"development"`. Dans ce mode, tous les templates sont rechargés à -chaque requête. Des handlers spécifiques pour `not_found` et -`error` sont installés pour vous permettre d'avoir une pile de trace -dans votre navigateur. En mode `"production"` et `"test"` les -templates sont mis en cache par défaut. - -Pour exécuter votre application dans un environnement différent, définissez la -variable d'environnement `RACK_ENV` : - -``` shell -RACK_ENV=production ruby my_app.rb -``` - -Vous pouvez utiliser une des méthodes `development?`, `test?` et `production?` -pour déterminer quel est l'environnement en cours : - -``` ruby -get '/' do - if settings.development? - "développement !" - else - "pas en développement !" - end -end -``` - -## Gérer les erreurs - -Les gestionnaires d'erreur s'exécutent dans le même contexte que les routes ou -les filtres, ce qui veut dire que vous avez accès (entre autres) aux bons -vieux `haml`, `erb`, `halt`, etc. - -### NotFound - -Quand une exception Sinatra::NotFound est soulevée, ou que le code -retour est 404, le gestionnaire not_found est invoqué : - -``` ruby -not_found do - 'Pas moyen de trouver ce que vous cherchez' -end -``` - -### Error - -Le gestionnaire `error` est invoqué à chaque fois qu'une exception est -soulevée dans une route ou un filtre. L'objet exception est accessible via la -variable Rack `sinatra.error` : - -``` ruby -error do - 'Désolé mais une méchante erreur est survenue - ' + env['sinatra.error'].name -end -``` - -Erreur sur mesure : - -``` ruby -error MonErreurSurMesure do - 'Donc il est arrivé ceci...' + env['sinatra.error'].message -end -``` - -Donc si ceci arrive : - -``` ruby -get '/' do - raise MonErreurSurMesure, 'quelque chose de mal' -end -``` - -Vous obtenez ça : - - Donc il est arrivé ceci... quelque chose de mal - -Alternativement, vous pouvez avoir un gestionnaire d'erreur associé à un code -particulier : - -``` ruby -error 403 do - 'Accès interdit' -end - -get '/secret' do - 403 -end -``` - -Ou un intervalle : - -``` ruby -error 400..510 do - 'Boom' -end -``` - -Sinatra installe pour vous quelques gestionnaires `not_found` et -`error` génériques lorsque vous êtes en environnement -`development`. - -## Les Middlewares Rack - -Sinatra tourne avec [Rack](http://rack.rubyforge.org/), une interface standard -et minimale pour les web frameworks Ruby. Un des points forts de Rack est le -support de ce que l'on appelle des "middlewares" -- composant qui vient se -situer entre le serveur et votre application, et dont le but est de -visualiser/manipuler la requête/réponse HTTP, et d'offrir diverses -fonctionnalités classiques. - -Sinatra permet de construire facilement des middlewares Rack via la méthode de -haut niveau `use` : - -``` ruby -require 'sinatra' -require 'mon_middleware_perso' - -use Rack::Lint -use MonMiddlewarePerso - -get '/bonjour' do - 'Bonjour le monde' -end -``` - -La sémantique de `use` est identique à celle définie dans le DSL de -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html) -(le plus souvent utilisé dans un fichier rackup). Par exemple, la méthode -`use` accepte divers arguments ainsi que des blocs : - -``` ruby -use Rack::Auth::Basic do |login, password| - login == 'admin' && password == 'secret' -end -``` - -Rack est distribué avec de nombreux middlewares standards pour loguer, débuguer, -faire du routage URL, de l'authentification ou gérer des sessions. Sinatra gère -plusieurs de ces composants automatiquement via son système de configuration, ce -qui vous dispense de faire un `use` en ce qui les concerne. - -Vous trouverez d'autres middlewares intéressants sur -[rack](https://github.com/rack/rack/tree/master/lib/rack), -[rack-contrib](https://github.com/rack/rack-contrib#readm), -ou en consultant le [wiki de Rack](https://github.com/rack/rack/wiki/List-of-Middleware). - -## Tester - -Les tests pour Sinatra peuvent être écrit avec n'importe quelle bibliothèque -basée sur Rack. [Rack::Test](http://gitrdoc.com/brynary/rack-test) est -recommandé : - -``` ruby -require 'mon_application_sinatra' -require 'test/unit' -require 'rack/test' - -class MonTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_ma_racine - get '/' - assert_equal 'Bonjour le monde !', last_response.body - end - - def test_avec_des_parametres - get '/rencontrer', :name => 'Frank' - assert_equal 'Salut Frank !', last_response.body - end - - def test_avec_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "Vous utilisez Songbird !", last_response.body - end -end -``` - -## Sinatra::Base - Les Middlewares, Bibliothèques, et Applications Modulaires - -Définir votre application au niveau supérieur fonctionne bien dans le cas des -micro-applications mais présente pas mal d'inconvénients pour créer des -composants réutilisables sous forme de middlewares Rack, de Rails metal, de -simples librairies avec un composant serveur ou même d'extensions Sinatra. Le -niveau supérieur suppose une configuration dans le style des micro-applications -(une application d'un seul fichier, des répertoires `./public` et -`./views`, des logs, une page d'erreur, etc...). C'est là que -`Sinatra::Base` prend tout son intérêt : - -``` ruby -require 'sinatra/base' - -class MonApplication < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Bonjour le monde !' - end -end -``` - -Les méthodes de la classe `Sinatra::Base` sont parfaitement identiques à -celles disponibles via le DSL de haut niveau. Il suffit de deux modifications -pour transformer la plupart des applications de haut niveau en un composant -`Sinatra::Base` : - -* Votre fichier doit charger `sinatra/base` au lieu de `sinatra`, sinon toutes - les méthodes du DSL Sinatra seront importées dans l'espace de nom principal. -* Les gestionnaires de routes, la gestion d'erreur, les filtres et les options - doivent être placés dans une classe héritant de `Sinatra::Base`. - -`Sinatra::Base` est une page blanche. La plupart des options sont -désactivées par défaut, y compris le serveur intégré. Reportez-vous à -[Options et Configuration](http://sinatra.github.com/configuration.html) -pour plus d'informations sur les options et leur fonctionnement. - -### Style modulaire vs. style classique - -Contrairement aux idées reçues, il n'y a rien de mal à utiliser le style -classique. Si c'est ce qui convient pour votre application, vous n'avez pas -aucune raison de passer à une application modulaire. - -Le principal inconvénient du style classique sur le style modulaire est que vous -ne pouvez avoir qu'une application Ruby par processus Ruby. Si vous pensez en -utiliser plus, passez au style modulaire. Et rien ne vous empêche de mixer style -classique et style modulaire. - -Si vous passez d'un style à l'autre, souvenez-vous des quelques différences -mineures en ce qui concerne les paramètres par défaut : - - Paramètre Classique Modulaire - - app_file fichier chargeant sinatra fichier héritant de Sinatra::Base - run $0 == app_file false - logging true false - method_override true false - inline_templates true false - static true false - -### Servir une application modulaire - -Il y a deux façons de faire pour démarrer une application modulaire, démarrez -avec `run!` : - -``` ruby -# my_app.rb -require 'sinatra/base' - -class MyApp < Sinatra::Base - # ... code de l'application ici ... - - # démarre le serveur si ce fichier est directement exécuté - run! if app_file == $0 -end -``` - -Démarrez ensuite avec : - -``` shell -ruby my_app.rb -``` - -Ou alors avec un fichier `config.ru`, qui permet d'utiliser n'importe -quel gestionnaire Rack : - -``` ruby -# config.ru -require './my_app' -run MyApp -``` - -Exécutez : - -``` shell -rackup -p 4567 -``` - -### Utiliser une application de style classique avec un fichier config.ru - -Ecrivez votre application : - -``` ruby -# app.rb -require 'sinatra' - -get '/' do - 'Bonjour le monde !' -end -``` - -Et un fichier `config.ru` correspondant : - -``` ruby -require './app' -run Sinatra::Application -``` - -### Quand utiliser un fichier config.ru ? - -Quelques cas où vous devriez utiliser un fichier `config.ru` : - -* Vous souhaitez déployer avec un autre gestionnaire Rack (Passenger, Unicorn, - Heroku, ...). -* Vous souhaitez utiliser plus d'une sous-classe de `Sinatra::Base`. -* Vous voulez utiliser Sinatra comme un middleware, non en tant que - endpoint. - -**Il n'est pas nécessaire de passer par un fichier `config.ru` pour la -seule raison que vous êtes passé au style modulaire, et vous n'avez pas besoin -de passer au style modulaire pour utiliser un fichier `config.ru`.** - -### Utiliser Sinatra comme Middleware - -Non seulement Sinatra peut utiliser d'autres middlewares Rack, il peut -également être à son tour utilisé au-dessus de n'importe quel endpoint Rack -en tant que middleware. Ce endpoint peut très bien être une autre -application Sinatra, ou n'importe quelle application basée sur Rack -(Rails/Ramaze/Camping/...) : - -``` ruby -require 'sinatra/base' - -class EcranDeConnexion < Sinatra::Base - enable :sessions - - get('/connexion') { haml :connexion } - - post('/connexion') do - if params[:nom] = 'admin' && params[:motdepasse] = 'admin' - session['nom_utilisateur'] = params[:nom] - else - redirect '/connexion' - end - end -end - -class MonApp < Sinatra::Base - # le middleware sera appelé avant les filtres - use EcranDeConnexion - - before do - unless session['nom_utilisateur'] - halt "Accès refusé, merci de vous connecter." - end - end - - get('/') { "Bonjour #{session['nom_utilisateur']}." } -end -``` - -### Création dynamique d'applications - -Il se peut que vous ayez besoin de créer une nouvelle application à l'exécution -sans avoir à les assigner à une constante, vous pouvez le faire grâce à -`Sinatra.new` : - -``` ruby -require 'sinatra/base' -mon_app = Sinatra.new { get('/') { "salut" } } -mon_app.run! -``` - -L'application dont elle hérite peut être passé en argument optionnel : - -``` ruby -# config.ru -require 'sinatra/base' - -controleur = Sinatra.new do - enable :logging - helpers MyHelpers -end - -map('/a') do - run Sinatra.new(controleur) { get('/') { 'a' } } -end - -map('/b') do - run Sinatra.new(controleur) { get('/') { 'b' } } -end -``` - -C'est notamment utile pour tester des extensions à Sinatra ou bien pour -utiliser Sinatra dans votre propre bibliothèque. - -Cela permet également d'utiliser très facilement Sinatra comme middleware : - -``` ruby -require 'sinatra/base' - -use Sinatra do - get('/') { ... } -end - -run RailsProject::Application -``` - -## Contextes et Binding - -Le contexte dans lequel vous êtes détermine les méthodes et variables -disponibles. - -### Contexte de l'application/classe - -Une application Sinatra correspond à une sous-classe de `Sinatra::Base`. Il -s'agit de `Sinatra::Application` si vous utilisez le DSL de haut niveau -(`require 'sinatra'`). Sinon c'est la sous-classe que vous avez définie. Dans -le contexte de cette classe, vous avez accès aux méthodes telles que `get` ou -`before`, mais pas aux objets `request` ou `session` étant donné que toutes -les requêtes sont traitées par une seule classe d'application. - -Les options définies au moyen de `set` deviennent des méthodes de classe : - -``` ruby -class MonApp < Sinatra::Base - # Eh, je suis dans le contexte de l'application ! - set :foo, 42 - foo # => 42 - - get '/foo' do - # Eh, je ne suis plus dans le contexte de l'application ! - end -end -``` - -Vous avez le binding du contexte de l'application dans : - -* Le corps de la classe d'application -* Les méthodes définies par les extensions -* Le bloc passé à `helpers` -* Les procs/blocs utilisés comme argument pour `set` -* Le bloc passé à `Sinatra.new` - -Vous pouvez atteindre ce contexte (donc la classe) de la façon suivante : - -* Via l'objet passé dans les blocs `configure` (`configure { |c| ... }`) -* En utilisant `settings` dans le contexte de la requête - -### Contexte de la requête/instance - -Pour chaque requête traitée, une nouvelle instance de votre classe -d'application est créée et tous vos gestionnaires sont exécutés dans ce -contexte. Depuis celui-ci, vous pouvez accéder aux objets `request` et -`session` ou faire appel aux fonctions de rendu telles que `erb` ou `haml`. -Vous pouvez accéder au contexte de l'application depuis le contexte de la -requête au moyen de `settings` : - -``` ruby -class MonApp < Sinatra::Base - # Eh, je suis dans le contexte de l'application ! - get '/ajouter_route/:nom' do - # Contexte de la requête pour '/ajouter_route/:nom' - @value = 42 - - settings.get("/#{params[:nom]}") do - # Contexte de la requête pour "/#{params[:nom]}" - @value # => nil (on est pas au sein de la même requête) - end - - "Route ajoutée !" - end -end -``` - -Vous avez le binding du contexte de la requête dans : - -* les blocs get, head, post, put, delete, options, patch, link et unlink -* les filtres before et after -* les méthodes utilitaires (définies au moyen de `helpers`) -* les vues et templates - -### Le contexte de délégation - -Le contexte de délégation se contente de transmettre les appels de méthodes au -contexte de classe. Toutefois, il ne se comporte pas à 100% comme le contexte -de classe car vous n'avez pas le binding de la classe : seules les méthodes -spécifiquement déclarées pour délégation sont disponibles et il n'est pas -possible de partager des variables/états avec le contexte de classe -(comprenez : `self` n'est pas le même). Vous pouvez ajouter des délégation de -méthodes en appelant `Sinatra::Delegator.delegate :method_name`. - -Vous avez le binding du contexte de délégation dans : - -* Le binding de haut niveau, si vous avez utilisé `require "sinatra"` -* Un objet qui inclut le module `Sinatra::Delegator` - -Pour vous faire une idée, vous pouvez jeter un coup d'oeil au -[mixin Sinatra::Delegator](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633) -qui [étend l'objet principal](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30). - -## Ligne de commande - -Les applications Sinatra peuvent être lancées directement : - -``` shell -ruby mon_application.rb [-h] [-x] [-e ENVIRONNEMENT] [-p PORT] [-o HOTE] [-s SERVEUR] -``` - -Avec les options : - -``` --h # aide --p # déclare le port (4567 par défaut) --o # déclare l'hôte (0.0.0.0 par défaut) --e # déclare l'environnement (development par défaut) --s # déclare le serveur/gestionnaire à utiliser (thin par défaut) --x # active le mutex lock (off par défaut) -``` - -## Configuration nécessaire - -Les versions suivantes de Ruby sont officiellement supportées : - -
-
Ruby 1.8.7
-
- 1.8.7 est complètement supporté, toutefois si rien ne vous en empêche, - nous vous recommandons de faire une mise à jour ou bien de passer à JRuby - ou Rubinius. Le support de Ruby 1.8.7 ne sera pas supprimé avant la sortie - de Sinatra 2.0. Ruby 1.8.6 n’est plus supporté. -
- -
Ruby 1.9.2
-
- 1.9.2 est totalement supporté. N’utilisez pas 1.9.2p0 car il provoque des - erreurs de segmentation à l’exécution de Sinatra. Son support continuera - au minimum jusqu’à la sortie de Sinatra 1.5. -
- -
Ruby 1.9.3
-
- 1.9.3 est totalement supporté et recommandé. Nous vous rappelons que passer - à 1.9.3 depuis une version précédente annulera toutes les sessions. 1.9.3 - sera supporté jusqu'à la sortie de Sinatra 2.0. -
- -
Ruby 2.0.0
-
- 2.0.0 est totalement supporté et recommandé. L'abandon de son support - officiel n'est pas à l'ordre du jour. -
- -
Rubinius
-
- Rubinius est officiellement supporté (Rubinius >= 2.x). Un gem install - puma est recommandé. -
- -
JRuby
-
- La dernière version stable de JRuby est officiellement supportée. Il est - déconseillé d'utiliser des extensions C avec JRuby. Un gem install - trinidad est recommandé. -
-
- -Nous gardons également un oeil sur les versions Ruby à venir. - -Les implémentations Ruby suivantes ne sont pas officiellement supportées mais -sont malgré tout connues pour permettre de faire fonctionner Sinatra : - -* Versions plus anciennes de JRuby et Rubinius -* Ruby Enterprise Edition -* MacRuby, Maglev, IronRuby -* Ruby 1.9.0 et 1.9.1 (mais nous déconseillons leur utilisation) - -Le fait de ne pas être officiellement supporté signifie que si quelque chose -ne fonctionne pas sur cette plateforme uniquement alors c'est un problème de la -plateforme et pas un bug de Sinatra. - -Nous lançons également notre intégration continue (CI) avec ruby-head (la -future 2.1.0), mais nous ne pouvont rien garantir étant donné les évolutions -continuelles. La version 2.1.0 devrait être totalement supportée. - -Sinatra devrait fonctionner sur n'importe quel système d'exploitation -supporté par l'implémentation Ruby choisie. - -Si vous utilisez MacRuby, vous devriez `gem install control_tower`. - -Il n'est pas possible d'utiliser Sinatra sur Cardinal, SmallRuby, BlueRuby ou -toute version de Ruby antérieure à 1.8.7 à l'heure actuelle. - -## Essuyer les plâtres - -Si vous souhaitez tester la toute dernière version de Sinatra, n'hésitez pas -à faire tourner votre application sur la branche master, celle-ci devrait être -stable. - -Pour cela, la méthode la plus simple est d'installer une gem de prerelease que -nous publions de temps en temps : - -``` shell -gem install sinatra --pre -``` -Ce qui permet de bénéficier des toutes dernières fonctionnalités. - -### Installer avec Bundler - -Il est cependant conseillé de passer par [Bundler](http://gembundler.com/) pour -faire tourner votre application avec la dernière version de Sinatra. - -Pour commencer, installez bundler si nécessaire : - -``` shell -gem install bundler -``` - -Ensuite, créez un fichier `Gemfile` dans le dossier de votre projet : - -``` ruby -source 'https://rubygems.org' -gem 'sinatra', :github => "sinatra/sinatra" - -# autres dépendances -gem 'haml' # si par exemple vous utilisez haml -gem 'activerecord', '~> 3.0' # au cas où vous auriez besoin de ActiveRecord 3.x -``` - -Notez que vous devez lister toutes les dépendances de votre application dans -ce fichier `Gemfile`. Les dépendances directes de Sinatra (Rack et Tilt) seront -automatiquement téléchargées et ajoutées par Bundler. - -Vous pouvez alors lancer votre application de la façon suivante : - -``` shell -bundle exec ruby myapp.rb -``` - -### Faire un clone local - -Si vous ne souhaitez pas employer Bundler, vous pouvez cloner Sinatra en local -dans votre projet et démarrez votre application avec le dossier `sinatra/lib` -dans le `$LOAD_PATH` : - -``` shell -cd myapp -git clone git://github.com/sinatra/sinatra.git -ruby -I sinatra/lib myapp.rb -``` - -Et de temps en temps, vous devrez récupérer la dernière version du code source -de Sinatra : - -``` shell -cd myapp/sinatra -git pull -``` - -### Installer globalement - -Une dernière méthode consiste à construire la gem vous-même : - -``` shell -git clone git://github.com/sinatra/sinatra.git -cd sinatra -rake sinatra.gemspec -rake install -``` - -Si vous installez les gems en tant que root, vous devez encore faire un : - -``` shell -sudo rake install -``` - -## Versions - -Sinatra se conforme aux [versions sémantiques](http://semver.org/), aussi bien -SemVer que SemVerTag. - -## Mais encore - -* [Site internet](http://www.sinatrarb.com/) - Plus de documentation, - de news, et des liens vers d'autres ressources. -* [Contribuer](http://www.sinatrarb.com/contributing) - Vous avez trouvé un - bug ? Besoin d'aide ? Vous avez un patch ? -* [Suivi des problèmes](http://github.com/sinatra/sinatra/issues) -* [Twitter](http://twitter.com/sinatra) -* [Mailing List](http://groups.google.com/group/sinatrarb/topics) -* IRC : [#sinatra](irc://chat.freenode.net/#sinatra) sur http://freenode.net -* [Sinatra Book](http://sinatra-book.gittr.com) Tutoriels et recettes -* [Sinatra Recipes](http://recipes.sinatrarb.com/) trucs et astuces rédigés par - la communauté -* Documentation API de la [dernière version](http://rubydoc.info/gems/sinatra) - ou du [HEAD courant](http://rubydoc.info/github/sinatra/sinatra) sur - http://rubydoc.info -* [CI server](http://travis-ci.org/sinatra/sinatra) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.hu.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.hu.md deleted file mode 100644 index 7b08933..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.hu.md +++ /dev/null @@ -1,694 +0,0 @@ -# Sinatra -*Fontos megjegyzés: Ez a dokumentum csak egy fordítása az angol nyelvű -változat, és lehet, hogy nem naprakész.* - -A Sinatra egy [DSL](http://en.wikipedia.org/wiki/Domain-specific_language) -webalkalmazások Ruby nyelven történő fejlesztéséhez, minimális -energiabefektetéssel: - -```ruby - # myapp.rb - require 'sinatra' - get '/' do - 'Helló Világ!' - end -``` - -Telepítsd a gem-et és indítsd el az alkalmazást a következőképpen: - -```ruby - sudo gem install sinatra - ruby myapp.rb -``` - -Az alkalmazás elérhető lesz itt: `http://localhost:4567` - -## Útvonalak (routes) - -A Sinatrában az útvonalat egy HTTP metódus és egy URL-re illeszkedő minta -párosa alkotja. Minden egyes útvonalhoz tartozik egy blokk: - -```ruby - get '/' do - .. megjelenítünk valamit .. - end - - post '/' do - .. létrehozunk valamit .. - end - - put '/' do - .. frissítünk valamit .. - end - - delete '/' do - .. törlünk valamit .. - end -``` - -Az útvonalak illeszkedését a rendszer a definiálásuk sorrendjében -ellenőrzi. Sorrendben mindig az első illeszkedő útvonalhoz tartozó metódus kerül -meghívásra. - -Az útvonalminták tartalmazhatnak paramétereket is, melyeket a `params` -hash-ből érhetünk el: - -```ruby - get '/hello/:name' do - # illeszkedik a "GET /hello/foo" és a "GET /hello/bar" útvonalakra - # ekkor params[:name] értéke 'foo' vagy 'bar' lesz - "Helló #{params[:name]}!" - end -``` - -A kulcsszavas argumentumokat (named parameters) blokk paraméterek útján -is el tudod érni: - -```ruby - get '/hello/:name' do |n| - "Helló #{n}!" - end -``` - -Az útvonalmintákban szerepelhetnek joker paraméterek is, melyeket a -`params[:splat]` tömbön keresztül tudunk elérni. - -```ruby - get '/say/*/to/*' do - # illeszkedik a /say/hello/to/world mintára - params[:splat] # => ["hello", "world"] - end - - get '/download/*.*' do - # illeszkedik a /download/path/to/file.xml mintára - params[:splat] # => ["path/to/file", "xml"] - end -``` - -Reguláris kifejezéseket is felvehetünk az útvonalba: - -```ruby - get %r{/hello/([\w]+)} do - "Helló, #{params[:captures].first}!" - end -``` - -Vagy blokk paramétereket: - -```ruby - get %r{/hello/([\w]+)} do |c| - "Helló, #{c}!" - end -``` - -Az útvonalak azonban számos egyéb illeszkedési feltétel szerint is -tervezhetők, így például az user agent karakterláncot alapul véve: - -```ruby - get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "A Songbird #{params[:agent][0]} verzióját használod" - end - - get '/foo' do - # illeszkedik az egyéb user agentekre - end -``` - -## Statikus állományok - -A statikus fájlok kiszolgálása a `./public` könyvtárból -történik, de természetesen más könyvtárat is megadhatsz erre a célra, -mégpedig a :public_folder kapcsoló beállításával: - - set :public_folder, File.dirname(__FILE__) + '/static' - -Fontos mgejegyezni, hogy a nyilvános könyvtár neve nem szerepel az URL-ben. -A ./public/css/style.css fájl az -`http://example.com/css/style.css` URL-en lesz elérhető. - -## Nézetek és Sablonok - -A sablonfájlokat rendszerint a `./views` könyvtárba helyezzük, de -itt is lehetőség nyílik egyéb könyvtár használatára: - - set :views, File.dirname(__FILE__) + '/templates' - -Nagyon fontos észben tartani, hogy a sablononkra mindig szimbólumokkal -hivatkozunk, még akkor is, ha egyéb (ebben az esetben a -:'subdir/template') könyvtárban tároljuk őket. A renderelő -metódusok minden, nekik közvetlenül átadott karakterláncot megjelenítenek. - -### Haml sablonok - -HAML sablonok rendereléséhez szükségünk lesz a haml gem-re vagy könyvtárra: - -```ruby - # Importáljuk be a haml-t az alkalmazásba - require 'haml' - - get '/' do - haml :index - end -``` - -Ez szépen lerendereli a `./views/index.haml` sablont. - -A [Haml kapcsolói](http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html) -globálisan is beállíthatók a Sinatra konfigurációi között, lásd az -[Options and Configurations](http://www.sinatrarb.com/configuration.html) lapot. -A globális beállításokat lehetőségünk van felülírni metódus szinten is. - -```ruby - set :haml, {:format => :html5 } # az alapértelmezett Haml formátum az :xhtml - - get '/' do - haml :index, :haml_options => {:format => :html4 } # immár felülírva - end -``` - -### Erb sablonok - - # Importáljuk be az erb-t az alkalmazásba - -```ruby - require 'erb' - - get '/' do - erb :index - end -``` - -Ez a `./views/index.erb` sablont fogja lerenderelni. - -### Builder sablonok - -Szükségünk lesz a builder gem-re vagy könyvtárra a builder sablonok -rendereléséhez: - - # Importáljuk be a builder-t az alkalmazásba - -```ruby - require 'builder' - - get '/' do - builder :index - end -``` - -Ez pedig a `./views/index.builder` állományt fogja renderelni. - -### Sass sablonok - -Sass sablonok használatához szükség lesz a haml gem-re vagy könyvtárra: - - # Be kell importálni a haml, vagy a sass könyvtárat - -```ruby - require 'sass' - - get '/stylesheet.css' do - sass :stylesheet - end -``` - -Így a `./views/stylesheet.sass` fájl máris renderelhető. - -A [Sass kapcsolói](http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html) -globálisan is beállíthatók a Sinatra konfigurációi között, lásd az -[Options and Configurations](http://www.sinatrarb.com/configuration.html) lapot. -A globális beállításokat lehetőségünk van felülírni metódus szinten is. - -```ruby - set :sass, {:style => :compact } # az alapértelmezett Sass stílus a :nested - - get '/stylesheet.css' do - sass :stylesheet, :sass_options => {:style => :expanded } # felülírva - end -``` - -### Beágyazott sablonok - -```ruby - get '/' do - haml '%div.title Helló Világ' - end -``` - -Lerendereli a beágyazott sablon karakerláncát. - -### Változók elérése a sablonokban - -A sablonok ugyanabban a kontextusban kerülnek kiértékelésre, mint az -útvonal metódusok (route handlers). Az útvonal metódusokban megadott -változók közvetlenül elérhetőek lesznek a sablonokban: - -```ruby - get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.name' - end -``` - -De megadhatod egy lokális változókat tartalmazó explicit hash-ben is: - -```ruby - get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= foo.name', :locals => { :foo => foo } - end -``` - -Ezt leginkább akkor érdemes megtenni, ha partial-eket akarunk renderelni -valamely más sablonból. - -### Fájlon belüli sablonok - -Sablonokat úgy is megadhatunk, hogy egyszerűen az alkalmazás fájl -végére begépeljük őket: - -```ruby - require 'rubygems' - require 'sinatra' - - get '/' do - haml :index - end - - __END__ - - @@ layout - %html - = yield - - @@ index - %div.title Helló Világ!!!!! -``` - -Megjegyzés: azok a fájlon belüli sablonok, amelyek az alkalmazás fájl végére -kerülnek és függnek a sinatra könyvtártól, automatikusan betöltődnek. -Ha ugyanezt más alkalmazásfájlban is szeretnéd megtenni, hívd meg -a use_in_file_templates! metódust az adott fájlban. - -### Kulcsszavas sablonok - -Sablonokat végül a felsőszintű template metódussal is -definiálhatunk: - -```ruby - template :layout do - "%html\n =yield\n" - end - - template :index do - '%div.title Helló Világ!' - end - - get '/' do - haml :index - end -``` - -Ha létezik "layout" nevű sablon, akkor az minden esetben meghívódik, amikor -csak egy sablon renderelésre kerül. A layoutokat ki lehet kapcsolni a -`:layout => false` meghívásával. - -```ruby - get '/' do - haml :index, :layout => !request.xhr? - end -``` - -## Helperek - -Használd a felső szintű helpers metódust azokhoz a helper -függvényekhez, amiket az útvonal metódusokban és a sablonokban akarsz -használni: - -```ruby - helpers do - def bar(name) - "#{name}bar" - end - end - - get '/:name' do - bar(params[:name]) - end -``` - -## Szűrők (filters) - -Az előszűrők (before filter) az adott hívás kontextusában minden egyes -kérés alkalmával kiértékelődnek, így módosíthatják a kérést és a -választ egyaránt. A szűrőkbe felvett példányváltozók elérhetőek lesznek -az útvonalakban és a sablonokban is: - -```ruby - before do - @note = 'Csá!' - request.path_info = '/foo/bar/baz' - end - - get '/foo/*' do - @note #=> 'Szeva!' - params[:splat] #=> 'bar/baz' - end -``` - -Az utószűrők az egyes kérések után, az adott kérés kontextusában kerülnek -kiértékelésre, így ezek is képesek módosítani a kérést és a választ egyaránt. -Az előszűrőkben és úvonalakban létrehozott példányváltozók elérhetőek lesznek -az utószűrők számára: - -```ruby - after do - puts response.status - end -``` - -## Megállítás - -Egy kérés szűrőben vagy útvonalban történő azonnal blokkolásához -használd a következő parancsot: - - halt - -A megállításkor egy blokktörzset is megadhatsz ... - - halt 'ez fog megjelenni a törzsben' - -Vagy állítsd be a HTTP státuszt és a törzset is egyszerre ... - - halt 401, 'menj innen!' - -## Passzolás - -Az útvonalak továbbadhatják a végrehajtást egy másik útvonalnak -a `pass` függvényhívással: - -```ruby - get '/guess/:who' do - pass unless params[:who] == 'Frici' - "Elkaptál!" - end - - get '/guess/*' do - "Elhibáztál!" - end -``` - -Az útvonal blokkja azonnal kilép és átadja a vezérlést a következő -illeszkedő útvonalnak. Ha nem talál megfelelő útvonalat, a Sinatra -egy 404-es hibával tér vissza. - -## Beállítások - -Csak indításkor, de minden környezetre érvényesen fusson le: - -```ruby - configure do - ... - end -``` - -Csak akkor fusson le, ha a környezet (a RACK_ENV környezeti változóban) -`:production`-ra van állítva: - -```ruby - configure :production do - ... - end -``` - -Csak akkor fusson le, ha a környezet :production vagy :test: - -```ruby - configure :production, :test do - ... - end -``` - -## Hibakezelés - -A hibakezelők ugyanabban a kontextusban futnak le, mint az útvonalak és -előszűrők, ezért számukra is elérhetőek mindazok a könyvtárak, amelyek -az utóbbiak rendelkezésére is állnak; így például a `haml`, -az `erb`, a `halt` stb. - -### Nem található - -Amikor a `Sinatra::NotFound` kivétel fellép, vagy a válasz HTTP -státuszkódja 404-es, mindig a `not_found` metódus hívódik meg. - -```ruby - not_found do - 'Sehol sem találom, amit keresel' - end -``` - -### Hiba - -Az `error` metódus hívódik meg olyankor, amikor egy útvonal, blokk vagy -előszűrő kivételt vált ki. A kivétel objektum lehívható a -`sinatra.error` Rack változótól: - -```ruby - error do - 'Elnézést, de valami szörnyű hiba lépett fel - ' + env['sinatra.error'].name - end -``` - -Egyéni hibakezelés: - -```ruby - error MyCustomError do - 'Szóval az van, hogy...' + env['sinatra.error'].message - end -``` - -És amikor fellép: - -```ruby - get '/' do - raise MyCustomError, 'valami nem stimmel!' - end -``` - -Ez fog megjelenni: - - Szóval az van, hogy... valami nem stimmel! - -A Sinatra speciális `not_found` és `error` hibakezelőket -használ, amikor a futtatási környezet fejlesztői módba van kapcsolva. - -## Mime típusok - -A `send_file` metódus használatakor, vagy statikus fájlok -kiszolgálásakor előfordulhat, hogy a Sinatra nem ismeri fel a fájlok -mime típusát. Ilyenkor használd a +mime_type+ kapcsolót a fájlkiterjesztés -bevezetéséhez: - -```ruby - mime_type :foo, 'text/foo' -``` - -## Rack Middleware - -A Sinatra egy Ruby keretrendszerek számára kifejlesztett egyszerű és szabványos -interfészre, a [Rack](http://rack.rubyforge.org/) -re épül. A Rack fejlesztői -szempontból egyik legérdekesebb jellemzője, hogy támogatja az úgynevezett -"middleware" elnevezésű komponenseket, amelyek beékelődnek a szerver és az -alkalmazás közé, így képesek megfigyelni és/vagy módosítani a HTTP -kéréseket és válaszokat. Segítségükkel különféle, egységesen működő -funkciókat építhetünk be rendszerünkbe. - -A Sinatra keretrendszerben gyerekjáték a Rack middleware-ek behúzása a -`use` metódus segítségével: - -```ruby - require 'sinatra' - require 'my_custom_middleware' - - use Rack::Lint - use MyCustomMiddleware - - get '/hello' do - 'Helló Világ' - end -``` - -A `use` metódus szemantikája megegyezik a -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html) DSL-ben -használt +use+ metóduséval (az említett DSL-t leginkább rackup állományokban -használják). Hogy egy példát említsünk, a `use` metódus elfogad -változókat és blokkokat egyaránt, akár kombinálva is ezeket: - -```ruby - use Rack::Auth::Basic do |username, password| - username == 'admin' && password == 'titkos' - end -``` - -A Rack terjesztéssel egy csomó alap middleware komponens is érkezik, -amelyekkel a naplózás, URL útvonalak megadása, autentikáció és -munkamenet-kezelés könnyen megvalósítható. A Sinatra ezek közül elég -sokat automatikusan felhasznál a beállításoktól függően, így ezek -explicit betöltésével (+use+) nem kell bajlódnod. - -## Tesztelés - -Sinatra teszteket bármely Rack alapú tesztelő könyvtárral vagy -keretrendszerrel készíthetsz. Mi a [Rack::Test](http://gitrdoc.com/brynary/rack-test) -könyvtárat ajánljuk: - -```ruby - require 'my_sinatra_app' - require 'rack/test' - - class MyAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_my_default - get '/' - assert_equal 'Helló Világ!', last_response.body - end - - def test_with_params - get '/meet', :name => 'Frici' - assert_equal 'Helló Frici!', last_response.body - end - - def test_with_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "Songbird-öt használsz!", last_response.body - end - end -``` - -Megjegyzés: A beépített Sinatra::Test és Sinatra::TestHarness osztályok -a 0.9.2-es kiadástól kezdve elavultnak számítanak. - -## Sinatra::Base - Middleware-ek, könyvtárak és moduláris alkalmazások - -Az alkalmazást felső szinten építeni megfelelhet mondjuk egy kisebb -app esetén, ám kifejezetten károsnak bizonyulhat olyan komolyabb, -újra felhasználható komponensek készítésekor, mint például egy Rack -middleware, Rails metal, egyszerűbb kiszolgáló komponenssel bíró -könyvtárak vagy éppen Sinatra kiterjesztések. A felső szintű DSL -bepiszkítja az Objektum névteret, ráadásul kisalkalmazásokra szabott -beállításokat feltételez (így például egyetlen alkalmazásfájl, -`./public` -és `./views` könyvtár meglétét, naplózást, kivételkezelő oldalt stb.). -Itt jön a képbe a Sinatra::Base osztály: - -```ruby - require 'sinatra/base' - - class MyApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Helló Világ!' - end - end -``` - -A MyApp osztály immár önálló Rack komponensként, mondjuk Rack middleware-ként -vagy alkalmazásként, esetleg Rails metal-ként is tud működni. Közvetlenül -használhatod (`use`) vagy futtathatod (`run`) az osztályodat egy rackup -konfigurációs állományban (`config.ru`), vagy egy szerverkomponenst -tartalmazó könyvtár vezérlésekor: - -```ruby - MyApp.run! :host => 'localhost', :port => 9090 -``` - -A Sinatra::Base gyermekosztályaiban elérhető metódusok egyúttal a felső -szintű DSL-en keresztül is hozzáférhetők. A legtöbb felső szintű -alkalmazás átalakítható Sinatra::Base alapú komponensekké két lépésben: - -* A fájlban nem a `sinatra`, hanem a `sinatra/base` osztályt kell - beimportálni, mert egyébként az összes Sinatra DSL metódus a fő - névtérbe kerül. -* Az alkalmazás útvonalait, hibakezelőit, szűrőit és beállításait - a Sinatra::Base osztály gyermekosztályaiban kell megadni. - -A `Sinatra::Base` osztály igazából egy üres lap: a legtöbb funkció -alapból ki van kapcsolva, beleértve a beépített szervert is. A -beállításokkal és az egyes kapcsolók hatásával az -[Options and Configuration](http://sinatra.github.com/configuration.html) lap -foglalkozik. - -Széljegyzet: A Sinatra felső szintű DSL-je egy egyszerű delegációs -rendszerre épül. A Sinatra::Application osztály - a Sinatra::Base egy -speciális osztályaként - fogadja az összes :get, :put, :post, -:delete, :before, :error, :not_found, :configure és :set üzenetet, -ami csak a felső szintre beérkezik. Érdemes utánanézned a kódban, -miképp [kerül be](http://github.com/sinatra/sinatra/blob/master/lib/sinatra/main.rb#L25) -a [Sinatra::Delegator mixin](http://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L1064) -a fő névtérbe. - -## Parancssori lehetőségek - -Sinatra alkalmazásokat közvetlenül futtathatunk: - -``` - ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-s HANDLER] -``` - -Az alábbi kapcsolókat ismeri fel a rendszer: - - -h # segítség - -p # a port beállítása (alapértelmezés szerint ez a 4567-es) - -e # a környezet beállítása (alapértelmezés szerint ez a development) - -s # a rack szerver/handler beállítása (alapértelmezetten ez a thin) - -x # a mutex lock bekapcsolása (alapértelmezetten ki van kapcsolva) - -## Fejlesztői változat - -Ha a Sinatra legfrissebb, fejlesztői változatát szeretnéd használni, -készíts egy helyi másolatot és indítsd az alkalmazásodat úgy, -hogy a `sinatra/lib` könyvtár elérhető legyen a -`LOAD_PATH`-on: - -``` - cd myapp - git clone git://github.com/sinatra/sinatra.git - ruby -Isinatra/lib myapp.rb -``` - -De hozzá is adhatod a sinatra/lib könyvtárat a LOAD_PATH-hoz -az alkalmazásodban: - -```ruby - $LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib' - require 'rubygems' - require 'sinatra' - - get '/about' do - "A következő változatot futtatom " + Sinatra::VERSION - end -``` - -A Sinatra frissítését később így végezheted el: - -``` - cd myproject/sinatra - git pull -``` - -## További információk - -* [A projekt weboldala](http://sinatra.github.com/) - Kiegészítő dokumentáció, - hírek, hasznos linkek -* [Közreműködés](http://sinatra.github.com/contributing.html) - Hibát találtál? - Segítségre van szükséged? Foltot küldenél be? -* [Lighthouse](http://sinatra.lighthouseapp.com) - Hibakövetés és kiadások -* [Twitter](http://twitter.com/sinatra) -* [Levelezőlista](http://groups.google.com/group/sinatrarb) -* [IRC: #sinatra](irc://chat.freenode.net/#sinatra) a http://freenode.net címen diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ja.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ja.md deleted file mode 100644 index e983bc8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ja.md +++ /dev/null @@ -1,2726 +0,0 @@ -# Sinatra - -*注) -本文書は英語から翻訳したものであり、その内容が最新でない場合もあります。最新の情報はオリジナルの英語版を参照して下さい。* - -Sinatraは最小の労力でRubyによるWebアプリケーションを手早く作るための[DSL](http://ja.wikipedia.org/wiki/ドメイン固有言語)です。 - -``` ruby -# myapp.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -gemをインストールし、 - -``` shell -gem install sinatra -``` - -次のように実行します。 - -``` shell -ruby myapp.rb -``` - -[localhost:4567](http://localhost:4567) を開きます。 - -ThinがあればSinatraはこれを利用するので、`gem install thin`することをお薦めします。 - -## 目次 - -* [Sinatra](#sinatra) - * [目次](#目次) - * [ルーティング(Routes)](#ルーティングroutes) - * [条件(Conditions)](#条件conditions) - * [戻り値(Return Values)](#戻り値return-values) - * [カスタムルーティングマッチャー(Custom Route Matchers)](#カスタムルーティングマッチャーcustom-route-matchers) - * [静的ファイル(Static Files)](#静的ファイルstatic-files) - * [ビュー / テンプレート(Views / Templates)](#ビュー--テンプレートviews--templates) - * [リテラルテンプレート(Literal Templates)](#リテラルテンプレートliteral-templates) - * [利用可能なテンプレート言語](#利用可能なテンプレート言語) - * [Haml テンプレート](#haml-テンプレート) - * [Erb テンプレート](#erb-テンプレート) - * [Builder テンプレート](#builder-テンプレート) - * [Nokogiri テンプレート](#nokogiri-テンプレート) - * [Sass テンプレート](#sass-テンプレート) - * [SCSS テンプレート](#scss-テンプレート) - * [Less テンプレート](#less-テンプレート) - * [Liquid テンプレート](#liquid-テンプレート) - * [Markdown テンプレート](#markdown-テンプレート) - * [Textile テンプレート](#textile-テンプレート) - * [RDoc テンプレート](#rdoc-テンプレート) - * [AsciiDoc テンプレート](#asciidoc-テンプレート) - * [Radius テンプレート](#radius-テンプレート) - * [Markaby テンプレート](#markaby-テンプレート) - * [RABL テンプレート](#rabl-テンプレート) - * [Slim テンプレート](#slim-テンプレート) - * [Creole テンプレート](#creole-テンプレート) - * [MediaWiki テンプレート](#mediawiki-テンプレート) - * [CoffeeScript テンプレート](#coffeescript-テンプレート) - * [Stylus テンプレート](#stylus-テンプレート) - * [Yajl テンプレート](#yajl-テンプレート) - * [WLang テンプレート](#wlang-テンプレート) - * [テンプレート内での変数へのアクセス](#テンプレート内での変数へのアクセス) - * [`yield`を伴うテンプレートとネストしたレイアウト](#yieldを伴うテンプレートとネストしたレイアウト) - * [インラインテンプレート(Inline Templates)](#インラインテンプレートinline-templates) - * [名前付きテンプレート(Named Templates)](#名前付きテンプレートnamed-templates) - * [ファイル拡張子の関連付け](#ファイル拡張子の関連付け) - * [オリジナルテンプレートエンジンの追加](#オリジナルテンプレートエンジンの追加) - * [フィルタ(Filters)](#フィルタfilters) - * [ヘルパー(Helpers)](#ヘルパーhelpers) - * [セッションの使用](#セッションの使用) - * [停止(Halting)](#停止halting) - * [パッシング(Passing)](#パッシングpassing) - * [別ルーティングの誘発](#別ルーティングの誘発) - * [ボディ、ステータスコードおよびヘッダの設定](#ボディステータスコードおよびヘッダの設定) - * [ストリーミングレスポンス(Streaming Responses)](#ストリーミングレスポンスstreaming-responses) - * [ロギング(Logging)](#ロギングlogging) - * [MIMEタイプ(Mime Types)](#mimeタイプmime-types) - * [URLの生成](#urlの生成) - * [ブラウザリダイレクト(Browser Redirect)](#ブラウザリダイレクトbrowser-redirect) - * [キャッシュ制御(Cache Control)](#キャッシュ制御cache-control) - * [ファイルの送信](#ファイルの送信) - * [リクエストオブジェクトへのアクセス](#リクエストオブジェクトへのアクセス) - * [アタッチメント(Attachments)](#アタッチメントattachments) - * [日付と時刻の取り扱い](#日付と時刻の取り扱い) - * [テンプレートファイルの探索](#テンプレートファイルの探索) - * [コンフィギュレーション(Configuration)](#コンフィギュレーションconfiguration) - * [攻撃防御に対する設定](#攻撃防御に対する設定) - * [利用可能な設定](#利用可能な設定) - * [環境設定(Environments)](#環境設定environments) - * [エラーハンドリング(Error Handling)](#エラーハンドリングerror-handling) - * [Not Found](#not-found) - * [エラー(Error)](#エラーerror) - * [Rackミドルウェア(Rack Middleware)](#rackミドルウェアrack-middleware) - * [テスト(Testing)](#テストtesting) - * [Sinatra::Base - ミドルウェア、ライブラリおよびモジュラーアプリ](#sinatrabase---ミドルウェアライブラリおよびモジュラーアプリ) - * [モジュラースタイル vs クラッシックスタイル](#モジュラースタイル-vs-クラッシックスタイル) - * [モジュラーアプリケーションの提供](#モジュラーアプリケーションの提供) - * [config.ruを用いたクラッシックスタイルアプリケーションの使用](#configruを用いたクラッシックスタイルアプリケーションの使用) - * [config.ruはいつ使うのか?](#configruはいつ使うのか) - * [Sinatraのミドルウェアとしての利用](#sinatraのミドルウェアとしての利用) - * [動的なアプリケーションの生成](#動的なアプリケーションの生成) - * [スコープとバインディング(Scopes and Binding)](#スコープとバインディングscopes-and-binding) - * [アプリケーション/クラスのスコープ](#アプリケーションクラスのスコープ) - * [リクエスト/インスタンスのスコープ](#リクエストインスタンスのスコープ) - * [デリゲートスコープ](#デリゲートスコープ) - * [コマンドライン](#コマンドライン) - * [必要環境](#必要環境) - * [最新開発版](#最新開発版) - * [Bundlerを使う場合](#bundlerを使う場合) - * [直接組み込む場合](#直接組み込む場合) - * [グローバル環境にインストールする場合](#グローバル環境にインストールする場合) - * [バージョニング(Versioning)](#バージョニングversioning) - * [参考文献](#参考文献) - -## ルーティング(Routes) - -Sinatraでは、ルーティングはHTTPメソッドとURLマッチングパターンがペアになっています。 -ルーティングはブロックに結び付けられています。 - -``` ruby -get '/' do - .. 何か見せる .. -end - -post '/' do - .. 何か生成する .. -end - -put '/' do - .. 何か更新する .. -end - -patch '/' do - .. 何か修正する .. -end - -delete '/' do - .. 何か削除する .. -end - -options '/' do - .. 何か満たす .. -end - -link '/' do - .. 何かリンクを張る .. -end - -unlink '/' do - .. 何かアンリンクする .. -end -``` - -ルーティングは定義された順番にマッチします。 -リクエストに最初にマッチしたルーティングが呼び出されます。 - -ルーティングのパターンは名前付きパラメータを含むことができ、 -`params`ハッシュで取得できます。 - -``` ruby -get '/hello/:name' do - # "GET /hello/foo" と "GET /hello/bar" にマッチ - # params[:name] は 'foo' か 'bar' - "Hello #{params[:name]}!" -end -``` - -また、ブロックパラメータで名前付きパラメータにアクセスすることもできます。 - -``` ruby -get '/hello/:name' do |n| - # "GET /hello/foo" と "GET /hello/bar" にマッチ - # params[:name] は 'foo' か 'bar' - # n が params[:name] を保持 - "Hello #{n}!" -end -``` - -ルーティングパターンはアスタリスク(すなわちワイルドカード)を含むこともでき、 -`params[:splat]` で取得できます。 - -``` ruby -get '/say/*/to/*' do - # /say/hello/to/world にマッチ - params[:splat] # => ["hello", "world"] -end - -get '/download/*.*' do - # /download/path/to/file.xml にマッチ - params[:splat] # => ["path/to/file", "xml"] -end -``` - -ここで、ブロックパラメータを使うこともできます。 - -``` ruby -get '/download/*.*' do |path, ext| - [path, ext] # => ["path/to/file", "xml"] -end -``` - -ルーティングを正規表現にマッチさせることもできます。 - -``` ruby -get %r{/hello/([\w]+)} do - "Hello, #{params[:captures].first}!" -end -``` - -ここでも、ブロックパラメータが使えます。 - -``` ruby -get %r{/hello/([\w]+)} do |c| - "Hello, #{c}!" -end -``` - -ルーティングパターンは、オプショナルパラメータを取ることもできます。 - -``` ruby -get '/posts.?:format?' do - # "GET /posts" と "GET /posts.json", "GET /posts.xml" の拡張子などにマッチ -end -``` - -ところで、ディレクトリトラバーサル攻撃防御設定を無効にしないと(下記参照)、 -ルーティングにマッチする前にリクエストパスが修正される可能性があります。 - -## 条件(Conditions) - -ルーティングにはユーザエージェントのようなさまざまな条件を含めることができます。 - -``` ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "Songbirdのバージョン #{params[:agent][0]}を使ってます。" -end - -get '/foo' do - # Songbird以外のブラウザにマッチ -end -``` - -ほかに`host_name`と`provides`条件が利用可能です。 - -``` ruby -get '/', :host_name => /^admin\./ do - "Adminエリアです。アクセスを拒否します!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -独自の条件を定義することも簡単にできます。 - -``` ruby -set(:probability) { |value| condition { rand <= value } } - -get '/win_a_car', :probability => 0.1 do - "あなたの勝ちです!" -end - -get '/win_a_car' do - "残念、あなたの負けです。" -end -``` - -複数の値を取る条件には、アスタリスクを使います。 - -``` ruby -set(:auth) do |*roles| # <- ここでアスタリスクを使う - condition do - unless logged_in? && roles.any? {|role| current_user.in_role? role } - redirect "/login/", 303 - end - end -end - -get "/my/account/", :auth => [:user, :admin] do - "アカウントの詳細" -end - -get "/only/admin/", :auth => :admin do - "ここは管理者だけ!" -end -``` - -## 戻り値(Return Values) - -ルーティングブロックの戻り値は、HTTPクライアントまたはRackスタックでの次のミドルウェアに渡されるレスポンスボディを決定します。 - -これは大抵の場合、上の例のように文字列ですが、それ以外の値も使用することができます。 - -Rackレスポンス、Rackボディオブジェクト、HTTPステータスコードのいずれかとして妥当なオブジェクトであればどのようなオブジェクトでも返すことができます。 - -* 3つの要素を含む配列: - `[ステータス(Fixnum), ヘッダ(Hash), レスポンスボディ(#eachに応答する)]` -* 2つの要素を含む配列: - `[ステータス(Fixnum), レスポンスボディ(#eachに応答する)]` -* `#each`に応答するオブジェクト。通常はそのまま何も返さないが、 -与えられたブロックに文字列を渡す。 -* ステータスコードを表現する整数(Fixnum) - -これにより、例えばストリーミングを簡単に実装することができます。 - -``` ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -後述する`stream`ヘルパーメソッドを使って、定型パターンを減らしつつストリーミングロジックをルーティングに埋め込むこともできます。 - -## カスタムルーティングマッチャー(Custom Route Matchers) - -先述のようにSinatraはルーティングマッチャーとして、文字列パターンと正規表現を使うことをビルトインでサポートしています。しかしこれに留まらず、独自のマッチャーを簡単に定義することもできるのです。 - -``` ruby -class AllButPattern - Match = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Match.new([]) - end - - def match(str) - @captures unless @except === str - end -end - -def all_but(pattern) - AllButPattern.new(pattern) -end - -get all_but("/index") do - # ... -end -``` - -ノート: この例はオーバースペックであり、以下のようにも書くことができます。 - -``` ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -または、否定先読みを使って: - -``` ruby -get %r{^(?!/index$)} do - # ... -end -``` - - -## 静的ファイル(Static Files) - -静的ファイルは`./public`ディレクトリから配信されます。 -`:public_folder`オプションを指定することで別の場所を指定することができます。 - -``` ruby -set :public_folder, File.dirname(__FILE__) + '/static' -``` - -ノート: この静的ファイル用のディレクトリ名はURL中に含まれません。 -例えば、`./public/css/style.css`は`http://example.com/css/style.css`でアクセスできます。 - -`Cache-Control`の設定をヘッダーへ追加するには`:static_cache_control`の設定(下記参照)を加えてください。 - -## ビュー / テンプレート(Views / Templates) - -各テンプレート言語はそれ自身のレンダリングメソッドを通して展開されます。それらのメソッドは単に文字列を返します。 - -``` ruby -get '/' do - erb :index -end -``` - -これは、`views/index.erb`をレンダリングします。 - -テンプレート名を渡す代わりに、直接そのテンプレートの中身を渡すこともできます。 - -``` ruby -get '/' do - code = "<%= Time.now %>" - erb code -end -``` - -テンプレートのレイアウトは第2引数のハッシュ形式のオプションをもとに表示されます。 - -``` ruby -get '/' do - erb :index, :layout => :post -end -``` - -これは、`views/post.erb`内に埋め込まれた`views/index.erb`をレンダリングします(デフォルトは`views/layout.erb`があればそれになります)。 - -Sinatraが理解できないオプションは、テンプレートエンジンに渡されることになります。 - - -``` ruby -get '/' do - haml :index, :format => :html5 -end -``` - -テンプレート言語ごとにオプションをセットすることもできます。 - -``` ruby -set :haml, :format => :html5 - -get '/' do - haml :index -end -``` - -レンダリングメソッドに渡されたオプションは`set`で設定されたオプションを上書きします。 - -利用可能なオプション: - -
-
locals
-
- ドキュメントに渡されるローカルのリスト。パーシャルに便利。 - 例: erb "<%= foo %>", :locals => {:foo => "bar"} -
- -
default_encoding
-
- 文字エンコーディング(不確かな場合に使用される)。デフォルトは、settings.default_encoding。 -
- -
views
-
- テンプレートを読み出すビューのディレクトリ。デフォルトは、settings.views。 -
- -
layout
-
- レイアウトを使うかの指定(true または false)。値がシンボルの場合は、使用するテンプレートが指定される。例: erb :index, :layout => !request.xhr? -
- -
content_type
-
- テンプレートが生成するContent-Type。デフォルトはテンプレート言語ごとに異なる。 -
- -
scope
-
- テンプレートをレンダリングするときのスコープ。デフォルトは、アプリケーションのインスタンス。これを変更した場合、インスタンス変数およびヘルパーメソッドが利用できなくなる。 -
- -
layout_engine
-
- レイアウトをレンダリングするために使用するテンプレートエンジン。レイアウトをサポートしない言語で有用。デフォルトはテンプレートに使われるエンジン。例: set :rdoc, :layout_engine => :erb -
- -
layout_options
-
- レイアウトをレンダリングするときだけに使う特別なオプション。例: - set :rdoc, :layout_options => { :views => 'views/layouts' } -
-
- -テンプレートは`./views`ディレクトリ下に配置されています。 -他のディレクトリを使用する場合の例: - -``` ruby -set :views, settings.root + '/templates' -``` - -テンプレートはシンボルを使用して参照させることを覚えておいて下さい。 -サブディレクトリでもこの場合は`:'subdir/template'`のようにします。 -レンダリングメソッドは文字列が渡されると、それをそのまま文字列として出力するので、シンボルを使ってください。 - -### リテラルテンプレート(Literal Templates) - -``` ruby -get '/' do - haml '%div.title Hello World' -end -``` - -これはそのテンプレート文字列をレンダリングします。 - -### 利用可能なテンプレート言語 - -いくつかの言語には複数の実装があります。使用する(そしてスレッドセーフにする)実装を指定するには、それを最初にrequireしてください。 - - -``` ruby -require 'rdiscount' # または require 'bluecloth' -get('/') { markdown :index } -``` - -#### Haml テンプレート - - - - - - - - - - - - - - -
依存haml
ファイル拡張子.haml
haml :index, :format => :html5
- - -#### Erb テンプレート - - - - - - - - - - - - - - -
依存 - erubis - または erb (Rubyに同梱) -
ファイル拡張子.erb, .rhtml or .erubis (Erubisだけ)
erb :index
- -#### Builder テンプレート - - - - - - - - - - - - - - -
依存 - builder -
ファイル拡張子.builder
builder { |xml| xml.em "hi" }
- -インラインテンプレート用にブロックを取ることもできます(例を参照)。 - -#### Nokogiri テンプレート - - - - - - - - - - - - - - -
依存nokogiri
ファイル拡張子.nokogiri
nokogiri { |xml| xml.em "hi" }
- -インラインテンプレート用にブロックを取ることもできます(例を参照)。 - - -#### Sass テンプレート - - - - - - - - - - - - - - -
依存sass
ファイル拡張子.sass
sass :stylesheet, :style => :expanded
- - -#### Scss テンプレート - - - - - - - - - - - - - - -
依存sass
ファイル拡張子.scss
scss :stylesheet, :style => :expanded
- -#### Less テンプレート - - - - - - - - - - - - - - -
依存less
ファイル拡張子.less
less :stylesheet
- -#### Liquid テンプレート - - - - - - - - - - - - - - -
依存liquid
ファイル拡張子.liquid
liquid :index, :locals => { :key => 'value' }
- -LiquidテンプレートからRubyのメソッド(`yield`を除く)を呼び出すことができないため、ほぼ全ての場合にlocalsを指定する必要があるでしょう。 - -#### Markdown テンプレート - - - - - - - - - - - - - - -
依存 - 次の何れか: - RDiscount, - RedCarpet, - BlueCloth, - kramdown, - maruku -
ファイル拡張子.markdown, .mkd and .md
markdown :index, :layout_engine => :erb
- -Markdownからメソッドを呼び出すことも、localsに変数を渡すこともできません。 -それゆえ、他のレンダリングエンジンとの組み合わせで使うのが普通です。 - -``` ruby -erb :overview, :locals => { :text => markdown(:introduction) } -``` - -ノート: 他のテンプレート内で`markdown`メソッドを呼び出せます。 - -``` ruby -%h1 Hello From Haml! -%p= markdown(:greetings) -``` - -MarkdownからはRubyを呼ぶことができないので、Markdownで書かれたレイアウトを使うことはできません。しかしながら、`:layout_engine`オプションを渡すことでテンプレートのものとは異なるレンダリングエンジンをレイアウトのために使うことができます。 - - -#### Textile テンプレート - - - - - - - - - - - - - - -
依存RedCloth
ファイル拡張子.textile
textile :index, :layout_engine => :erb
- -Textileからメソッドを呼び出すことも、localsに変数を渡すこともできません。 -それゆえ、他のレンダリングエンジンとの組み合わせで使うのが普通です。 - -``` ruby -erb :overview, :locals => { :text => textile(:introduction) } -``` - -ノート: 他のテンプレート内で`textile`メソッドを呼び出せます。 - -``` ruby -%h1 Hello From Haml! -%p= textile(:greetings) -``` - -TexttileからはRubyを呼ぶことができないので、Textileで書かれたレイアウトを使うことはできません。しかしながら、`:layout_engine`オプションを渡すことでテンプレートのものとは異なるレンダリングエンジンをレイアウトのために使うことができます。 - -#### RDoc テンプレート - - - - - - - - - - - - - - -
依存RDoc
ファイル拡張子.rdoc
rdoc :README, :layout_engine => :erb
- -RDocからメソッドを呼び出すことも、localsに変数を渡すこともできません。 -それゆえ、他のレンダリングエンジンとの組み合わせで使うのが普通です。 - -``` ruby -erb :overview, :locals => { :text => rdoc(:introduction) } -``` - -ノート: 他のテンプレート内で`rdoc`メソッドを呼び出せます。 - - -``` ruby -%h1 Hello From Haml! -%p= rdoc(:greetings) -``` - -RDocからはRubyを呼ぶことができないので、RDocで書かれたレイアウトを使うことはできません。しかしながら、`:layout_engine`オプションを渡すことでテンプレートのものとは異なるレンダリングエンジンをレイアウトのために使うことができます。 - -#### AsciiDoc テンプレート - - - - - - - - - - - - - - -
依存Asciidoctor
ファイル拡張子.asciidoc, .adoc and .ad
asciidoc :README, :layout_engine => :erb
- -AsciiDocテンプレートからRubyのメソッドを直接呼び出すことができないため、ほぼ全ての場合にlocalsを指定する必要があるでしょう。 - -#### Radius テンプレート - - - - - - - - - - - - - - -
依存Radius
ファイル拡張子.radius
radius :index, :locals => { :key => 'value' }
- -RadiusテンプレートからRubyのメソッドを直接呼び出すことができないため、ほぼ全ての場合にlocalsを指定する必要があるでしょう。 - - -#### Markaby テンプレート - - - - - - - - - - - - - - -
依存Markaby
ファイル拡張子.mab
markaby { h1 "Welcome!" }
- -インラインテンプレート用にブロックを取ることもできます(例を参照)。 - -#### RABL テンプレート - - - - - - - - - - - - - - -
依存Rabl
ファイル拡張子.rabl
rabl :index
- -#### Slim テンプレート - - - - - - - - - - - - - - -
依存Slim Lang
ファイル拡張子.slim
slim :index
- -#### Creole テンプレート - - - - - - - - - - - - - - -
依存Creole
ファイル拡張子.creole
creole :wiki, :layout_engine => :erb
- -Creoleからメソッドを呼び出すことも、localsに変数を渡すこともできません。 -それゆえ、他のレンダリングエンジンとの組み合わせで使うのが普通です。 - -``` ruby -erb :overview, :locals => { :text => creole(:introduction) } -``` - -ノート: 他のテンプレート内で`creole`メソッドを呼び出せます。 - -``` ruby -%h1 Hello From Haml! -%p= creole(:greetings) -``` - -CreoleからはRubyを呼ぶことができないので、Creoleで書かれたレイアウトを使うことはできません。しかしながら、`:layout_engine`オプションを渡すことでテンプレートのものとは異なるレンダリングエンジンをレイアウトのために使うことができます。 - -#### MediaWiki テンプレート - - - - - - - - - - - - - - -
依存WikiCloth
ファイル拡張子.mediawiki および .mw
mediawiki :wiki, :layout_engine => :erb
- -MediaWikiのテンプレートは直接メソッドから呼び出したり、ローカル変数を通すことはできません。それゆえに、通常は別のレンダリングエンジンと組み合わせて利用します。 - -```ruby -erb :overview, :locals => { :text => mediawiki(:introduction) } -``` - -ノート: 他のテンプレートから部分的に`mediawiki`メソッドを呼び出すことも可能です。 - -#### CoffeeScript テンプレート - - - - - - - - - - - - - - -
依存 - - CoffeeScript - および - - JavaScriptの起動方法 - -
ファイル拡張子.coffee
coffee :index
- -#### Stylus テンプレート - - - - - - - - - - - - - - -
依存 - - Stylus - および - - JavaScriptの起動方法 - -
ファイル拡張子.styl
stylus :index
- -Stylusテンプレートを使えるようにする前に、まず`stylus`と`stylus/tilt`を読み込む必要があります。 - -``` ruby -require 'sinatra' -require 'stylus' -require 'stylus/tilt' - -get '/' do - stylus :example -end -``` - -#### Yajl テンプレート - - - - - - - - - - - - - - -
依存yajl-ruby
ファイル拡張子.yajl
- - yajl :index, - :locals => { :key => 'qux' }, - :callback => 'present', - :variable => 'resource' - -
- - -テンプレートのソースはRubyの文字列として評価され、その結果のJSON変数は`#to_json`を使って変換されます。 - -``` ruby -json = { :foo => 'bar' } -json[:baz] = key -``` - -`:callback`および`:variable`オプションは、レンダリングされたオブジェクトを装飾するために使うことができます。 - -``` ruby -var resource = {"foo":"bar","baz":"qux"}; present(resource); -``` - -#### WLang テンプレート - - - - - - - - - - - - - - -
依存wlang
ファイル拡張子.wlang
wlang :index, :locals => { :key => 'value' }
- -WLang内でのRubyメソッドの呼び出しは一般的ではないので、ほとんどの場合にlocalsを指定する必要があるでしょう。しかしながら、WLangで書かれたレイアウトは`yield`をサポートしています。 - -### テンプレート内での変数へのアクセス - -テンプレートはルーティングハンドラと同じコンテキストの中で評価されます。ルーティングハンドラでセットされたインスタンス変数はテンプレート内で直接使うことができます。 - -``` ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.name' -end -``` - -また、ローカル変数のハッシュで明示的に指定することもできます。 - -``` ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= bar.name', :locals => { :bar => foo } -end -``` - -このやり方は他のテンプレート内で部分テンプレートとして表示する時に典型的に使用されます。 - -### `yield`を伴うテンプレートとネストしたレイアウト - -レイアウトは通常、`yield`を呼ぶ単なるテンプレートに過ぎません。 -そのようなテンプレートは、既に説明した`:template`オプションを通して使われるか、または次のようなブロックを伴ってレンダリングされます。 - -``` ruby -erb :post, :layout => false do - erb :index -end -``` - -このコードは、`erb :index, :layout => :post`とほぼ等価です。 - -レンダリングメソッドにブロックを渡すスタイルは、ネストしたレイアウトを作るために最も役立ちます。 - -``` ruby -erb :main_layout, :layout => false do - erb :admin_layout do - erb :user - end -end -``` - -これはまた次のより短いコードでも達成できます。 - -``` ruby -erb :admin_layout, :layout => :main_layout do - erb :user -end -``` - -現在、次のレンダリングメソッドがブロックを取れます: `erb`, `haml`, -`liquid`, `slim `, `wlang`。 -また汎用の`render`メソッドもブロックを取れます。 - - -### インラインテンプレート(Inline Templates) - -テンプレートはソースファイルの最後で定義することもできます。 - -``` ruby -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Hello world!!!!! -``` - -ノート: Sinatraをrequireするソースファイル内で定義されたインラインテンプレートは自動的に読み込まれます。他のソースファイル内にインラインテンプレートがある場合には`enable :inline_templates`を明示的に呼んでください。 - -### 名前付きテンプレート(Named Templates) - -テンプレートはトップレベルの`template`メソッドで定義することもできます。 - -``` ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Hello World!' -end - -get '/' do - haml :index -end -``` - -「layout」というテンプレートが存在する場合、そのテンプレートファイルは他のテンプレートがレンダリングされる度に使用されます。`:layout => false`で個別に、または`set :haml, :layout => false`でデフォルトとして、レイアウトを無効にすることができます。 - -``` ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -### ファイル拡張子の関連付け - -任意のテンプレートエンジンにファイル拡張子を関連付ける場合は、`Tilt.register`を使います。例えば、Textileテンプレートに`tt`というファイル拡張子を使いたい場合は、以下のようにします。 - -``` ruby -Tilt.register :tt, Tilt[:textile] -``` - -### オリジナルテンプレートエンジンの追加 - -まず、Tiltでそのエンジンを登録し、次にレンダリングメソッドを作ります。 - -``` ruby -Tilt.register :myat, MyAwesomeTemplateEngine - -helpers do - def myat(*args) render(:myat, *args) end -end - -get '/' do - myat :index -end -``` - -これは、`./views/index.myat`をレンダリングします。Tiltについての詳細は、https://github.com/rtomayko/tilt を参照してください。 - -## フィルタ(Filters) - -beforeフィルタは、リクエストのルーティングと同じコンテキストで各リクエストの前に評価され、それによってリクエストとレスポンスを変更可能にします。フィルタ内でセットされたインスタンス変数はルーティングとテンプレートからアクセスすることができます。 - -``` ruby -before do - @note = 'Hi!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @note #=> 'Hi!' - params[:splat] #=> 'bar/baz' -end -``` - -afterフィルタは、リクエストのルーティングと同じコンテキストで各リクエストの後に評価され、それによってこれもリクエストとレスポンスを変更可能にします。beforeフィルタとルーティング内でセットされたインスタンス変数はafterフィルタからアクセスすることができます。 - -``` ruby -after do - puts response.status -end -``` - -ノート: `body`メソッドを使わずにルーティングから文字列を返すだけの場合、その内容はafterフィルタでまだ利用できず、その後に生成されることになります。 - -フィルタにはオプションとしてパターンを渡すことができ、この場合はリクエストのパスがパターンにマッチした場合にのみフィルタが評価されるようになります。 - -``` ruby -before '/protected/*' do - authenticate! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -``` - -ルーティング同様、フィルタもまた条件を取ることができます。 - -``` ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'example.com' do - # ... -end -``` - -## ヘルパー(Helpers) - -トップレベルの`helpers`メソッドを使用してルーティングハンドラやテンプレートで使うヘルパーメソッドを定義できます。 - -``` ruby -helpers do - def bar(name) - "#{name}bar" - end -end - -get '/:name' do - bar(params[:name]) -end -``` - -あるいは、ヘルパーメソッドをモジュール内で個別に定義することもできます。 - -``` ruby -module FooUtils - def foo(name) "#{name}foo" end -end - -module BarUtils - def bar(name) "#{name}bar" end -end - -helpers FooUtils, BarUtils -``` - -その効果は、アプリケーションクラスにモジュールをインクルードするのと同じです。 - - -### セッションの使用 - -セッションはリクエスト間での状態維持のために使用されます。その起動により、ユーザセッションごとに一つのセッションハッシュが与えられます。 - -``` ruby -enable :sessions - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -ノート: `enable :sessions`は実際にはすべてのデータをクッキーに保持します。これは必ずしも期待通りのものにならないかもしれません(例えば、大量のデータを保持することでトラフィックが増大するなど)。Rackセッションミドルウェアの利用が可能であり、その場合は`enable :sessions`を呼ばずに、選択したミドルウェアを他のミドルウェアのときと同じようにして取り込んでください。 - -``` ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -セキュリティ向上のため、クッキー内のセッションデータはセッション秘密鍵(session secret)で署名されます。Sinatraによりランダムな秘密鍵が個別に生成されます。しかし、この秘密鍵はアプリケーションの立ち上げごとに変わってしまうので、すべてのアプリケーションのインスタンスで共有できる秘密鍵をセットしたくなるかもしれません。 - -``` ruby -set :session_secret, 'super secret' -``` - -更に、設定変更をしたい場合は、`sessions`の設定においてオプションハッシュを保持することもできます。 - -``` ruby -set :sessions, :domain => 'foo.com' -``` - -foo.comのサブドメイン上のアプリ間でセッションを共有化したいときは、代わりにドメインの前に *.* を付けます。 - -``` ruby -set :sessions, :domain => '.foo.com' -``` - -### 停止(Halting) - -フィルタまたはルーティング内で直ちにリクエストを止める場合 - -``` ruby -halt -``` - -この際、ステータスを指定することもできます。 - -``` ruby -halt 410 -``` - -body部を指定することも、 - -``` ruby -halt 'ここにbodyを書く' -``` - -ステータスとbody部を指定することも、 - -``` ruby -halt 401, '立ち去れ!' -``` - -ヘッダを付けることもできます。 - -``` ruby -halt 402, {'Content-Type' => 'text/plain'}, 'リベンジ' -``` - -もちろん、テンプレートを`halt`に結びつけることも可能です。 - -``` ruby -halt erb(:error) -``` - -### パッシング(Passing) - -ルーティングは`pass`を使って次のルーティングに飛ばすことができます。 - -``` ruby -get '/guess/:who' do - pass unless params[:who] == 'Frank' - "見つかっちゃった!" -end - -get '/guess/*' do - "はずれです!" -end -``` - -ルーティングブロックからすぐに抜け出し、次にマッチするルーティングを実行します。マッチするルーティングが見当たらない場合は404が返されます。 - -### 別ルーティングの誘発 - -`pass`を使ってルーティングを飛ばすのではなく、他のルーティングを呼んだ結果を得たいというときがあります。これを実現するには`call`を使えばいいです。 - -``` ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do - "bar" -end -``` - -ノート: 先の例において、テストを楽にしパフォーマンスを改善するには、`"bar"`を単にヘルパーに移し、`/foo`および`/bar`から使えるようにするのがいいです。 - -リクエストが、その複製物でない同じアプリケーションのインスタンスに送られるようにしたいときは、`call`に代えて`call!`を使ってください。 - -`call`についての詳細はRackの仕様書を参照してください。 - - -### ボディ、ステータスコードおよびヘッダの設定 - -ステータスコードおよびレスポンスボディを、ルーティングブロックの戻り値にセットすることが可能であり、これは推奨されています。しかし、あるケースでは実行フローの任意のタイミングでボディをセットしたくなるかもしれません。`body`ヘルパーメソッドを使えばそれができます。そうすると、それ以降、ボディにアクセスするためにそのメソッドを使うことができるようになります。 - -``` ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -``` - -また、`body`にはブロックを渡すことができ、これはRackハンドラにより実行されることになります(これはストリーミングを実装するのに使われます。"戻り値"の項を参照してください。) - -ボディと同様に、ステータスコードおよびヘッダもセットできます。 - -``` ruby -get '/foo' do - status 418 - headers \ - "Allow" => "BREW, POST, GET, PROPFIND, WHEN", - "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - body "I'm a tea pot!" -end -``` - -引数を伴わない`body`、`headers`、`status`などは、それらの現在の値にアクセスするために使えます。 - -### ストリーミングレスポンス(Streaming Responses) - -レスポンスボディの部分を未だ生成している段階で、データを送り出したいということがあります。極端な例では、クライアントがコネクションを閉じるまでデータを送り続けたいことがあります。`stream`ヘルパーを使えば、独自ラッパーを作る必要はありません。 - -``` ruby -get '/' do - stream do |out| - out << "それは伝 -\n" - sleep 0.5 - out << " (少し待つ) \n" - sleep 1 - out << "- 説になる!\n" - end -end -``` - -これはストリーミングAPI、[Server Sent Events](http://dev.w3.org/html5/eventsource/)の実装を可能にし、[WebSockets](http://en.wikipedia.org/wiki/WebSocket)の土台に使うことができます。また、一部のコンテンツが遅いリソースに依存しているときに、スループットを上げるために使うこともできます。 - -ノート: ストリーミングの挙動、特に並行リクエスト(cuncurrent requests)の数は、アプリケーションを提供するのに使われるWebサーバに強く依存します。WEBRickを含むいくつかのサーバは、ストリーミングを全くサポートしません。サーバがストリーミングをサポートしない場合、ボディは`stream`に渡されたブロックの実行が終了した後、一度に全部送られることになります。ストリーミングは、Shotgunを使った場合は全く動作しません。 - -オプション引数が`keep_open`にセットされている場合、ストリームオブジェクト上で`close`は呼ばれず、実行フローの任意の遅れたタイミングでユーザがこれを閉じることを可能にします。これはThinやRainbowsのようなイベント型サーバ上でしか機能しません。他のサーバでは依然ストリームは閉じられます。 - -``` ruby -# ロングポーリング - -set :server, :thin -connections = [] - -get '/subscribe' do - # サーバイベントにおけるクライアントの関心を登録 - stream(:keep_open) { |out| connections << out } - - # 死んでいるコネクションを排除 - connections.reject!(&:closed?) - - # 肯定応答 - "subscribed" -end - -post '/message' do - connections.each do |out| - # クライアントへ新規メッセージ到着の通知 - out << params[:message] << "\n" - - # クライアントへの再接続の指示 - out.close - end - - # 肯定応答 - "message received" -end -``` - -### ロギング(Logging) - -リクエストスコープにおいて、`logger`ヘルパーは`Logger`インスタンスを作り出します。 - - -``` ruby -get '/' do - logger.info "loading data" - # ... -end -``` - -このロガーは、自動でRackハンドラのロギング設定を参照します。ロギングが無効(disabled)にされている場合、このメソッドはダミーオブジェクトを返すので、ルーティングやフィルタにおいて特に心配することはありません。 - -ノート: ロギングは、`Sinatra::Application`に対してのみデフォルトで有効にされているので、`Sinatra::Base`を継承している場合は、ユーザがこれを有効化する必要があります。 - -``` ruby -class MyApp < Sinatra::Base - configure :production, :development do - enable :logging - end -end -``` - -ロギングミドルウェアが設定されてしまうのを避けるには、`logging`設定を`nil`にセットします。しかしこの場合、`logger`が`nil`を返すことを忘れないように。よくあるユースケースは、オリジナルのロガーをセットしたいときです。Sinatraは、とにかく`env['rack.logger']`で見つかるものを使います。 - -### MIMEタイプ(Mime Types) - -`send_file`か静的ファイルを使う時、SinatraがMIMEタイプを理解できない場合があります。その時は `mime_type` を使ってファイル拡張子毎に登録して下さい。 - -``` ruby -configure do - mime_type :foo, 'text/foo' -end -``` - -これは`content_type`ヘルパーで利用することができます: - -``` ruby -get '/' do - content_type :foo - "foo foo foo" -end -``` - -### URLの生成 - -URLを生成するためには`url`ヘルパーメソッドが使えます。Hamlではこのようにします。 - -``` ruby -%a{:href => url('/foo')} foo -``` - -これはリバースプロキシおよびRackルーティングを、それらがあれば考慮に入れます。 - -このメソッドには`to`というエイリアスがあります(以下の例を参照)。 - -### ブラウザリダイレクト(Browser Redirect) - -`redirect` ヘルパーメソッドを使うことで、ブラウザをリダイレクトさせることができます。 - -``` ruby -get '/foo' do - redirect to('/bar') -end -``` - -他に追加されるパラメータは、`halt`に渡される引数と同様に取り扱われます。 - -``` ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'wrong place, buddy' -``` - -また、`redirect back`を使えば、簡単にユーザが来たページへ戻るリダイレクトを作れます。 - -``` ruby -get '/foo' do - "do something" -end - -get '/bar' do - do_something - redirect back -end -``` - -redirectに引数を渡すには、それをクエリーに追加するか、 - - -``` ruby -redirect to('/bar?sum=42') -``` - -または、セッションを使います。 - -``` ruby -enable :sessions - -get '/foo' do - session[:secret] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secret] -end -``` - -### キャッシュ制御(Cache Control) - -ヘッダを正しく設定することが、適切なHTTPキャッシングのための基礎となります。 - -キャッシュ制御ヘッダ(Cache-Control header)は、次のように簡単に設定できます。 - -``` ruby -get '/' do - cache_control :public - "キャッシュしました!" -end -``` - -ヒント: キャッシングをbeforeフィルタ内で設定します。 - -``` ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -``` - -`expires`ヘルパーを対応するヘッダに使っている場合は、キャッシュ制御は自動で設定されます。 - -``` ruby -before do - expires 500, :public, :must_revalidate -end -``` - -キャッシュを適切に使うために、`etag`または`last_modified`を使うことを検討してください。これらのヘルパーを、重い仕事をさせる *前* に呼ぶことを推奨します。そうすれば、クライアントが既にキャッシュに最新版を持っている場合はレスポンスを直ちに破棄するようになります。 - -``` ruby -get '/article/:id' do - @article = Article.find params[:id] - last_modified @article.updated_at - etag @article.sha1 - erb :article -end -``` - -また、[weak ETag](http://ja.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation)を使うこともできます。 - -``` ruby -etag @article.sha1, :weak -``` - -これらのヘルパーは、キャッシングをしてくれませんが、必要な情報をキャッシュに与えてくれます。もし手早いリバースプロキシキャッシングの解決策をお探しなら、 [rack-cache](https://github.com/rtomayko/rack-cache)を試してください。 - - -``` ruby -require "rack/cache" -require "sinatra" - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hello" -end -``` - -`:static_cache_control`設定(以下を参照)を、キャッシュ制御ヘッダ情報を静的ファイルに追加するために使ってください。 - -RFC 2616によれば、アプリケーションは、If-MatchまたはIf-None-Matchヘッダが`*`に設定されている場合には、要求されたリソースが既に存在するか否かに応じて、異なる振る舞いをすべきとなっています。Sinatraは、getのような安全なリクエストおよびputのような冪等なリクエストは既に存在しているものとして仮定し、一方で、他のリソース(例えば、postリクエスト)は新たなリソースとして取り扱われるよう仮定します。この振る舞いは、`:new_resource`オプションを渡すことで変更できます。 - -``` ruby -get '/create' do - etag '', :new_resource => true - Article.create - erb :new_article -end -``` - -ここでもWeak ETagを使いたい場合は、`:kind`オプションを渡してください。 - -``` ruby -etag '', :new_resource => true, :kind => :weak -``` - -### ファイルの送信 - -ファイルを送信するには、`send_file`ヘルパーメソッドを使います。 - -``` ruby -get '/' do - send_file 'foo.png' -end -``` - -これはオプションを取ることもできます。 - -``` ruby -send_file 'foo.png', :type => :jpg -``` - -オプション一覧 - -
-
filename
-
ファイル名。デフォルトは実際のファイル名。
- -
last_modified
-
Last-Modifiedヘッダの値。デフォルトはファイルのmtime。
- -
type
-
コンテンツの種類。設定がない場合、ファイル拡張子から類推される。
- - disposition -
- Content-Dispositionに使われる。許容値: nil (デフォルト)、 - :attachment および :inline -
- -
length
-
Content-Lengthヘッダ。デフォルトはファイルサイズ。
- -
status
-
- 送られるステータスコード。静的ファイルをエラーページとして送るときに便利。 - - Rackハンドラでサポートされている場合は、Rubyプロセスからのストリーミング以外の手段が使われる。このヘルパーメソッドを使うと、Sinatraは自動で範囲リクエスト(range requests)を扱う。 -
-
- - -## リクエストオブジェクトへのアクセス - -受信するリクエストオブジェクトは、`request`メソッドを通じてリクエストレベル(フィルタ、ルーティング、エラーハンドラ)からアクセスすることができます。 - -``` ruby -# アプリケーションが http://example.com/example で動作している場合 -get '/foo' do - t = %w[text/css text/html application/javascript] - request.accept # ['text/html', '*/*'] - request.accept? 'text/xml' # true - request.preferred_type(t) # 'text/html' - request.body # クライアントによって送信されたリクエストボディ(下記参照) - request.scheme # "http" - request.script_name # "/example" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # request.bodyの長さ - request.media_type # request.bodyのメディアタイプ - request.host # "example.com" - request.get? # true (他の動詞にも同種メソッドあり) - request.form_data? # false - request["some_param"] # some_param変数の値。[]はパラメータハッシュのショートカット - request.referrer # クライアントのリファラまたは'/' - request.user_agent # ユーザエージェント (:agent 条件によって使用される) - request.cookies # ブラウザクッキーのハッシュ - request.xhr? # Ajaxリクエストかどうか - request.url # "http://example.com/example/foo" - request.path # "/example/foo" - request.ip # クライアントのIPアドレス - request.secure? # false (sslではtrueになる) - request.forwarded? # true (リバースプロキシの裏で動いている場合) - request.env # Rackによって渡された生のenvハッシュ -end -``` - -`script_name`や`path_info`などのオプションは次のように利用することもできます。 - -``` ruby -before { request.path_info = "/" } - -get "/" do - "全てのリクエストはここに来る" -end -``` - -`request.body`はIOまたはStringIOのオブジェクトです。 - -``` ruby -post "/api" do - request.body.rewind # 既に読まれているときのため - data = JSON.parse request.body.read - "Hello #{data['name']}!" -end -``` - -### アタッチメント(Attachments) - -`attachment`ヘルパーを使って、レスポンスがブラウザに表示されるのではなく、ディスクに保存されることをブラウザに対し通知することができます。 - -``` ruby -get '/' do - attachment - "保存しました!" -end -``` - -ファイル名を渡すこともできます。 - -``` ruby -get '/' do - attachment "info.txt" - "保存しました!" -end -``` - -### 日付と時刻の取り扱い - -Sinatraは`time_for`ヘルパーメソッドを提供しており、それは与えられた値からTimeオブジェクトを生成します。これはまた`DateTime`、`Date`および類似のクラスを変換できます。 - -``` ruby -get '/' do - pass if Time.now > time_for('Dec 23, 2012') - "まだ時間がある" -end -``` - -このメソッドは、`expires`、`last_modified`といった種類のものの内部で使われています。そのため、アプリケーションにおいて、`time_for`をオーバーライドすることでそれらのメソッドの挙動を簡単に拡張できます。 - -``` ruby -helpers do - def time_for(value) - case value - when :yesterday then Time.now - 24*60*60 - when :tomorrow then Time.now + 24*60*60 - else super - end - end -end - -get '/' do - last_modified :yesterday - expires :tomorrow - "hello" -end -``` - -### テンプレートファイルの探索 - -`find_template`ヘルパーは、レンダリングのためのテンプレートファイルを見つけるために使われます。 - -``` ruby -find_template settings.views, 'foo', Tilt[:haml] do |file| - puts "could be #{file}" -end -``` - -この例はあまり有益ではありません。しかし、このメソッドを、独自の探索機構で働くようオーバーライドするなら有益になります。例えば、複数のビューディレクトリを使えるようにしたいときがあります。 - - -``` ruby -set :views, ['views', 'templates'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -``` - -他の例としては、異なるエンジン用の異なるディレクトリを使う場合です。 - -``` ruby -set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:default] - super(folder, name, engine, &block) - end -end -``` - -これをエクステンションとして書いて、他の人と簡単に共有することもできます! - -ノート: `find_template`はファイルが実際に存在するかのチェックをしませんが、与えられたブロックをすべての可能なパスに対し呼び出します。これがパフォーマンス上の問題にはならないのは、`render`はファイルを見つけると直ちに`break`を使うからです。また、テンプレートの場所(および内容)は、developmentモードでの起動でない限りはキャッシュされます。このことは、複雑なメソッド(a really crazy method)を書いた場合は記憶しておく必要があります。 - -## コンフィギュレーション(Configuration) - -どの環境でも起動時に1回だけ実行されます。 - -``` ruby -configure do - # 1つのオプションをセット - set :option, 'value' - - # 複数のオプションをセット - set :a => 1, :b => 2 - - # `set :option, true`と同じ - enable :option - - # `set :option, false`と同じ - disable :option - - # ブロックを使って動的な設定をすることもできます。 - set(:css_dir) { File.join(views, 'css') } -end -``` - -環境設定(`RACK_ENV`環境変数)が`:production`に設定されている時だけ実行する方法: - -``` ruby -configure :production do - ... -end -``` - -環境設定が`:production`か`:test`に設定されている時だけ実行する方法: - -``` ruby -configure :production, :test do - ... -end -``` - -設定したオプションには`settings`からアクセスできます: - -``` ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -``` - -### 攻撃防御に対する設定 - -Sinatraは、[Rack::Protection](https://github.com/rkh/rack-protection#readme)を使って、アプリケーションを多発する日和見的攻撃から守っています。この挙動は簡単に無効化できます(これはアプリケーションを大量の脆弱性攻撃に晒すことになります)。 - -``` ruby -disable :protection -``` - -単一の防御層を外すためには、`protection`をオプションハッシュにセットします。 - -``` ruby -set :protection, :except => :path_traversal -``` -また配列を渡して、複数の防御を無効にすることもできます。 - -``` ruby -set :protection, :except => [:path_traversal, :session_hijacking] -``` - -デフォルトでSinatraは、`:sessions`が有効になっている場合、セッションベースの防御だけを設定します。しかし、自身でセッションを設定したい場合があります。その場合は、`:session`オプションを渡すことにより、セッションベースの防御を設定することができます。 - -``` ruby -use Rack::Session::Pool -set :protection, :session => true -``` - -### 利用可能な設定 - -
-
absolute_redirects
-
- 無効のとき、Sinatraは相対リダイレクトを許容するが、RFC 2616 (HTTP 1.1)は絶対リダイレクトのみを許容するので、これには準拠しなくなる。 -
-
- アプリケーションが、適切に設定されていないリバースプロキシの裏で走っている場合は有効。ノート: urlヘルパーは、第2引数にfalseを渡さない限り、依然として絶対URLを生成する。 -
-
デフォルトは無効。
- -
add_charsets
-
- Mimeタイプ content_typeヘルパーが自動的にキャラクタセット情報をここに追加する。このオプションは書き換えるのではなく、値を追加するようにすること。 - settings.add_charsets << "application/foobar" -
- -
app_file
-
- メインのアプリケーションファイルのパスであり、プロジェクトのルート、viewsおよびpublicフォルダを見つけるために使われる。 -
- -
bind
-
バインドするIPアドレス(デフォルト: `environment`がdevelopmentにセットされているときは、0.0.0.0 または localhost)。ビルトインサーバでのみ使われる。 - -
default_encoding
-
不明なときに仮定されるエンコーディング(デフォルトは"utf-8")。
- -
dump_errors
-
ログにおけるエラーの表示。
- -
environment
-
- 現在の環境。デフォルトはENV['RACK_ENV']、それが無い場合は"development"。 -
- -
logging
-
ロガーの使用。
- -
lock
-
- 各リクエスト周りのロックの配置で、Rubyプロセスごとにリクエスト処理を並行して走らせるようにする。 -
-
アプリケーションがスレッドセーフでなければ有効。デフォルトは無効。
- -
method_override
-
- put/deleteフォームを、それらをサポートしないブラウザで使えるように_methodのおまじないを使えるようにする。 -
- -
port
-
待ち受けポート。ビルトインサーバのみで有効。
- -
prefixed_redirects
-
- 絶対パスが与えられていないときに、リダイレクトにrequest.script_nameを挿入するか否かの設定。これによりredirect '/foo'は、redirect to('/foo')のように振る舞う。デフォルトは無効。 -
- -
protection
-
Web攻撃防御を有効にするか否かの設定。上述の攻撃防御の項を参照。
- -
public_dir
-
public_folderのエイリアス。以下を参照。
- -
public_folder
-
- publicファイルが提供されるディレクトリのパス。静的ファイルの提供が有効になっている場合にのみ使われる (以下のstatic設定を参照)。設定されていない場合、app_file設定から推定。 -
- -
reload_templates
-
- リクエスト間でテンプレートを再ロードするか否かの設定。developmentモードでは有効。 -
- -
root
-
- プロジェクトのルートディレクトリのパス。設定されていない場合、app_file設定から推定。 -
- -
raise_errors
-
- 例外発生の設定(アプリケーションは止まる)。environment"test"に設定されているときはデフォルトは有効。それ以外は無効。 -
- -
run
-
- 有効のとき、SinatraがWebサーバの起動を取り扱う。rackupまたは他の手段を使うときは有効にしないこと。 -
- -
running
-
ビルトインサーバが稼働中か?この設定を変更しないこと!
- -
server
-
- ビルトインサーバとして使用するサーバまたはサーバ群の指定。指定順位は優先度を表し、デフォルトはRuby実装に依存。 -
- -
sessions
-
- Rack::Session::Cookieを使ったクッキーベースのセッションサポートの有効化。詳しくは、'セッションの使用'の項を参照のこと。 -
- -
show_exceptions
-
- 例外発生時にブラウザにスタックトレースを表示する。environment"development"に設定されているときは、デフォルトで有効。それ以外は無効。 -
-
- また、:after_handlerをセットすることができ、これにより、ブラウザにスタックトレースを表示する前に、アプリケーション固有のエラーハンドリングを起動させられる。 -
- -
static
-
Sinatraが静的ファイルの提供を取り扱うかの設定。
-
その取り扱いができるサーバを使う場合は無効。
-
無効化でパフォーマンスは改善する
-
- クラッシックスタイルではデフォルトで有効。モジュラースタイルでは無効。 -
- -
static_cache_control
-
- Sinatraが静的ファイルを提供するときこれをセットして、レスポンスにCache-Controlヘッダを追加するようにする。cache_controlヘルパーを使うこと。デフォルトは無効。 -
-
- 複数の値をセットするときは明示的に配列を使う: - set :static_cache_control, [:public, :max_age => 300] -
- -
threaded
-
- trueに設定されているときは、Thinにリクエストを処理するためにEventMachine.deferを使うことを通知する。 -
- -
views
-
- ビューディレクトリのパス。設定されていない場合、app_file設定から推定する。 -
- -
x_cascade
-
- マッチするルーティングが無い場合に、X-Cascadeヘッダをセットするか否かの設定。デフォルトはtrue。 -
-
- -## 環境設定(Environments) - -3種類の既定環境、`"development"`、`"production"`および`"test"`があります。環境は、`RACK_ENV`環境変数を通して設定できます。デフォルト値は、`"development"`です。`"development"`環境において、すべてのテンプレートは、各リクエスト間で再ロードされ、そして、特別の`not_found`および`error`ハンドラがブラウザにスタックトレースを表示します。`"production"`および`"test"`環境においては、テンプレートはデフォルトでキャッシュされます。 - -異なる環境を走らせるには、`RACK_ENV`環境変数を設定します。 - -``` shell -RACK_ENV=production ruby my_app.rb -``` - -既定メソッド、`development?`、`test?`および`production?`を、現在の環境設定を確認するために使えます。 - -``` ruby -get '/' do - if settings.development? - "development!" - else - "not development!" - end -end -``` - -## エラーハンドリング(Error Handling) - -エラーハンドラはルーティングおよびbeforeフィルタと同じコンテキストで実行されます。すなわちこれは、`haml`、`erb`、`halt`といった便利なものが全て使えることを意味します。 - -### 未検出(Not Found) - -`Sinatra::NotFound`例外が発生したとき、またはレスポンスのステータスコードが404のときに、`not_found`ハンドラが発動します。 - -``` ruby -not_found do - 'ファイルが存在しません' -end -``` - -### エラー(Error) - -`error`ハンドラはルーティングブロックまたはフィルタ内で例外が発生したときはいつでも発動します。例外オブジェクトはRack変数`sinatra.error`から取得できます。 - -``` ruby -error do - 'エラーが発生しました。 - ' + env['sinatra.error'].name -end -``` - -エラーをカスタマイズする場合は、 - -``` ruby -error MyCustomError do - 'エラーメッセージ...' + env['sinatra.error'].message -end -``` - -と書いておいて、下記のように呼び出します。 - -``` ruby -get '/' do - raise MyCustomError, '何かがまずかったようです' -end -``` - -そうするとこうなります。 - -``` -エラーメッセージ... 何かがまずかったようです -``` - -あるいは、ステータスコードに対応するエラーハンドラを設定することもできます。 - -``` ruby -error 403 do - 'Access forbidden' -end - -get '/secret' do - 403 -end -``` - -範囲指定もできます。 - -``` ruby -error 400..510 do - 'Boom' -end -``` - -Sinatraを開発環境の下で実行している場合は、特別な`not_found`および`error`ハンドラが導入され、これは親切なスタックトレースと追加のデバッギング情報をブラウザに表示します。 - - -## Rackミドルウェア(Rack Middleware) - -SinatraはRuby製Webフレームワークのミニマルな標準的インタフェースである[Rack](http://rack.rubyforge.org/)上に構築されています。アプリケーションデベロッパーにとってRackにおける最も興味深い機能は、「ミドルウェア(middleware)」をサポートしていることであり、これは、サーバとアプリケーションとの間に置かれ、HTTPリクエスト/レスポンスを監視および/または操作することで、各種の汎用的機能を提供するコンポーネントです。 - -Sinatraはトップレベルの`use`メソッドを通して、Rackミドルウェアパイプラインの構築を楽にします。 - -``` ruby -require 'sinatra' -require 'my_custom_middleware' - -use Rack::Lint -use MyCustomMiddleware - -get '/hello' do - 'Hello World' -end -``` - -`use`の文法は、[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html)DSLで定義されているそれ(rackupファイルで最もよく使われる)と同じです。例えば `use`メソッドは複数の引数、そしてブロックも取ることができます。 - -``` ruby -use Rack::Auth::Basic do |username, password| - username == 'admin' && password == 'secret' -end -``` - -Rackは、ロギング、デバッギング、URLルーティング、認証、セッション管理など、多様な標準的ミドルウェアを共に配布されています。Sinatraはその多くのコンポーネントを自動で使うよう基本設定されているため、通常、それらを`use`で明示的に指定する必要はありません。 - -便利なミドルウェアを以下で見つけられます。 - -[rack](https://github.com/rack/rack/tree/master/lib/rack)、 -[rack-contrib](https://github.com/rack/rack-contrib#readm)、 -または[Rack wiki](https://github.com/rack/rack/wiki/List-of-Middleware)。 - -## テスト(Testing) - -SinatraでのテストはRackベースのテストライブラリまたはフレームワークを使って書くことができます。[Rack::Test](http://rdoc.info/github/brynary/rack-test/master/frames)をお薦めします。 - -``` ruby -require 'my_sinatra_app' -require 'test/unit' -require 'rack/test' - -class MyAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_my_default - get '/' - assert_equal 'Hello World!', last_response.body - end - - def test_with_params - get '/meet', :name => 'Frank' - assert_equal 'Hello Frank!', last_response.body - end - - def test_with_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "Songbirdを使ってます!", last_response.body - end -end -``` - -ノート: モジュラースタイルでSinatraを使う場合は、上記`Sinatra::Application`をアプリケーションのクラス名に置き換えてください。 - -## Sinatra::Base - ミドルウェア、ライブラリおよびモジュラーアプリ - -軽量なアプリケーションであれば、トップレベルでアプリケーションを定義していくことはうまくいきますが、再利用性可能なコンポーネント、例えばRackミドルウェア、RailsのMetal、サーバコンポーネントを含むシンプルなライブラリ、あるいはSinatraの拡張プログラムを構築するような場合、これは無視できない欠点を持つものとなります。トップレベルは、軽量なアプリケーションのスタイルにおける設定(例えば、単一のアプリケーションファイル、`./public`および`./views`ディレクトリ、ロギング、例外詳細ページなど)を仮定しています。そこで`Sinatra::Base`の出番です。 - -``` ruby -require 'sinatra/base' - -class MyApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Hello world!' - end -end -``` - -`Sinatra::Base`のサブクラスで利用できるメソッドは、トップレベルDSLで利用できるものと全く同じです。ほとんどのトップレベルで記述されたアプリは、以下の2点を修正することで`Sinatra::Base`コンポーネントに変えることができます。 - -* `sinatra`の代わりに`sinatra/base`を読み込む - (そうしない場合、SinatraのDSLメソッドの全てがmainの名前空間にインポートされます) -* ルーティング、エラーハンドラ、フィルタ、オプションを`Sinatra::Base`のサブクラスに書く - -`Sinatra::Base`はまっさらです。ビルトインサーバを含む、ほとんどのオプションがデフォルトで無効になっています。利用可能なオプションとその挙動の詳細については[Configuring Settings](http://sinatra.github.com/configuration.html)(英語)をご覧下さい。 - -もしもクラシックスタイルと同じような挙動のアプリケーションをトップレベルで定義させる必要があれば、`Sinatra::Application`をサブクラス化させてください。 - -```ruby -require "sinatra/base" - -class MyApp < Sinatra::Application - get "/" do - 'Hello world!' - end -end -``` - -### モジュラースタイル vs クラッシックスタイル - -一般的認識と違って、クラッシックスタイルを使うことに問題はなにもありません。それがそのアプリケーションに合っているのであれば、モジュラーアプリケーションに移行する必要はありません。 - -モジュラースタイルを使わずにクラッシックスタイルを使った場合の一番の不利な点は、Rubyプロセスごとにただ一つのSinatraアプリケーションしか持てない点です。複数が必要な場合はモジュラースタイルに移行してください。モジュラースタイルとクラッシックスタイルを混合できないということはありません。 - -一方のスタイルから他方へ移行する場合、デフォルト設定がわずかに異なる点に注意が必要です。 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
設定クラッシックモジュラーモジュラー
app_filesinatraを読み込むファイルSinatra::Baseをサブクラス化したファイルSinatra::Applicationをサブクラス化したファイル
run$0 == app_filefalsefalse
loggingtruefalsetrue
method_overridetruefalsetrue
inline_templatestruefalsetrue
statictruefalsetrue
- -### モジュラーアプリケーションの提供 - -モジュラーアプリケーションを開始、つまり`run!`を使って開始させる二種類のやり方があります。 - -``` ruby -# my_app.rb -require 'sinatra/base' - -class MyApp < Sinatra::Base - # ... アプリケーションのコードを書く ... - - # Rubyファイルが直接実行されたらサーバを立ち上げる - run! if app_file == $0 -end -``` - -として、次のように起動するか、 - -``` shell -ruby my_app.rb -``` - -または、Rackハンドラを使えるようにする`config.ru`ファイルを書いて、 - -``` ruby -# config.ru (rackupで起動) -require './my_app' -run MyApp -``` - -起動します。 - -``` shell -rackup -p 4567 -``` - -### config.ruを用いたクラッシックスタイルアプリケーションの使用 - -アプリケーションファイルと、 - -``` ruby -# app.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -対応する`config.ru`を書きます。 - -``` ruby -require './app' -run Sinatra::Application -``` - -### config.ruはいつ使うのか? - -`config.ru`ファイルは、以下の場合に適しています。 - -* 異なるRackハンドラ(Passenger, Unicorn, Herokuなど)でデプロイしたいとき -* `Sinatra::Base`の複数のサブクラスを使いたいとき -* Sinatraをミドルウェアとして利用し、エンドポイントとしては利用しないとき - -**モジュラースタイルに移行したという理由だけで、`config.ru`に移行する必要はなく、`config.ru`で起動するためにモジュラースタイルを使う必要はありません。** - -### Sinatraのミドルウェアとしての利用 - -Sinatraは他のRackミドルウェアを利用することができるだけでなく、 -全てのSinatraアプリケーションは、それ自体ミドルウェアとして別のRackエンドポイントの前に追加することが可能です。 - -このエンドポイントには、別のSinatraアプリケーションまたは他のRackベースのアプリケーション(Rails/Ramaze/Camping/…)が用いられるでしょう。 - -``` ruby -require 'sinatra/base' - -class LoginScreen < Sinatra::Base - enable :sessions - - get('/login') { haml :login } - - post('/login') do - if params[:name] = 'admin' and params[:password] = 'admin' - session['user_name'] = params[:name] - else - redirect '/login' - end - end -end - -class MyApp < Sinatra::Base - # ミドルウェアはbeforeフィルタの前に実行される - use LoginScreen - - before do - unless session['user_name'] - halt "アクセスは拒否されました。ログインしてください。" - end - end - - get('/') { "Hello #{session['user_name']}." } -end -``` - -### 動的なアプリケーションの生成 - -新しいアプリケーションを実行時に、定数に割り当てることなく生成したくなる場合があるでしょう。`Sinatra.new`を使えばそれができます。 - -``` ruby -require 'sinatra/base' -my_app = Sinatra.new { get('/') { "hi" } } -my_app.run! -``` - -これは省略できる引数として、それが継承するアプリケーションを取ります。 - -```ruby -# config.ru (rackupで起動) -require 'sinatra/base' - -controller = Sinatra.new do - enable :logging - helpers MyHelpers -end - -map('/a') do - run Sinatra.new(controller) { get('/') { 'a' } } -end - -map('/b') do - run Sinatra.new(controller) { get('/') { 'b' } } -end -``` - -これは特にSinatraのextensionをテストするときや、Sinatraを自身のライブラリで利用する場合に役立ちます。 - -これはまた、Sinatraをミドルウェアとして利用することを極めて簡単にします。 - -``` ruby -require 'sinatra/base' - -use Sinatra do - get('/') { ... } -end - -run RailsProject::Application -``` - -## スコープとバインディング(Scopes and Binding) - -現在のスコープはどのメソッドや変数が利用可能かを決定します。 - -### アプリケーション/クラスのスコープ - -全てのSinatraアプリケーションはSinatra::Baseのサブクラスに相当します。 -もしトップレベルDSLを利用しているならば(`require 'sinatra'`)このクラスはSinatra::Applicationであり、 -そうでなければ、あなたが明示的に作成したサブクラスです。 -クラスレベルでは`get`や`before`のようなメソッドを持っています。 -しかし`request`や`session`オブジェクトには、全てのリクエストに対する単一のアプリケーションクラスがあるだけなので、アクセスできません。 - -`set`によって作られたオプションはクラスレベルのメソッドです。 - -``` ruby -class MyApp < Sinatra::Base - # アプリケーションスコープの中だよ! - set :foo, 42 - foo # => 42 - - get '/foo' do - # もうアプリケーションスコープの中にいないよ! - end -end -``` - -次の場所ではアプリケーションスコープバインディングを持ちます。 - -* アプリケーションクラス本体 -* 拡張によって定義されたメソッド -* `helpers`に渡されたブロック -* `set`の値として使われるProcまたはブロック -* `Sinatra.new`に渡されたブロック - -このスコープオブジェクト(クラス)は次のように利用できます。 - -* configureブロックに渡されたオブジェクト経由(`configure { |c| ... }`) -* リクエストスコープの中での`settings` - -### リクエスト/インスタンスのスコープ - -やってくるリクエストごとに、あなたのアプリケーションクラスの新しいインスタンスが作成され、全てのハンドラブロックがそのスコープで実行されます。 -このスコープの内側からは`request`や`session`オブジェクトにアクセスすることができ、`erb`や`haml`のようなレンダリングメソッドを呼び出すことができます。 -リクエストスコープの内側からは、`settings`ヘルパーによってアプリケーションスコープにアクセスすることができます。 - -``` ruby -class MyApp < Sinatra::Base - # アプリケーションスコープの中だよ! - get '/define_route/:name' do - # '/define_route/:name'のためのリクエストスコープ - @value = 42 - - settings.get("/#{params[:name]}") do - # "/#{params[:name]}"のためのリクエストスコープ - @value # => nil (not the same request) - end - - "ルーティングが定義された!" - end -end -``` - -次の場所ではリクエストスコープバインディングを持ちます。 - -* get/head/post/put/delete/options/patch/link/unlink ブロック -* before/after フィルタ -* helper メソッド -* テンプレート/ビュー - -### デリゲートスコープ - -デリゲートスコープは、単にクラススコープにメソッドを転送します。 -しかしながら、クラスのバインディングを持っていないため、クラススコープと全く同じふるまいをするわけではありません。 -委譲すると明示的に示されたメソッドのみが利用可能であり、またクラススコープと変数/状態を共有することはできません(注: -異なった`self`を持っています)。 -`Sinatra::Delegator.delegate :method_name`を呼び出すことによってデリゲートするメソッドを明示的に追加することができます。 - -次の場所ではデリゲートスコープを持ちます。 - -* もし`require "sinatra"`しているならば、トップレベルバインディング -* `Sinatra::Delegator` mixinでextendされたオブジェクト - -コードをご覧ください: ここでは [Sinatra::Delegator -mixin](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633)は[mainオブジェクトにextendされています](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30)。 - -## コマンドライン - -Sinatraアプリケーションは直接実行できます。 - -``` shell -ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER] -``` - -オプション: - -``` --h # ヘルプ --p # ポート指定(デフォルトは4567) --o # ホスト指定(デフォルトは0.0.0.0) --e # 環境を指定 (デフォルトはdevelopment) --s # rackserver/handlerを指定 (デフォルトはthin) --x # mutex lockを付ける (デフォルトはoff) -``` - -## 必要環境 - -次のRubyバージョンが公式にサポートされています。 - -
-
Ruby 1.8.7
-
- 1.8.7は完全にサポートされていますが、特にそれでなければならないという理由がないのであれば、アップグレードまたはJRubyまたはRubiniusへの移行を薦めます。1.8.7のサポートがSinatra 2.0の前に終わることはないでしょう。Ruby 1.8.6はサポート対象外です。 -
- -
Ruby 1.9.2
-
- 1.9.2は完全にサポートされています。1.9.2p0は、Sinatraを起動したときにセグメントフォルトを引き起こすことが分かっているので、使わないでください。公式なサポートは、少なくともSinatra 1.5のリリースまでは続きます。 -
- -
Ruby 1.9.3
-
- 1.9.3は完全にサポート、そして推奨されています。以前のバージョンからの1.9.3への移行は全セッションを無効にする点、覚えておいてください。 -
- -
Ruby 2.0.0
-
- 2.0.0は完全にサポート、そして推奨されています。現在、その公式サポートを終了する計画はありません。 -
- -
Rubinius
-
- Rubiniusは公式にサポートされています(Rubinius >= 2.x)。 - gem install pumaすることが推奨されています。 -
- -
JRuby
-
- JRubyの最新安定版が公式にサポートされています。JRubyでC拡張を使うことは推奨されていません。 - gem install trinidadすることが推奨されています。 -
-
- -開発チームは常に最新となるRubyバージョンに注視しています。 - -次のRuby実装は公式にはサポートされていませんが、Sinatraが起動すると報告されています。 - -* JRubyとRubiniusの古いバージョン -* Ruby Enterprise Edition -* MacRuby, Maglev, IronRuby -* Ruby 1.9.0と1.9.1 (これらの使用はお薦めしません) - -公式サポートをしないという意味は、問題がそこだけで起こり、サポートされているプラットフォーム上では起きない場合に、開発チームはそれはこちら側の問題ではないとみなすということです。 - -開発チームはまた、ruby-head(最新となる2.1.0)に対しCIを実行していますが、それが一貫して動くようになるまで何も保証しません。2.1.0が完全にサポートされればその限りではありません。 - -Sinatraは、利用するRuby実装がサポートしているオペレーティングシステム上なら動作するはずです。 - -MacRubyを使う場合は、`gem install control_tower`してください。 - -Sinatraは現在、Cardinal、SmallRuby、BlueRubyまたは1.8.7以前のバージョンのRuby上では動作しません。 - -## 最新開発版 - -Sinatraの最新開発版のコードを使いたい場合は、マスターブランチに対してアプリケーションを走らせて構いません。ある程度安定しています。また、適宜プレリリース版gemをpushしているので、 - -``` shell -gem install sinatra --pre -``` - -すれば、最新の機能のいくつかを利用できます。 - -### Bundlerを使う場合 - -最新のSinatraでアプリケーションを動作させたい場合には、[Bundler](http://gembundler.com/)を使うのがお薦めのやり方です。 - -まず、Bundlerがなければそれをインストールします。 - -``` shell -gem install bundler -``` - -そして、プロジェクトのディレクトリで、`Gemfile`を作ります。 - -```ruby -source 'https://rubygems.org' -gem 'sinatra', :github => "sinatra/sinatra" - -# 他の依存ライブラリ -gem 'haml' # Hamlを使う場合 -gem 'activerecord', '~> 3.0' # ActiveRecord 3.xが必要かもしれません -``` - -ノート: `Gemfile`にアプリケーションの依存ライブラリのすべてを並べる必要があります。しかし、Sinatraが直接依存するもの(RackおよびTile)はBundlerによって自動的に取り込まれ、追加されます。 - -これで、以下のようにしてアプリケーションを起動することができます。 - -``` shell -bundle exec ruby myapp.rb -``` - -### 直接組み込む場合 - -ローカルにクローンを作って、`sinatra/lib`ディレクトリを`$LOAD_PATH`に追加してアプリケーションを起動します。 - -``` shell -cd myapp -git clone git://github.com/sinatra/sinatra.git -ruby -I sinatra/lib myapp.rb -``` - -追ってSinatraのソースを更新する方法。 - -``` shell -cd myapp/sinatra -git pull -``` - -### グローバル環境にインストールする場合 - -Sinatraのgemを自身でビルドすることもできます。 - -``` shell -git clone git://github.com/sinatra/sinatra.git -cd sinatra -rake sinatra.gemspec -rake install -``` - -gemをルートとしてインストールする場合は、最後のステップはこうなります。 - -``` shell -sudo rake install -``` - -## バージョニング(Versioning) - -Sinatraは、[Semantic Versioning](http://semver.org/)におけるSemVerおよびSemVerTagの両方に準拠しています。 - -## 参考文献 - -* [プロジェクトサイト](http://sinatra.github.com/) - ドキュメント、ニュース、他のリソースへのリンクがあります。 -* [プロジェクトに参加(貢献)する](http://sinatra.github.com/contributing.html) - バグレポート パッチの送信、サポートなど -* [Issue tracker](http://github.com/sinatra/sinatra/issues) -* [Twitter](http://twitter.com/sinatra) -* [メーリングリスト](http://groups.google.com/group/sinatrarb/topics) -* http://freenode.net上のIRC: [#sinatra](irc://chat.freenode.net/#sinatra) -* [Sinatra Book](http://sinatra-book.gittr.com) クックブック、チュートリアル -* [Sinatra Recipes](http://recipes.sinatrarb.com/) コミュニティによるレシピ集 -* http://rubydoc.info上のAPIドキュメント: [最新版(latest release)用](http://rubydoc.info/gems/sinatra)または[現在のHEAD用](http://rubydoc.info/github/sinatra/sinatra) -* [CIサーバ](http://travis-ci.org/sinatra/sinatra) -* [Greenbear Laboratory Rack日本語マニュアル](http://route477.net/w/RackReferenceJa.html) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ko.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ko.md deleted file mode 100644 index 3177b35..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ko.md +++ /dev/null @@ -1,2832 +0,0 @@ -# Sinatra - -*주의: 이 문서는 영문판의 번역본이며 최신판 문서와 다를 수 있습니다.* - -Sinatra는 최소한의 노력으로 루비 기반 웹 애플리케이션을 신속하게 만들 수 있게 -해 주는 [DSL](http://en.wikipedia.org/wiki/Domain-specific_language)입니다. - -``` ruby -# myapp.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -젬을 설치합니다. - -``` shell -gem install sinatra -``` - -실행합니다. - -``` shell -ruby myapp.rb -``` - -`http://localhost:4567`를 확인해 보세요. - -`gem install thin`도 함께 실행하기를 권장합니다. -thin이 설치되어 있을 경우 Sinatra는 thin을 통해 실행합니다. - -## 목차 - -* [Sinatra](#sinatra) - * [목차](#목차) - * [라우터(Routes)](#라우터routes) - * [조건(Conditions)](#조건conditions) - * [반환값(Return Values)](#반환값return-values) - * [커스텀 라우터 매처(Custom Route Matchers)](#커스텀-라우터-매처custom-route-matchers) - * [정적 파일(Static Files)](#정적-파일static-files) - * [뷰 / 템플릿(Views / Templates)](#뷰--템플릿views--templates) - * [리터럴 템플릿(Literal Templates)](#리터럴-템플릿literal-templates) - * [가능한 템플릿 언어들(Available Template Languages)](#가능한-템플릿-언어들available-template-languages) - * [Haml 템플릿](#haml-템플릿) - * [Erb 템플릿](#erb-템플릿) - * [Builder 템플릿](#builder-템플릿) - * [Nokogiri 템플릿](#nokogiri-템플릿) - * [Sass 템플릿](#sass-템플릿) - * [SCSS 템플릿](#scss-템플릿) - * [Less 템플릿](#less-템플릿) - * [Liquid 템플릿](#liquid-템플릿) - * [Markdown 템플릿](#markdown-템플릿) - * [Textile 템플릿](#textile-템플릿) - * [RDoc 템플릿](#rdoc-템플릿) - * [Radius 템플릿](#radius-템플릿) - * [Markaby 템플릿](#markaby-템플릿) - * [RABL 템플릿](#rabl-템플릿) - * [Slim 템플릿](#slim-템플릿) - * [Creole 템플릿](#creole-템플릿) - * [CoffeeScript 템플릿](#coffeescript-템플릿) - * [Stylus 템플릿](#stylus-템플릿) - * [Yajl 템플릿](#yajl-템플릿) - * [WLang 템플릿](#wlang-템플릿) - * [템플릿에서 변수에 접근하기](#템플릿에서-변수에-접근하기) - * [템플릿에서의 `yield` 와 중첩 레이아웃](#템플릿에서의-yield-와-중첩-레이아웃) - * [인라인 템플릿](#인라인-템플릿) - * [이름을 가지는 템플릿(Named Templates)](#이름을-가지는-템플릿named-templates) - * [파일 확장자 연결하기](#파일-확장자-연결하기) - * [나만의 고유한 템플릿 엔진 추가하기](#나만의-고유한-템플릿-엔진-추가하기) - * [필터(Filters)](#필터filters) - * [헬퍼(Helpers)](#헬퍼helpers) - * [세션(Sessions) 사용하기](#세션sessions-사용하기) - * [중단하기(Halting)](#중단하기halting) - * [넘기기(Passing)](#넘기기passing) - * [다른 라우터 부르기(Triggering Another Route)](#다른-라우터-부르기triggering-another-route) - * [본문, 상태 코드 및 헤더 설정하기](#본문-상태-코드-및-헤더-설정하기) - * [응답 스트리밍(Streaming Responses)](#응답-스트리밍streaming-responses) - * [로깅(Logging)](#로깅logging) - * [마임 타입(Mime Types)](#마임-타입mime-types) - * [URL 생성하기](#url-생성하기) - * [브라우저 재지정(Browser Redirect)](#브라우저-재지정browser-redirect) - * [캐시 컨트롤(Cache Control)](#캐시-컨트롤cache-control) - * [파일 전송하기(Sending Files)](#파일-전송하기sending-files) - * [요청 객체에 접근하기(Accessing the Request Object)](#요청-객체에-접근하기accessing-the-request-object) - * [첨부(Attachments)](#첨부attachments) - * [날짜와 시간 다루기](#날짜와-시간-다루기) - * [템플릿 파일 참조하기](#템플릿-파일-참조하기) - * [설정(Configuration)](#설정configuration) - * [공격 방어 설정하기(Configuring attack protection)](#공격-방어-설정하기configuring-attack-protection) - * [가능한 설정들(Available Settings)](#가능한-설정들available-settings) - * [환경(Environments)](#환경environments) - * [에러 처리(Error Handling)](#에러-처리error-handling) - * [찾을 수 없음(Not Found)](#찾을-수-없음not-found) - * [에러](#에러) - * [Rack 미들웨어(Rack Middleware)](#rack-미들웨어rack-middleware) - * [테스팅(Testing)](#테스팅testing) - * [Sinatra::Base - 미들웨어(Middleware), 라이브러리(Libraries), 그리고 모듈 앱(Modular Apps)](#sinatrabase---미들웨어middleware-라이브러리libraries-그리고-모듈-앱modular-apps) - * [모듈(Modular) vs. 전통적 방식(Classic Style)](#모듈modular-vs-전통적-방식classic-style) - * [모듈 애플리케이션(Modular Application) 제공하기](#모듈-애플리케이션modular-application-제공하기) - * [config.ru로 전통적 방식의 애플리케이션 사용하기](#configru로-전통적-방식의-애플리케이션-사용하기) - * [언제 config.ru를 사용할까?](#언제-configru를-사용할까) - * [Sinatra를 미들웨어로 사용하기](#sinatra를-미들웨어로-사용하기) - * [동적인 애플리케이션 생성(Dynamic Application Creation)](#동적인-애플리케이션-생성dynamic-application-creation) - * [범위(Scopes)와 바인딩(Binding)](#범위scopes와-바인딩binding) - * [애플리케이션/클래스 범위](#애플리케이션클래스-범위) - * [요청/인스턴스 범위](#요청인스턴스-범위) - * [위임 범위(Delegation Scope)](#위임-범위delegation-scope) - * [명령행(Command Line)](#명령행command-line) - * [요구사항(Requirement)](#요구사항requirement) - * [최신(The Bleeding Edge)](#최신the-bleeding-edge) - * [Bundler를 사용하여](#bundler를-사용하여) - * [직접 하기(Roll Your Own)](#직접-하기roll-your-own) - * [전역으로 설치(Install Globally)](#전역으로-설치install-globally) - * [버저닝(Versioning)](#버저닝versioning) - * [더 읽을 거리(Further Reading)](#더-읽을-거리further-reading) - -## 라우터(Routes) - -Sinatra에서, 라우터(route)는 URL-매칭 패턴과 쌍을 이루는 HTTP 메서드입니다. -각각의 라우터는 블록과 연결됩니다. - -``` ruby -get '/' do - .. 무언가 보여주기(show) .. -end - -post '/' do - .. 무언가 만들기(create) .. -end - -put '/' do - .. 무언가 대체하기(replace) .. -end - -patch '/' do - .. 무언가 수정하기(modify) .. -end - -delete '/' do - .. 무언가 없애기(annihilate) .. -end - -options '/' do - .. 무언가 주기(appease) .. -end - -link '/' do - .. 무언가 관계맺기(affiliate) .. -end - -unlink '/' do - .. 무언가 격리하기(separate) .. -end -``` - -라우터는 정의된 순서에 따라 매치되고 요청에 대해 가장 먼저 매칭된 라우터가 호출됩니다. - -라우터 패턴에는 이름을 가진 매개변수가 포함될 수 있으며, `params` 해시로 접근할 수 있습니다. - -``` ruby -get '/hello/:name' do - # "GET /hello/foo" 및 "GET /hello/bar"와 매치 - # params[:name]은 'foo' 또는 'bar' - "Hello #{params[:name]}!" -end -``` - -또한 블록 매개변수를 통하여도 이름을 가진 매개변수에 접근할 수 있습니다. - -``` ruby -get '/hello/:name' do |n| - # "GET /hello/foo" 및 "GET /hello/bar"와 매치 - # params[:name]은 'foo' 또는 'bar' - "Hello #{n}!" -end -``` - -라우터 패턴에는 스플랫(splat, 또는 와일드카드)도 매개변수도 포함될 수 있으며, 이럴 경우 `params[:splat]` 배열을 통해 접근할 수 있습니다. - -``` ruby -get '/say/*/to/*' do - # /say/hello/to/world와 매치 - params[:splat] # => ["hello", "world"] -end - -get '/download/*.*' do - # /download/path/to/file.xml과 매치 - params[:splat] # => ["path/to/file", "xml"] -end -``` - -블록 매개변수로도 접근할 수 있습니다. - -``` ruby -get '/download/*.*' do |path, ext| - [path, ext] # => ["path/to/file", "xml"] -end -``` - -라우터는 정규표현식으로 매치할 수 있습니다. - -``` ruby -get %r{/hello/([\w]+)} do - "Hello, #{params[:captures].first}!" -end -``` - -블록 매개변수로도 사용가능합니다. - -``` ruby -get %r{/hello/([\w]+)} do |c| - "Hello, #{c}!" -end -``` - -라우터 패턴에는 선택적인(optional) 매개변수도 올 수 있습니다. - -``` ruby -get '/posts.?:format?' do - # "GET /posts" 는 물론 "GET /posts.json", "GET /posts.xml" 와 같은 어떤 확장자와도 매칭 -end -``` - -한편, 경로 탐색 공격 방지(path traversal attack protection, 아래 참조)를 비활성화시키지 않았다면, -요청 경로는 라우터와 매칭되기 이전에 수정될 수 있습니다. - -### 조건(Conditions) - -라우터는 사용자 에이전트(user agent)같은 다양한 매칭 조건을 포함할 수 있습니다. - -``` ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "Songbird 버전 #{params[:agent][0]}을 사용하는군요!" -end - -get '/foo' do - # songbird 브라우저가 아닌 경우 매치 -end -``` - -다른 가능한 조건에는 `host_name`과 `provides`가 있습니다. - -``` ruby -get '/', :host_name => /^admin\./ do - "Admin Area, Access denied!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -사용자 정의 조건도 쉽게 만들 수 있습니다. - -``` ruby -set(:probability) { |value| condition { rand <= value } } - -get '/win_a_car', :probability => 0.1 do - "내가 졌소!" -end - -get '/win_a_car' do - "미안해서 어쩌나." -end -``` - -여러 값을 받는 조건에는 스플랫(splat)을 사용합니다. - -``` ruby -set(:auth) do |*roles| # <- 이게 스플랫 - condition do - unless logged_in? && roles.any? {|role| current_user.in_role? role } - redirect "/login/", 303 - end - end -end - -get "/my/account/", :auth => [:user, :admin] do - "내 계정 정보" -end - -get "/only/admin/", :auth => :admin do - "관리자 외 접근불가!" -end -``` - -### 반환값(Return Values) - -라우터 블록의 반환 값은 HTTP 클라이언트로 전달되는 응답 본문만을 결정하거나, 또는 Rack 스택에서 다음 번 미들웨어만를 결정합니다. -위의 예제에서 볼 수 있지만 대부분의 경우 이 반환값은 문자열입니다.하지만 다른 값도 허용됩니다. - -유효한 Rack 응답, Rack 본문 객체 또는 HTTP 상태 코드가 되는 어떠한 객체라도 반환할 수 있습니다. - -* 세 요소를 가진 배열: `[상태 (Fixnum), 헤더 (Hash), 응답 본문 (#each에 반응)]` -* 두 요소를 가진 배열: `[상태 (Fixnum), 응답 본문 (#each에 반응)]` -* `#each`에 반응하고 주어진 블록으로 문자열만을 전달하는 객체 -* 상태 코드를 의미하는 Fixnum - -이것을 이용한 예를 들자면, 스트리밍(streaming) 예제를 쉽게 구현할 수 있습니다. - -``` ruby -class Stream - def each -100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -`stream` 헬퍼 메서드(아래 참조)를 사용하면 이런 번거로움을 줄이고 스트리밍 로직을 라우터 속에 포함 시킬 수도 있습니다. - -### 커스텀 라우터 매처(Custom Route Matchers) - -위에서 보듯, Sinatra에는 문자열 패턴 및 정규표현식을 이용한 라우터 매칭 지원이 내장되어 있습니다. -하지만, 그게 끝은 아닙니다. 여러분 만의 매처(matcher)도 쉽게 정의할 수 있습니다. - -``` ruby -class AllButPattern - Match = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Match.new([]) - end - - def match(str) - @captures unless @except === str - end -end - -def all_but(pattern) - AllButPattern.new(pattern) -end - -get all_but("/index") do - # ... -end -``` - -사실 위의 예제는 조금 과하게 작성된 면이 있습니다. 간단하게 표현할 수도 있어요. - -``` ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -또는 거꾸로 탐색(negative look ahead)할 수도 있습니다. - -``` ruby -get %r{^(?!/index$)} do - # ... -end -``` - -## 정적 파일(Static Files) - -정적 파일들은 `./public` 디렉터리에서 제공됩니다. 위치를 다른 곳으로 -변경하려면 `:public_folder` 옵션을 지정하면 됩니다. - -``` ruby -set :public_folder, File.dirname(__FILE__) + '/static' -``` - -public 디렉터리명은 URL에 포함되지 않는다는 점에 주의하세요. -`./public/css/style.css` 파일은 아마 `http://example.com/css/style.css` 로 접근할 수 있을 것 입니다. - -`Cache-Control` 헤더 정보를 추가하려면 `:static_cache_control` 설정(아래 참조)을 사용하면 됩니다. - -## 뷰 / 템플릿(Views / Templates) - -템플릿 언어들은 각각의 렌더링 메서드를 통해 표출됩니다. -이들 메서드는 문자열을 반환할 뿐입니다. - -``` ruby -get '/' do - erb :index -end -``` - -이 구문은 `views/index.erb`를 렌더합니다. - -템플릿 이름 대신 템플릿의 내용을 직접 넘길 수도 있습니다. - -``` ruby -get '/' do - code = "<%= Time.now %>" - erb code -end -``` - -템플릿은 두 번째 인자로 옵션값의 해시를 받습니다. - -``` ruby -get '/' do - erb :index, :layout => :post -end -``` - -이 구문은 `views/post.erb` 속에 내장된 `views/index.erb`를 렌더합니다. -(`views/layout.erb`파일이 존재할 경우 기본값은 `views/layout.erb`입니다.) - -Sinatra가 이해하지 못하는 모든 옵션값들은 템플릿 엔진으로 전달됩니다. - -``` ruby -get '/' do - haml :index, :format => :html5 -end -``` - -옵션값은 템플릿 언어별로 전역적으로 설정할 수도 있습니다. - -``` ruby -set :haml, :format => :html5 - -get '/' do - haml :index -end -``` - -render 메서드에서 전달된 옵션값들은 `set`을 통해 설정한 옵션값보다 우선합니다. - -가능한 옵션값들은 다음과 같습니다. - -
-
locals
-
- 문서로 전달되는 local 목록. 파셜과 함께 사용하기 좋음. - 예제: erb "<%= foo %>", :locals => {:foo => "bar"} -
- -
default_encoding
-
- 불확실한 경우에 사용할 문자열 인코딩. - 기본값은 settings.default_encoding. -
- -
views
-
- 템플릿을 로드할 뷰 폴더. - 기본값은 settings.views. -
- -
layout
-
- 레이아웃을 사용할지 여부 (true 또는 false), 만약 이 값이 심볼일 경우, - 사용할 템플릿을 지정. 예제: erb :index, :layout => !request.xhr? -
- -
content_type
-
- 템플릿이 생성하는 Content-Type, 기본값은 템플릿 언어에 의존. -
- -
scope
-
- 템플릿을 렌더링하는 범위. 기본값은 어플리케이션 인스턴스. - 만약 이 값을 변경하면, 인스턴스 변수와 헬퍼 메서드들을 사용할 수 없게 됨. -
- -
layout_engine
-
- 레이아웃 렌더링에 사용할 템플릿 엔진. 레이아웃을 지원하지 않는 언어인 경우에 유용. - 기본값은 템플릿에서 사용하는 엔진. 예제: set :rdoc, :layout_engine => :erb -
-
- - -템플릿은 `./views` 디렉터리에 있는 것으로 가정됩니다. 뷰 디렉터리를 -다른 곳으로 하고 싶으시면 이렇게 하세요. - -``` ruby -set :views, settings.root + '/templates' -``` - -템플릿은 언제나 심볼로 참조되어야 한다는 것에 주의하세요. -템플릿이 하위 디렉터리에 위치한 경우(그럴 경우에는 `:'subdir/template'`을 -사용)에도 예외는 없습니다. 반드시 심볼이어야 하는 이유는, 문자열을 넘기면 -렌더링 메서드가 전달된 문자열을 직접 렌더하기 때문입니다. - -### 리터럴 템플릿(Literal Templates) - -``` ruby -get '/' do - haml '%div.title Hello World' -end -``` - -템플릿 문자열을 렌더합니다. - -### 가능한 템플릿 언어들(Available Template Languages) - -일부 언어는 여러 개의 구현이 있습니다. (스레드에 안전하게 thread-safe) 어느 구현을 -사용할지 저정하려면, 먼저 require 하기만 하면 됩니다. - -``` ruby -require 'rdiscount' # or require 'bluecloth' -get('/') { markdown :index } -``` - -#### Haml 템플릿 - - - - - - - - - - - - - - -
의존성haml
파일 확장자.haml
예제haml :index, :format => :html5
- -#### Erb 템플릿 - - - - - - - - - - - - - - -
의존성erubis 또는 erb (루비 속에 포함)
파일 확장자.erb, .rhtml, .erubis (Erubis만 해당)
예제erb :index
- -#### Builder 템플릿 - - - - - - - - - - - - - - -
의존성builder
파일 확장자.builder
예제builder { |xml| xml.em "hi" }
- -인라인 템플릿으로 블록을 받을 수도 있습니다(예제 참조). - -#### Nokogiri 템플릿 - - - - - - - - - - - - - - -
의존성nokogiri
파일 확장자.nokogiri
예제nokogiri { |xml| xml.em "hi" }
- -인라인 템플릿으로 블록을 받을 수도 있습니다(예제 참조). - -#### Sass 템플릿 - - - - - - - - - - - - - - -
의존성sass
파일 확장자.sass
예제sass :stylesheet, :style => :expanded
- -#### SCSS 템플릿 - - - - - - - - - - - - - - -
의존성sass
파일 확장자.scss
예제scss :stylesheet, :style => :expanded
- -#### Less 템플릿 - - - - - - - - - - - - - - -
의존성less
파일 확장자.less
예제less :stylesheet
- -#### Liquid 템플릿 - - - - - - - - - - - - - - -
의존성liquid
파일 확장자.liquid
예제liquid :index, :locals => { :key => 'value' }
- -Liquid 템플릿에서는 루비 메서드(`yield` 제외)를 호출할 수 없기 -때문에, 거의 대부분의 경우 locals를 전달해야 합니다. - -#### Markdown 템플릿 - - - - - - - - - - - - - - -
의존성 - RDiscount, - RedCarpet, - BlueCloth, - kramdown, - maruku - 중 아무거나 -
파일 확장.markdown, .mkd, .md
예제markdown :index, :layout_engine => :erb
- -Markdown에서는 메서드 호출 뿐 아니라 locals 전달도 안됩니다. -따라서 일반적으로는 다른 렌더링 엔진과 함께 사용하게 됩니다. - -``` ruby -erb :overview, :locals => { :text => markdown(:introduction) } -``` - -다른 템플릿 속에서 `markdown` 메서드를 호출할 수도 있습니다. - -``` ruby -%h1 안녕 Haml! -%p= markdown(:greetings) -``` - -Markdown에서 루비를 호출할 수 없기 때문에, Markdown으로 작성된 레이아웃은 -사용할 수 없습니다. 하지만, `:layout_engine` 옵션으로 레이아웃의 템플릿을 -다른 렌더링 엔진으로 렌더링 할 수는 있습니다. - -#### Textile 템플릿 - - - - - - - - - - - - - - -
의존성RedCloth
파일 확장자.textile
예제textile :index, :layout_engine => :erb
- -Textile에서는 메서드 호출 뿐 아니라 locals 전달도 안됩니다. -따라서 일반적으로는 다른 렌더링 엔진과 함께 사용하게 됩니다. - -``` ruby -erb :overview, :locals => { :text => textile(:introduction) } -``` - -다른 템플릿 속에서 `textile` 메서드를 호출할 수도 있습니다. - -``` ruby -%h1 안녕 Haml! -%p= textile(:greetings) -``` - -Textile에서 루비를 호출할 수 없기 때문에, Textile으로 작성된 레이아웃은 -사용할 수 없습니다. 하지만, `:layout_engine` 옵션으로 레이아웃의 템플릿을 -다른 렌더링 엔진으로 렌더링 할 수는 있습니다. - -#### RDoc 템플릿 - - - - - - - - - - - - - - -
의존성rdoc
파일 확장자.rdoc
예제rdoc :README, :layout_engine => :erb
- -RDoc에서는 메서드 호출 뿐 아니라 locals 전달도 안됩니다. -따라서 일반적으로는 다른 렌더링 엔진과 함께 사용하게 됩니다. - -``` ruby -erb :overview, :locals => { :text => rdoc(:introduction) } -``` - -다른 템플릿 속에서 `rdoc` 메서드를 호출할 수도 있습니다. - -``` ruby -%h1 Hello From Haml! -%p= rdoc(:greetings) -``` - -RDoc에서 루비를 호출할 수 없기 때문에, RDoc으로 작성된 레이아웃은 -사용할 수 없습니다. 하지만, `:layout_engine` 옵션으로 레이아웃의 템플릿을 -다른 렌더링 엔진으로 렌더링 할 수는 있습니다. - -#### Radius 템플릿 - - - - - - - - - - - - - - -
의존성radius
파일 확장자.radius
예제radius :index, :locals => { :key => 'value' }
- -Radius 템플릿에서는 루비 메서드를 호출할 수 없기 -때문에, 거의 대부분의 경우 locals를 전달해야 합니다. - -#### Markaby 템플릿 - - - - - - - - - - - - - - -
의존성markaby
파일확장.mab
예제markaby { h1 "Welcome!" }
- -인라인 템플릿으로 블록을 받을 수도 있습니다(예제 참조). - -#### RABL 템플릿 - - - - - - - - - - - - - - -
의존성rabl
파일 확장자.rabl
예제rabl :index
- -#### Slim 템플릿 - - - - - - - - - - - - - - -
의존성slim
파일 확장자.slim
예제slim :index
- -#### Creole 템플릿 - - - - - - - - - - - - - - -
의존성creole
파일 확장자.creole
예제creole :wiki, :layout_engine => :erb
- -Creole에서는 메서드 호출 뿐 아니라 locals 전달도 안됩니다. -따라서 일반적으로는 다른 렌더링 엔진과 함께 사용하게 됩니다. - -``` ruby -erb :overview, :locals => { :text => creole(:introduction) } -``` - -다른 템플릿 속에서 `creole` 메서드를 호출할 수도 있습니다. - -``` ruby -%h1 Hello From Haml! -%p= creole(:greetings) -``` - -Creole에서 루비를 호출할 수 없기 때문에, Creole으로 작성된 레이아웃은 -사용할 수 없습니다. 하지만, `:layout_engine` 옵션으로 레이아웃의 템플릿을 -다른 렌더링 엔진으로 렌더링 할 수는 있습니다. - -#### CoffeeScript 템플릿 - - - - - - - - - - - - - - -
의존성 - - CoffeeScript - 와 - - 자바스크립트 실행법 - -
파일 확장자.coffee
예제coffee :index
- -#### Stylus 템플릿 - - - - - - - - - - - - - - -
의존성 - - Stylus - 와 - - 자바스크립트 실행법 - -
파일 확장자.styl
예제stylus :index
- -Stylus 템플릿을 사용가능하게 하려면, 먼저 `stylus`와 `stylus/tilt`를 로드 -해야합니다. - -``` ruby -require 'sinatra' -require 'stylus' -require 'stylus/tilt' - -get '/' do - stylus :example -end -``` - -#### Yajl 템플릿 - - - - - - - - - - - - - - -
의존성yajl-ruby
파일 확장자.yajl
예제 - - yajl :index, - :locals => { :key => 'qux' }, - :callback => 'present', - :variable => 'resource' - -
- -템플릿 소스는 루비 문자열로 평가(evaluate)되고, 결과인 json 변수는 `#to_json`으로 변환됩니다. - -``` ruby -json = { :foo => 'bar' } -json[:baz] = key -``` - -`:callback`과 `:variable` 옵션은 렌더된 객체를 꾸미는데(decorate) 사용할 수 있습니다. - -```javascript -var resource = {"foo":"bar","baz":"qux"}; -present(resource); -``` - -#### WLang 템플릿 - - - - - - - - - - - - - - -
의존성WLang
파일 확장자.wlang
예제wlang :index, :locals => { :key => 'value' }
- -WLang 템플릿에서는 루비 메서드(`yield` 제외)를 호출할 수 없기 -때문에, 거의 대부분의 경우 locals를 전달해야 합니다. 그래도 -WLang으로 쓰여진 레이아웃과 `yield`는 지원합니다. - -### 템플릿에서 변수에 접근하기 - -템플릿은 라우터 핸들러와 같은 맥락(context)에서 평가됩니다. 라우터 -핸들러에서 설정한 인스턴스 변수들은 템플릿에서 직접 접근 가능합니다. - -``` ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.name' -end -``` - -명시적으로 로컬 변수의 해시를 지정할 수도 있습니다. - -``` ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= bar.name', :locals => { :bar => foo } -end -``` - -이 방법은 주로 템플릿을 다른 템플릿 속에서 파셜(partial)로 렌더링할 -때 사용됩니다. - -### 템플릿에서의 `yield` 와 중첩 레이아웃 - -레이아웃은 보통 `yield`만 호출하는 템플릿입니다. -위에 설명된 `:template` 옵션을 통해 템플릿을 사용하거나, -다음 예제처럼 블록으로 렌더링 할 수 있습니다. - -``` ruby -erb :post, :layout => false do - erb :index -end -``` - -위 코드는 `erb :index, :layout => :post`와 대부분 동일합니다. - -렌더링 메서드에 블록 넘기기는 중첩 레이아웃을 만들때 유용합니다. - -``` ruby -erb :main_layout, :layout => false do - erb :admin_layout do - erb :user - end -end -``` - -위의 코드도 줄일 수 있습니다. - -``` ruby -erb :admin_layout, :layout => :main_layout do - erb :user -end -``` - -현재, `erb`, `haml`, `liquid`, `slim `, `wlang`는 블럭을 지원합니다. -일반적인 `render` 메소드도 블럭을 지원합니다. - -### 인라인 템플릿 - -템플릿은 소스 파일의 마지막에서 정의할 수도 있습니다. - -``` ruby -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html -= yield - -@@ index -%div.title Hello world. -``` - -참고: sinatra를 require한 소스 파일에 정의된 인라인 템플릿은 자동으로 -로드됩니다. 다른 소스 파일에서 인라인 템플릿을 사용하려면 명시적으로 -`enable :inline_templates`을 호출하면 됩니다. - -### 이름을 가지는 템플릿(Named Templates) - -템플릿은 톱 레벨(top-level)에서 `template`메서드로도 정의할 수 있습니다. - -``` ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Hello World!' -end - -get '/' do - haml :index -end -``` - -"layout"이라는 이름의 템플릿이 존재하면, 템플릿이 렌더될 때마다 사용됩니다. -레이아웃을 비활성화할 때는 `:layout => false`를 전달하여 개별적으로 -비활성시키거나 `set :haml, :layout => false`으로 기본값을 비활성으로 둘 수 -있습니다. - -``` ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -### 파일 확장자 연결하기 - -어떤 파일 확장자를 특정 템플릿 엔진과 연결하려면, `Tilt.register`를 사용하면 -됩니다. 예를 들어, `tt`라는 파일 확장자를 Textile 템플릿과 연결하고 싶다면, -다음과 같이 하면 됩니다. - -``` ruby -Tilt.register :tt, Tilt[:textile] -``` - -### 나만의 고유한 템플릿 엔진 추가하기 - -우선, Tilt로 여러분 엔진을 등록하고, 렌더링 메서드를 생성합니다. - -``` ruby -Tilt.register :myat, MyAwesomeTemplateEngine - -helpers do - def myat(*args) render(:myat, *args) end -end - -get '/' do - myat :index -end -``` - -위 코드는 `./views/index.myat` 를 렌더합니다. -Tilt에 대한 더 자세한 내용은 https://github.com/rtomayko/tilt 참조하세요. - -## 필터(Filters) - -사전 필터(before filter)는 라우터와 동일한 맥락에서 매 요청 전에 평가되며 -요청과 응답을 변형할 수 있습니다. 필터에서 설정된 인스턴스 변수들은 라우터와 -템플릿에서 접근 가능합니다. - -``` ruby -before do - @note = 'Hi!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @note #=> 'Hi!' - params[:splat] #=> 'bar/baz' -end -``` - -사후 필터(after filter)는 라우터와 동일한 맥락에서 매 요청 이후에 평가되며 -마찬가지로 요청과 응답을 변형할 수 있습니다. 사전 필터와 라우터에서 설정된 -인스턴스 변수들은 사후 필터에서 접근 가능합니다. - -``` ruby -after do - puts response.status -end -``` - -참고: 만약 라우터에서 `body` 메서드를 사용하지 않고 그냥 문자열만 반환한 -경우라면, body는 나중에 생성되는 탓에, 아직 사후 필터에서 사용할 수 없을 -것입니다. - -필터는 패턴을 취할 수도 있으며, 이 경우 요청 경로가 그 패턴과 매치할 -경우에만 필터가 평가될 것입니다. - -``` ruby -before '/protected/*' do - authenticate! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -``` - -라우터와 마찬가지로, 필터 역시 조건을 취할 수 있습니다. - -``` ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'example.com' do - # ... -end -``` - -## 헬퍼(Helpers) - -톱-레벨의 `helpers` 메서드를 사용하여 라우터 핸들러와 템플릿에서 사용할 헬퍼 -메서드들을 정의할 수 있습니다. - -``` ruby -helpers do - def bar(name) - "#{name}bar" - end -end - -get '/:name' do - bar(params[:name]) -end -``` - -또는, 헬퍼 메서드는 별도의 모듈 속에 정의할 수도 있습니다. - -``` ruby -module FooUtils - def foo(name) "#{name}foo" end -end - -module BarUtils - def bar(name) "#{name}bar" end -end - -helpers FooUtils, BarUtils -``` - -이 것은 모듈을 애플리케이션 클래스에 포함(include)시킨 것과 같습니다. - -### 세션(Sessions) 사용하기 - -세션은 요청 동안에 상태를 유지하기 위해 사용합니다. -세션이 활성화되면, 사용자 세션 당 세션 해시 하나씩을 갖게 됩니다. - -``` ruby -enable :sessions - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -`enable :sessions`은 실은 모든 데이터를 쿠키 속에 저장하는 것에 주의하세요. -이 방식이 바람직하지 않을 수도 있습니다. (예를 들어, 많은 양의 데이터를 -저장하게 되면 트래픽이 늘어납니다). -이런 경우에는 랙 세션 미들웨어(Rack session middleware)를 사용할 수 있습니다. -`enable :sessions`을 호출하지 **않는** 대신에, 선택한 미들웨어를 다른 -미들웨어들처럼 포함시키면 됩니다. - -``` ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -보안 강화을 위해서, 쿠키 속의 세션 데이터는 세션 시크릿(secret)으로 -사인(sign)됩니다. Sinatra는 무작위 시크릿을 생성합니다. 하지만, 이 -시크릿은 애플리케이션 시작 시마다 변경되기 때문에, 애플리케이션의 -모든 인스턴스들이 공유할 시크릿을 직접 만들 수도 있습니다. - -``` ruby -set :session_secret, 'super secret' -``` - -조금 더 세부적인 설정이 필요하다면, `sessions` 설정에서 옵션이 있는 -해시를 저장할 수도 있습니다. - -``` ruby -set :sessions, :domain => 'foo.com' -``` - -세션을 다른 foo.com의 서브도메인 들과 공유하기 원한다면, 다음에 나오는 -것 처럼 도메인 앞에 *.*을 붙이셔야 합니다. - -``` ruby -set :sessions, :domain => '.foo.com' -``` - -### 중단하기(Halting) - -필터나 라우터에서 요청을 즉각 중단하고 싶을 때 사용하합니다. - -``` ruby -halt -``` - -중단할 때 상태를 지정할 수도 있습니다. - -``` ruby -halt 410 -``` - -본문을 넣을 수도 있습니다. - -``` ruby -halt 'this will be the body' -``` - -둘 다 할 수도 있습니다. - -``` ruby -halt 401, 'go away!' -``` - -헤더를 추가할 경우에는 다음과 같이 하면 됩니다. - -``` ruby -halt 402, {'Content-Type' => 'text/plain'}, 'revenge' -``` - -당연히 `halt`와 템플릿은 같이 사용할 수 있습니다. - -``` ruby -halt erb(:error) -``` - -### 넘기기(Passing) - -라우터는 `pass`를 사용하여 다음 번 매칭되는 라우터로 처리를 넘길 수 있습니다. - -``` ruby -get '/guess/:who' do - pass unless params[:who] == 'Frank' - 'You got me!' -end - -get '/guess/*' do - 'You missed!' -end -``` - -이 때 라우터 블록에서 즉각 빠져나오게 되고 제어는 다음 번 매칭되는 라우터로 -넘어갑니다. 만약 매칭되는 라우터를 찾지 못하면, 404가 반환됩니다. - -### 다른 라우터 부르기(Triggering Another Route) - -때로는 `pass`가 아니라, 다른 라우터를 호출한 결과를 얻고 싶을 때도 -있습니다. 이럴때는 간단하게 `call`을 사용하면 됩니다. - -``` ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do -"bar" -end -``` - -위 예제의 경우, `"bar"`를 헬퍼로 옮겨 `/foo`와 `/bar` 모두에서 사용하도록 -하면 테스팅을 쉽게 하고 성능을 높일 수 있습니다. - -요청의 사본이 아닌 바로 그 인스턴스로 보내지도록 하고 싶다면, -`call` 대신 `call!`을 사용하면 됩니다. - -`call`에 대한 더 자세한 내용은 Rack 명세를 참고하세요. - -### 본문, 상태 코드 및 헤더 설정하기 - -라우터 블록의 반환값과 함께 상태 코드(status code)와 응답 본문(response body)을 -설정할수 있고 권장됩니다. 하지만, 경우에 따라서는 본문을 실행 흐름 중의 임의 -지점에서 설정해야 할때도 있습니다. 이런 경우 `body` 헬퍼 메서드를 사용하면 -됩니다. 이렇게 하면, 그 순간부터 본문에 접근할 때 그 메서드를 사용할 수가 있습니다. - -``` ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -``` - -`body`로 블록을 전달하는 것도 가능하며, 이 블록은 랙(Rack) 핸들러에 의해 -실행됩니다. (이 방법은 스트리밍을 구현할 때 사용할 수 있습니다. "값 -반환하기"를 참고하세요). - -본문와 마찬가지로, 상태코드와 헤더도 설정할 수 있습니다. - -``` ruby -get '/foo' do - status 418 - headers \ -"Allow" => "BREW, POST, GET, PROPFIND, WHEN", -"Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - body "I'm a tea pot!" -end -``` - -`body`처럼, `header`와 `status`도 매개변수 없이 사용하여 현재 값을 -액세스할 수 있습니다. - -### 응답 스트리밍(Streaming Responses) - -응답 본문의 일정 부분을 계속 생성하는 가운데 데이터를 내보내기 시작하고 -싶을 경우가 있습니다. 극단적인 예제로, 클라이언트가 접속을 끊기 전까지 -계속 데이터를 내보내고 싶을 경우도 있죠. 여러분만의 래퍼(wrapper)를 -만들지 않으려면 `stream` 헬퍼를 사용하면 됩니다. - -``` ruby -get '/' do - stream do |out| - out << "It's gonna be legen -\n" - sleep 0.5 - out << " (wait for it) \n" - sleep 1 - out << "- dary!\n" - end -end -``` - -이렇게 스트리밍 API나 [서버 발송 이벤트Server Sent -Events](http://dev.w3.org/html5/eventsource/)를 구현할 수 있고, 이 방법은 -[WebSockets](http://en.wikipedia.org/wiki/WebSocket)을 위한 기반으로 사용됩니다. -이 방법은 일부 콘텐츠가 느린 자원에 의존하는 경우에 스로풋(throughtput)을 -높이기 위해 사용되기도 합니다. - -스트리밍 동작, 특히 동시 요청의 수는 애플리케이션을 서빙하는 웹서버에 크게 -의존합니다. WEBRick서버 같은 일부의 경우 아예 스트리밍을 지원하지 조차 않습니다. -만약 서버가 스트리밍을 지원하지 않는다면, 본문은 `stream` 으로 전달된 블록이 -수행을 마친 후에 한꺼번에 반환됩니다. 이런 한번에 쏘는 샷건같은 방식으로는 -스트리밍은 움직이지 않습니다. - -선택적 매개변수 `keep_open`이 설정되어 있다면, 스트림 객체에서 `close`를 -호출하지 않을 것이고, 나중에 실행 흐름 상의 어느 시점에서 스트림을 닫을 수 -있습니다. 이 옵션은 Thin과 Rainbow 같은 이벤트 기반 서버에서만 작동하고 -다른 서버들은 여전히 스트림을 닫습니다. - -``` ruby -# long polling - -set :server, :thin -connections = [] - -get '/subscribe' do - # register a client's interest in server events - stream(:keep_open) { |out| connections << out } - - # purge dead connections - connections.reject!(&:closed?) - - # acknowledge - "subscribed" -end - -post '/message' do - connections.each do |out| - # notify client that a new message has arrived - out << params[:message] << "\n" - - # indicate client to connect again - out.close - end - - # acknowledge - "message received" -end -``` - -### 로깅(Logging) - -요청 스코프(request scope) 내에서, `Logger`의 인스턴스인 `logger` -헬퍼를 사용할 수 있습니다. - -``` ruby -get '/' do - logger.info "loading data" - # ... -end -``` - -이 로거는 자동으로 Rack 핸들러에서 설정한 로그설정을 참고합니다. -만약 로깅이 비활성상태라면, 이 메서드는 더미(dummy) 객체를 반환하기 때문에, -라우터나 필터에서 이 부분에 대해 걱정할 필요는 없습니다. - -로깅은 `Sinatra::Application`에서만 기본으로 활성화되어 있음에 유의합시다. -만약 `Sinatra::Base`로부터 상속받은 경우라면 직접 활성화시켜 줘야 합니다. - -``` ruby -class MyApp < Sinatra::Base - configure :production, :development do - enable :logging - end -end -``` - -로깅 미들웨어를 사용하지 않으려면, `logging` 설정을 `nil`로 두면 됩니다. -하지만, 이 경우 주의할 것은 `logger`는 `nil`을 반환하는 것입니다. -통상적인 유스케이스는 여러분만의 로거를 사용하고자 할 경우일 것입니다. -Sinatra는 `env['rack.logger']`에서 찾은 로거를 사용할 것입니다. - -### 마임 타입(Mime Types) - -`send_file`이나 정적인 파일을 사용할 때에 Sinatra가 인식하지 못하는 -마임 타입이 있을 수 있습니다. 이 경우 `mime_type`을 사용하여 파일 -확장자를 등록합니다. - -``` ruby -configure do - mime_type :foo, 'text/foo' -end -``` - -`content_type` 헬퍼로 쓸 수도 있습니다. - -``` ruby -get '/' do - content_type :foo - "foo foo foo" -end -``` - -### URL 생성하기 - -URL을 생성할때 `url` 헬퍼 메서드를 사용합니다. 예를 들어 Haml에서는 이렇게 -합니다. - -``` ruby -%a{:href => url('/foo')} foo -``` - -이것은 리버스 프록시(reverse proxies)와 Rack 라우터가 있다면 참고합니다. - -이 메서드는 `to`라는 별칭으로도 사용할 수 있습니다. (아래 예제 참조) - -### 브라우저 재지정(Browser Redirect) - -`redirect` 헬퍼 메서드를 사용하여 브라우저를 리다이렉트 시킬 수 있습니다. - -``` ruby -get '/foo' do - redirect to('/bar') -end -``` - -다른 부가적인 매개변수들은 `halt`에 전달하는 인자들과 비슷합니다. - -``` ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'wrong place, buddy' -``` - -`redirect back`을 사용하면 쉽게 사용자가 왔던 페이지로 다시 돌아가게 -할 수 있습니다. - -``` ruby -get '/foo' do - "do something" -end - -get '/bar' do - do_something - redirect back -end -``` - -리다이렉트와 함께 인자를 전달하려면, 쿼리로 붙이거나, - -``` ruby -redirect to('/bar?sum=42') -``` - -세션을 사용하면 됩니다. - -``` ruby -enable :sessions - -get '/foo' do - session[:secret] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secret] -end -``` - -### 캐시 컨트롤(Cache Control) - -헤더를 정확하게 설정하는 것은 적절한 HTTP 캐싱의 기본입니다. - -Cache-Control 헤더를 다음과 같이 간단하게 설정할 수 있습니다. - -``` ruby -get '/' do - cache_control :public - "cache it!" -end -``` - -프로 팁: 캐싱은 사전 필터에서 설정하세요. - -``` ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -``` - -`expires` 헬퍼를 사용하여 그에 상응하는 헤더를 설정한다면, -`Cache-Control`이 자동으로 설정됩니다. - -``` ruby -before do - expires 500, :public, :must_revalidate -end -``` - -캐시를 잘 사용하려면, `etag` 또는 `last_modified`의 사용을 고려해야 할 것이다. -무거운 작업을 하기 *전*에 이들 헬퍼를 호출하길 권장합니다. 이렇게 하면, -클라이언트 캐시에 현재 버전이 이미 들어 있을 경우엔 즉각 응답을 -뿌릴(flush) 것입니다. - -``` ruby -get '/article/:id' do - @article = Article.find params[:id] - last_modified @article.updated_at - etag @article.sha1 - erb :article -end -``` - -[약한 ETag](http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation)를 -사용할 수 도 있습니다. - -``` ruby -etag @article.sha1, :weak -``` - -이들 헬퍼는 어떠한 캐싱도 하지 않으며, 대신 캐시에 필요한 정보를 제공합니다. -손쉬운 리버스 프록시(reverse-proxy) 캐싱 솔루션을 찾고 있다면, -[rack-cache](https://github.com/rtomayko/rack-cache)를 써보세요. - -``` ruby -require "rack/cache" -require "sinatra" - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hello" -end -``` - -정적 파일에 `Cache-Control` 헤더 정보를 추가하려면 `:static_cache_control` -설정(아래 참조)을 쓰세요. - -RFC 2616에 따르면 If-Match 또는 If-None-Match 헤더가 `*`로 설정된 경우 요청한 -리소스(resource)가 이미 존재하느냐 여부에 따라 다르게 취급해야 한다고 되어 -있습니다. Sinatra는 (get 처럼) 안전하거나 (put 처럼) 멱등인 요청에 대한 리소스는 -이미 존재한다고 가정하지만, 다른 리소스(예를 들면 post 요청 같은)의 경우는 -새 리소스로 취급합니다. 이 행동은 `:new_resource` 옵션을 전달하여 변경할 수 있습니다. - -``` ruby -get '/create' do - etag '', :new_resource => true - Article.create - erb :new_article -end -``` - -약한 ETag를 사용하고자 한다면, `:kind`으로 전달합시다. - -``` ruby -etag '', :new_resource => true, :kind => :weak -``` - -### 파일 전송하기(Sending Files) - -파일을 전송하려면, `send_file` 헬퍼 메서드를 사용하면 됩니다. - -``` ruby -get '/' do - send_file 'foo.png' -end -``` - -이 메서드는 몇 가지 옵션을 받습니다. - -``` ruby -send_file 'foo.png', :type => :jpg -``` - -옵션들: - -
-
filename
-
응답에서의 파일명. 기본값은 실제 파일명.
- -
last_modified
-
Last-Modified 헤더값. 기본값은 파일의 mtime.
- -
type
-
사용할 컨텐츠 유형. 없으면 파일 확장자로부터 유추.
- -
disposition
-
- Content-Disposition에서 사용됨. 가능한 값들: nil (기본값), - :attachment:inline -
- -
length
-
Content-Length, 기본값은 파일 크기.
- -
status
-
- 전송할 상태 코드. 오류 페이지로 정적 파일을 전송할 경우에 유용. - - Rack 핸들러가 지원할 경우, Ruby 프로세스로부터의 스트리밍이 아닌 - 다른 수단이 사용가능함. 이 헬퍼 메서드를 사용하게 되면, Sinatra는 - 자동으로 범위 요청(range request)을 처리함. -
-
- - -### 요청 객체에 접근하기(Accessing the Request Object) - -들어오는 요청 객에는 요청 레벨(필터, 라우터, 오류 핸들러)에서 `request` -메서드를 통해 접근 가능합니다. - -``` ruby -# http://example.com/example 상에서 실행 중인 앱 -get '/foo' do - t = %w[text/css text/html application/javascript] - request.accept # ['text/html', '*/*'] - request.accept? 'text/xml' # true - request.preferred_type(t) # 'text/html' - request.body # 클라이언트로부터 전송된 요청 본문 (아래 참조) - request.scheme # "http" - request.script_name # "/example" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # request.body의 길이 - request.media_type # request.body의 미디어 유형 - request.host # "example.com" - request.get? # true (다른 동사에 대해 유사한 메서드 있음) - request.form_data? # false - request["SOME_HEADER"] # SOME_HEADER 헤더의 값 - request.referrer # 클라이언트의 리퍼러 또는 '/' - request.user_agent # 사용자 에이전트 (:agent 조건에서 사용됨) - request.cookies # 브라우저 쿠키의 해시 - request.xhr? # 이게 ajax 요청인가요? - request.url # "http://example.com/example/foo" - request.path # "/example/foo" - request.ip # 클라이언트 IP 주소 - request.secure? # false (ssl 접속인 경우 true) - request.forwarded? # true (리버스 프록시 하에서 작동 중이라면) - request.env # Rack에 의해 처리되는 로우(raw) env 해시 -end -``` - -`script_name`, `path_info`같은 일부 옵션들은 이렇게 쓸 수도 있습니다. - -``` ruby -before { request.path_info = "/" } - -get "/" do - "all requests end up here" -end -``` - -`request.body`는 IO 객체이거나 StringIO 객체입니다. - -``` ruby -post "/api" do - request.body.rewind # 누군가 이미 읽은 경우 - data = JSON.parse request.body.read - "Hello #{data['name']}!" -end -``` - -### 첨부(Attachments) - -`attachment` 헬퍼를 사용하여 응답이 브라우저에 표시하는 대신 -디스크에 저장되어야 함을 블라우저에게 알릴 수 있습니다. - -``` ruby -get '/' do - attachment - "store it!" -end -``` - -파일명을 전달할 수도 있습니다. - -``` ruby -get '/' do - attachment "info.txt" - "store it!" -end -``` - -### 날짜와 시간 다루기 - -Sinatra는 `time_for_` 헬퍼 메서드를 제공합니다. 이 메서드는 -주어진 값으로부터 Time 객체를 생성한다. `DateTime`, `Date` 같은 -비슷한 클래스들도 변환됩니다. - -``` ruby -get '/' do - pass if Time.now > time_for('Dec 23, 2012') - "still time" -end -``` - -이 메서드는 내부적으로 `expires` 나 `last_modified` 같은 곳에서 사용됩니다. -따라서 여러분은 애플리케이션에서 `time_for`를 오버라이딩하여 이들 메서드의 -동작을 쉽게 확장할 수 있습니다. - -``` ruby -helpers do - def time_for(value) - case value - when :yesterday then Time.now - 24*60*60 - when :tomorrow then Time.now + 24*60*60 - else super - end - end -end - -get '/' do - last_modified :yesterday - expires :tomorrow - "hello" -end -``` - -### 템플릿 파일 참조하기 - -`find_template`는 렌더링할 템플릿 파일을 찾는데 사용됩니다. - -``` ruby -find_template settings.views, 'foo', Tilt[:haml] do |file| - puts "could be #{file}" -end -``` - -이것만으로는 그렇게 유용하지는 않습니다만, 이 메서드를 오버라이드하여 여러분만의 -참조 메커니즘에서 가로채게 하면 유용해집니다. 예를 들어, 하나 이상의 뷰 디렉터리를 -사용하고자 한다면 이렇게 하세요. - -``` ruby -set :views, ['views', 'templates'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -``` - -다른 예제는 각 엔진마다 다른 디렉터리를 사용할 경우입니다. - -``` ruby -set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:default] - super(folder, name, engine, &block) - end -end -``` - -여러분은 이것을 간단하게 확장(extension)으로 만들어 다른 사람들과 공유할 수 있다! - -`find_template`은 그 파일이 실제 존재하는지 검사하지 않음에 유의합니다. -모든 가능한 경로에 대해 주어진 블록을 호출할 뿐입니다. 이것은 성능 문제는 -되지 않습니다. 왜냐하면 `render`는 파일이 발견되는 즉시 `break`하기 때문입니다. -또한, 템플릿 위치(그리고 콘텐츠)는 개발 모드에서 실행 중이 아니라면 캐시될 것입니다. -정말로 멋진 메세드를 작성하고 싶다면 이 점을 명심하세요. - -## 설정(Configuration) - -모든 환경에서, 시작될 때, 한번만 실행되게 하려면 이렇게 하면 됩니다. - -``` ruby -configure do - # 옵션 하나 설정 - set :option, 'value' - - # 여러 옵션 설정 - set :a => 1, :b => 2 - - # `set :option, true`와 동일 - enable :option - - # `set :option, false`와 동일 - disable :option - - # 블록으로 동적인 설정을 할 수도 있음 - set(:css_dir) { File.join(views, 'css') } -end -``` - -환경(RACK_ENV 환경 변수)이 `:production`일 때만 실행되게 하려면 이렇게 하면 됩니다. - -``` ruby -configure :production do - ... -end -``` - -환경이 `:production` 또는 `:test`일 때 실행되게 하려면 이렇게 하면 됩니다. - -``` ruby -configure :production, :test do - ... -end -``` - -이 옵션들은 `settings`를 통해 접근 가능합니다. - -``` ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -``` - -### 공격 방어 설정하기(Configuring attack protection) - -Sinatra는 [Rack::Protection](https://github.com/rkh/rack-protection#readme)을 사용하여 -일반적이고 일어날 수 있는 공격에 대비합니다. 이 모듈은 간단하게 비활성시킬 수 있습니다. -(하지만 애플리케이션에 엄청나게 많은 취약성을 야기합니다.) - -``` ruby -disable :protection -``` - -하나의 방어층만 스킵하려면, 옵션 해시에 `protection`을 설정하면 됩니다. - -``` ruby -set :protection, :except => :path_traversal -``` - -배열로 넘김으로써 방어층 여러 개를 비활성화할 수 있습니다. - -``` ruby -set :protection, :except => [:path_traversal, :session_hijacking] -``` - -기본적으로 `:sessions`가 활성 중일 때만 Sinatra는 방어층을 설정합니다. -때로는 자신만의 세션을 설정할 때도 있습니다. 이런 경우 `:session` 옵션을 -넘겨줌으로써 세션을 기반으로한 방어층을 설정 할 수 있습니다. - -``` ruby -use Rack::Session::Pool -set :protection, :session => true -``` - -### 가능한 설정들(Available Settings) - -
-
absolute_redirects
-
- 만약 비활성이면, Sinatra는 상대경로 리다이렉트를 허용할 것이지만, - 이렇게 되면 Sinatra는 더 이상 오직 절대경로 리다이렉트만 허용하고 있는 - RFC 2616(HTTP 1.1)에 위배됨. -
-
- 적정하게 설정되지 않은 리버스 프록시 하에서 앱을 실행 중이라면 활성화시킬 것. - rul 헬퍼는, 만약 두 번째 매개변수로 false를 전달하지만 않는다면, - 여전히 절대경로 URL을 생성할 것임에 유의. -
-
기본값은 비활성.
- -
add_charsets
-
- content_type가 문자셋 정보에 자동으로 추가하게 될 마임(mime) 타입. - 이 옵션은 오버라이딩하지 말고 추가해야 함. - settings.add_charsets << "application/foobar" -
- -
app_file
-
- 메인 애플리케이션 파일의 경로. 프로젝트 루트, 뷰, public 폴더, - 인라인 템플릿을 파악할 때 사용됨. -
- -
bind
-
바인드할 IP 주소(기본값: 0.0.0.0 이나 `environment`가 개발로 설정 되어있으면 localhost). 오직 빌트인(built-in) 서버에서만 사용됨.
- -
default_encoding
-
인코딩을 알 수 없을 때 인코딩(기본값은 "utf-8").
- -
dump_errors
-
로그안의 에러 출력.
- -
environment
-
- 현재 환경, 기본값은 ENV['RACK_ENV'] ENV에 없을 경우엔 "development". -
- -
logging
-
로거(logger) 사용.
- -
lock
-
- Ruby 프로세스 당 요청을 동시에 할 경우에만 매 요청에 걸쳐 잠금(lock)을 설정. -
-
앱이 스레드에 안전(thread-safe)하지 않으면 활성화시킬 것. 기본값은 비활성.
- -
method_override
-
- put/delete를 지원하지 않는 브라우저에서 put/delete 폼을 허용하는 - _method 꼼수 사용. -
- -
port
-
접속 포트. 빌트인 서버에서만 사용됨.
- -
prefixed_redirects
-
- 절대경로가 주어지지 않은 리다이렉트에 request.script_name를 - 삽입할지 여부를 결정. 활성화 하면 redirect '/foo'는 - redirect to('/foo')처럼 동작. 기본값은 비활성. -
- -
protection
-
웹 공격 방어를 활성화시킬 건지 여부. 위의 보안 섹션 참조.
- -
public_dir
-
public_folder의 별칭. 밑을 참조.
- -
public_folder
-
- public 파일이 제공될 폴더의 경로. - static 파일 제공이 활성화된 경우만 사용됨(아래 static참조). - 만약 설정이 없으면 app_file로부터 유추됨. -
- -
reload_templates
-
- 요청 간에 템플릿을 리로드(reload)할 건지 여부. 개발 모드에서는 활성됨. -
- -
root
-
- 프로젝트 루트 디렉터리 경로. 설정이 없으면 app_file 설정으로부터 유추됨. -
- -
raise_errors
-
- 예외 발생(애플리케이션은 중단됨). - 기본값은 environment"test"인 경우는 활성, 그렇지 않으면 비활성. -
- -
run
-
- 활성화되면, Sinatra가 웹서버의 시작을 핸들링. - rackup 또는 다른 도구를 사용하는 경우라면 활성화시키지 말 것. -
- -
running
-
빌트인 서버가 실행 중인가? 이 설정은 변경하지 말 것!
- -
server
-
- 빌트인 서버로 사용할 서버 또는 서버 목록. - 기본값은 루비구현에 따라 다르며 순서는 우선순위를 의미. -
- -
sessions
-
- Rack::Session::Cookie를 사용한 쿠키 기반 세션 활성화. - 보다 자세한 정보는 '세션 사용하기' 참조. -
- -
show_exceptions
-
- 예외 발생 시에 브라우저에 스택 추적을 보임. - 기본값은 environment"development"인 - 경우는 활성, 나머지는 비활성. -
-
- :after_handler를 설정함으로써 브라우저에서 - 스택 트레이스를 보여주기 전에 앱에 특화된 에러 핸들링을 - 할 수도 있음. -
- -
static
-
Sinatra가 정적(static) 파일을 핸들링할 지 여부를 설정.
-
이 기능이 가능한 서버를 사용하는 경우라면 비활성시킬 것.
-
비활성시키면 성능이 올라감.
-
- 기본값은 전통적 방식에서는 활성, 모듈 앱에서는 비활성. -
- -
static_cache_control
-
- Sinatra가 정적 파일을 제공하는 경우, 응답에 Cache-Control 헤더를 - 추가할 때 설정. cache_control 헬퍼를 사용. - 기본값은 비활성. -
-
- 여러 값을 설정할 경우는 명시적으로 배열을 사용할 것: - set :static_cache_control, [:public, :max_age => 300] -
- -
threaded
-
- true로 설정하면, Thin이 요청을 처리하는데 있어 - EventMachine.defer를 사용하도록 함. -
- -
views
-
- 뷰 폴더 경로. 설정하지 않은 경우 app_file로부터 유추됨. -
- -
x_cascade
-
- 라우트를 찾지못했을 때의 X-Cascade 해더를 설정여부. - 기본값은 true -
-
- - -## 환경(Environments) - -3가지의 미리 정의된 `environments` `"development"`, `"production"`, `"test"` -가 있습니다. 환경은 `RACK_ENV` 환경 변수를 통해서도 설정됩니다. 기본값은 -`"development"`입니다. `"development"` 모드에서는 모든 템플릿들은 요청 간에 -리로드됩니다. 또, `"development"` 모드에서는 특별한 `not_found` 와 `error` -핸들러가 브라우저에서 스택 트레이스를 볼 수 있게합니다. -`"production"`과 `"test"`에서는 기본적으로 템플릿은 캐시됩니다. - -다른 환경으로 실행시키려면 `RACK_ENV` 환경 변수를 사용하세요. - -``` shell -RACK_ENV=production ruby my_app.rb -``` - -현재 설정된 환경이 무엇인지 검사하기 위해서는 준비된 `development?`, `test?`, -`production?` 메서드를 사용할 수 있습니다. - -``` ruby -get '/' do - if settings.development? - "development!" - else - "not development!" - end -end -``` - -## 에러 처리(Error Handling) - -예외 핸들러는 라우터 및 사전 필터와 동일한 맥락에서 실행됩니다. -이 말인즉, `haml`, `erb`, `halt`같은 이들이 제공하는 모든 것들을 사용할 수 -있다는 뜻입니다. - -### 찾을 수 없음(Not Found) - -`Sinatra::NotFound` 예외가 발생하거나 또는 응답의 상태 코드가 404라면, -`not_found` 핸들러가 호출됩니다. - -``` ruby -not_found do - '아무 곳에도 찾을 수 없습니다.' -end -``` - -### 에러 - -`error` 핸들러는 라우터 또는 필터에서 뭐든 오류가 발생할 경우에 호출됩니다. -예외 객체는 Rack 변수 `sinatra.error`로부터 얻을 수 있습니다. - -``` ruby -error do - '고약한 오류가 발생했군요 - ' + env['sinatra.error'].name -end -``` - -사용자 정의 오류는 이렇게 정의한다. - -``` ruby -error MyCustomError do - '무슨 일이 생겼나면요...' + env['sinatra.error'].message -end -``` - -그런 다음, 이 오류가 발생하면 이렇게 처리한다. - -``` ruby -get '/' do - raise MyCustomError, '안좋은 일' -end -``` - -결과는 이렇습니다. - -``` -무슨 일이 생겼냐면요... 안좋은 일 -``` - -상태 코드에 대해 오류 핸들러를 설치할 수도 있습니다. - -``` ruby -error 403 do - '액세스가 금지됨' -end - -get '/secret' do - 403 -end -``` - -범위로 지정할 수도 있습니다. - -``` ruby -error 400..510 do - '어이쿠' -end -``` - -Sinatra는 개발 환경에서 동작할 때 브라우저에 괜찮은 스택 트레이스와 추가적인 -디버그 정보를 보여주기 위해 특별한 `not_found` 와 `error` 핸들러를 설치합니다. - -## Rack 미들웨어(Rack Middleware) - -Sinatra는 [Rack](http://rack.rubyforge.org/) 위에서 동작하며, Rack은 루비 웹 -프레임워크를 위한 최소한의 표준 인터페이스입니다. Rack이 애플리케이션 개발자들에게 -제공하는 가장 흥미로운 기능은 "미들웨어(middleware)"에 대한 지원입니다. -여기서 미들웨어란 서버와 여러분의 애플리케이션 사이에 위치하면서 HTTP 요청/응답을 -모니터링하거나/조작함으로써 다양한 유형의 공통 기능을 제공하는 컴포넌트입니다. - -Sinatra는 톱레벨의 `use` 메서드를 사용하여 Rack 미들웨어의 파이프라인을 만드는 일을 -식은 죽 먹기로 만듭니다. - -``` ruby -require 'sinatra' -require 'my_custom_middleware' - -use Rack::Lint -use MyCustomMiddleware - -get '/hello' do - 'Hello World' -end -``` - -`use`문법은 [Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html]) DSL -(rackup 파일에서 가장 많이 사용)에서 정의한 것과 동일합니다. 예를 들어, `use` 메서드는 -블록이나 여러 개의/가변적인 인자도 받을 수 있습니다. - -``` ruby -use Rack::Auth::Basic do |username, password| - username == 'admin' && password == 'secret' -end -``` - -Rack은 로깅, 디버깅, URL 라우팅, 인증, 그리고 세센 핸들링을 위한 다양한 표준 -미들웨어로 분산되어 있습니다. Sinatra는 설정에 기반하여 이들 컴포넌트들 중 -많은 것들을 자동으로 사용하며, 따라서 여러분은 일반적으로는 `use`를 명시적으로 -사용할 필요가 없을 것입니다. - -[rack](https://github.com/rack/rack/tree/master/lib/rack), -[rack-contrib](https://github.com/rack/rack-contrib#readme), -[Rack wiki](https://github.com/rack/rack/wiki/List-of-Middleware) -에서 유용한 미들웨어들을 찾을 수 있습니다. - -## 테스팅(Testing) - -Sinatra 테스트는 많은 Rack 기반 테스팅 라이브러리, 프레임워크를 사용하여 작성가능합니다. -그 중 [Rack::Test](http://rdoc.info/github/brynary/rack-test/master/frames)를 권장합니다. - -``` ruby -require 'my_sinatra_app' -require 'test/unit' -require 'rack/test' - -class MyAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_my_default - get '/' - assert_equal 'Hello World!', last_response.body - end - - def test_with_params - get '/meet', :name => 'Frank' - assert_equal 'Hello Frank!', last_response.body - end - - def test_with_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "You're using Songbird!", last_response.body - end -end -``` - -주의: Sinatra를 모듈러 방식으로 사용한다면, `Sinatra::Application` -를 앱에서 사용하는 클래스 이름으로 바꾸세요. - -## Sinatra::Base - 미들웨어(Middleware), 라이브러리(Libraries), 그리고 모듈 앱(Modular Apps) - -톱레벨에서 앱을 정의하는 것은 마이크로 앱(micro-app) 수준에서는 잘 동작하지만, -Rack 미들웨어나, Rails 메탈(metal) 또는 서버 컴포넌트를 갖는 간단한 라이브러리, -또는 더 나아가 Sinatra 익스텐션(extension) 같은 재사용 가능한 컴포넌트들을 구축할 -경우에는 심각한 약점이 있습니다. 톱레벨은 마이크로 앱 스타일의 설정을 가정하는 것 -입니다. (즉, 하나의 단일 애플리케이션 파일과 `./public` 및 `./views` 디렉터리, -로깅, 예외 상세 페이지 등등). 이 곳에서 `Sinatra::Base`가 필요합니다. - -``` ruby -require 'sinatra/base' - -class MyApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Hello world!' - end -end -``` - -`Sinatra::Base` 서브클래스에서 사용가능한 메서드들은 톱레벨 DSL로 접근 가능한 것들과 -동일합니다. 대부분의 톱레벨 앱들은 다음 두 가지만 수정하면 `Sinatra::Base` 컴포넌트로 -변환 가능합니다. - -* 파일은 `sinatra`가 아닌 `sinatra/base`를 require해야 합니다. - 그렇지 않으면 모든 Sinatra의 DSL 메서드들이 메인 네임스페이스에 불러지게 - 됩니다. -* 앱의 라우터, 예외 핸들러, 필터, 옵션은 `Sinatra::Base`의 서브클래스에 두어야 - 합니다. - -`Sinatra::Base`는 백지상태(blank slate)입니다. 빌트인 서버를 비롯한 대부분의 옵션들이 -기본값으로 꺼져 있습니다. 가능한 옵션들과 그 작동에 대한 상세는 [옵션과 -설정](http://sinatra.github.com/configuration.html)을 참조하세요. - -### 모듈(Modular) vs. 전통적 방식(Classic Style) - -일반적인 믿음과는 반대로, 전통적 방식에 잘못된 부분은 없습니다. 여러분 애플리케이션에 -맞다면, 모듈 애플리케이션으로 전환할 필요는 없습니다. - -모듈 방식이 아닌 전통적 방식을 사용할 경우 생기는 주된 단점은 루비 프로세스 당 -하나의 Sinatra 애플리케이션만 사용할 수 있다는 점입니다. 만약 하나 이상을 사용할 -계획이라면 모듈 방식으로 전환하세요. 모듈 방식과 전통적 방식을 섞어쓰지 못할 -이유는 없습니다. - -방식을 전환할 경우에는, 기본값 설정의 미묘한 차이에 유의해야 합니다. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
설정전통적 방식모듈
app_filesinatra를 로딩하는 파일Sinatra::Base를 서브클래싱한 파일
run$0 == app_filefalse
logging truefalse
method_overridetruefalse
inline_templatestruefalse
statictruefalse
- -### 모듈 애플리케이션(Modular Application) 제공하기 - -모듈 앱을 시작하는 두 가지 일반적인 옵션이 있습니다. -`run!`으로 능동적으로 시작하는 방법은 이렇습니다. - -``` ruby -# my_app.rb -require 'sinatra/base' - -class MyApp < Sinatra::Base - # ... 여기에 앱 코드가 온다 ... - - # 루비 파일이 직접 실행될 경우에 서버를 시작 - run! if app_file == $0 -end -``` - -이렇게 시작할 수도 있습니다. - -``` shell -ruby my_app.rb -``` - -`config.ru`와 함께 사용할수도 있습니다. 이 경우는 어떠한 Rack 핸들러도 사용할 수 있도록 -허용 합다. - -``` ruby -# config.ru -require './my_app' -run MyApp -``` - -실행은 이렇게 합니다. - -``` shell -rackup -p 4567 -``` - -### config.ru로 전통적 방식의 애플리케이션 사용하기 - -앱 파일을 다음과 같이 작성합니다. - -``` ruby -# app.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -대응하는 `config.ru`는 다음과 같이 작성합니다. - -``` ruby -require './app' -run Sinatra::Application -``` - -### 언제 config.ru를 사용할까? - -`config.ru`는 다음 경우에 권장 됩니다. - -* 다른 Rack 핸들러(Passenger, Unicorn, Heroku, ...)로 배포하고자 할 때. -* 하나 이상의 `Sinatra::Base` 서브클래스를 사용하고자 할 때. -* Sinatra를 최종점(endpoint)이 아니라, 오로지 미들웨어로만 사용하고자 할 때. - -**모듈 방식으로 전환했다는 이유만으로 `config.ru`로 전환할 필요는 없으며, -또한 `config.ru`를 사용한다고 해서 모듈 방식을 사용해야 하는 것도 아닙니다.** - -### Sinatra를 미들웨어로 사용하기 - -Sinatra에서 다른 Rack 미들웨어를 사용할 수 있을 뿐 아니라, -어떤 Sinatra 애플리케이션에서도 순차로 어떠한 Rack 종착점 앞에 미들웨어로 -추가될 수 있습니다. 이 종착점은 다른 Sinatra 애플리케이션이 될 수도 있고, -또는 Rack 기반의 어떠한 애플리케이션(Rails/Ramaze/Camping/...)이 될 수도 -있습니다. - -``` ruby -require 'sinatra/base' - -class LoginScreen < Sinatra::Base - enable :sessions - - get('/login') { haml :login } - - post('/login') do - if params[:name] == 'admin' && params[:password] == 'admin' - session['user_name'] = params[:name] - else - redirect '/login' - end - end -end - -class MyApp < Sinatra::Base - # 미들웨어는 사전 필터보다 앞서 실행됨 - use LoginScreen - - before do -unless session['user_name'] - halt "접근 거부됨, 로그인 하세요." -end - end - - get('/') { "Hello #{session['user_name']}." } -end -``` - -### 동적인 애플리케이션 생성(Dynamic Application Creation) - -어떤 상수에 할당하지 않고 런타임에서 새 애플리케이션들을 생성하려면, -`Sinatra.new`를 쓰면 됩니다. - -``` ruby -require 'sinatra/base' -my_app = Sinatra.new { get('/') { "hi" } } -my_app.run! -``` - -선택적 인자로 상속할 애플리케이션을 받을 수 있습니다. - -``` ruby -# config.ru -require 'sinatra/base' - -controller = Sinatra.new do - enable :logging - helpers MyHelpers -end - -map('/a') do - run Sinatra.new(controller) { get('/') { 'a' } } -end - -map('/b') do - run Sinatra.new(controller) { get('/') { 'b' } } -end -``` - -이 방법은 Sintra 익스텐션을 테스팅하거나 또는 여러분의 라이브러리에서 Sinatra를 -사용할 경우에 특히 유용합니다. - -이 방법은 Sinatra를 미들웨어로 사용하는 것을 아주 쉽게 만들어 주기도 합니다. - -``` ruby -require 'sinatra/base' - -use Sinatra do - get('/') { ... } -end - -run RailsProject::Application -``` - -## 범위(Scopes)와 바인딩(Binding) - -현재 어느 범위에 있느냐가 어떤 메서드와 변수를 사용할 수 있는지를 결정합니다. - -### 애플리케이션/클래스 범위 - -모든 Sinatra 애플리케이션은 `Sinatra::Base`의 서브클래스에 대응됩니다. -만약 톱레벨 DSL (`require 'sinatra'`)을 사용한다면, 이 클래스는 -`Sinatra::Application`이며, 그렇지 않을 경우라면 여러분이 명시적으로 생성한 -그 서브클래스가 됩니다. 클래스 레벨에서는 `get` 이나 `before` 같은 메서드들을 -가지나, `request` 객체나 `session` 에는 접근할 수 없습니다. 왜냐면 모든 요청에 -대해 애플리케이션 클래스는 오직 하나이기 때문입니다. - -`set`으로 생성한 옵션들은 클래스 레벨의 메서드들입니다. - -``` ruby -class MyApp < Sinatra::Base - # 저기요, 저는 애플리케이션 범위에 있다구요! - set :foo, 42 - foo # => 42 - - get '/foo' do - # 저기요, 전 이제 더 이상 애플리케이션 범위 속에 있지 않아요! - end -end -``` - -애플리케이션 범위에는 이런 것들이 있습니다. - -* 애플리케이션 클래스 본문 -* 확장으로 정의된 메서드 -* `helpers`로 전달된 블록 -* `set`의 값으로 사용된 Procs/blocks -* `Sinatra.new`로 전달된 블록 - -범위 객체 (클래스)는 다음과 같이 접근할 수 있습니다. - -* configure 블록으로 전달된 객체를 통해(`configure { |c| ... }`) -* 요청 범위 내에서 `settings` - -### 요청/인스턴스 범위 - -매 요청마다, 애플리케이션 클래스의 새 인스턴스가 생성되고 모든 핸들러 블록은 -그 범위 내에서 실행됩니다. 범위 내에서 여러분은 `request` 와 `session` 객체에 -접근하거나 `erb` 나 `haml` 같은 렌더링 메서드를 호출할 수 있습니다. 요청 범위 -내에서 `settings` 헬퍼를 통해 애플리케이션 범위에 접근 가능합니다. - -``` ruby -class MyApp < Sinatra::Base - # 이봐요, 전 애플리케이션 범위에 있다구요! - get '/define_route/:name' do - # '/define_route/:name'의 요청 범위 - @value = 42 - - settings.get("/#{params[:name]}") do - # "/#{params[:name]}"의 요청 범위 - @value # => nil (동일한 요청이 아님) - end - - "라우터가 정의됨!" - end -end -``` - -요청 범위에는 이런 것들이 있습니다. - -* get/head/post/put/delete/options 블록 -* before/after 필터 -* 헬퍼(helper) 메서드 -* 템플릿/뷰 - -### 위임 범위(Delegation Scope) - -위임 범위(delegation scope)는 메서드를 단순히 클래스 범위로 보냅니다(forward). -하지만 클래스 바인딩을 갖지 않기에 완전히 클래스 범위처럼 동작하지는 않습니다. -오직 명시적으로 위임(delegation) 표시된 메서드들만 사용 가능하고, -또한 클래스 범위와 변수/상태를 공유하지 않습니다 (유의: `self`가 다름). -`Sinatra::Delegator.delegate :method_name`을 호출하여 메서드 위임을 명시적으로 -추가할 수 있습니다. - -위임 범위에는 이런 것들이 있습니다. - -* 톱레벨 바인딩, `require "sinatra"`를 한 경우 -* `Sinatra::Delegator` 믹스인으로 확장된 객체 - -직접 코드를 살펴보길 바랍니다. -[Sinatra::Delegator 믹스인](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633) -은 [메인 객체를 확장한 것](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30) 입니다. - -## 명령행(Command Line) - -Sinatra 애플리케이션은 직접 실행할 수 있습니다. - -``` shell -ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER] -``` - -옵션들은 다음과 같습니다. - -``` --h # 도움말 --p # 포트 설정 (기본값은 4567) --o # 호스트 설정 (기본값은 0.0.0.0) --e # 환경 설정 (기본값은 development) --s # rack 서버/핸들러 지정 (기본값은 thin) --x # mutex 잠금 켜기 (기본값은 off) -``` - -## 요구사항(Requirement) - -다음의 루비 버전은 공식적으로 지원됩니다. -
-
Ruby 1.8.7
-
- 1.8.7은 완전하게 지원되지만, 꼭 그래야할 특별한 이유가 없다면, - 1.9.2로 업그레이드하거나 또는 JRuby나 Rubinius로 전환할 것을 권장합니다. - 1.8.7에 대한 지원은 Sinatra 2.0 이전에는 중단되지 않을 것입니다. - Ruby 1.8.6은 더이상 지원하지 않습니다. -
- -
Ruby 1.9.2
-
- 1.9.2는 완전하게 지원됩니다. 1.9.2p0은, Sinatra를 실행했을 때 세그먼트 오류가 - 발생할수 있으므로 쓰지 마세요. 공식 지원은 Sinatra 1.5 이전에는 중단되지 않을 - 것입니다. -
- -
Ruby 1.9.3
-
- 1.9.3은 완전하게 지원되고 권장합니다. 이전 버전에서 1.9.3으로 전환할 경우 모든 - 세션이 무효화되므로 주의하세요. 1.9.3에 대한 지원은 Sinatra 2.0 이전에는 - 중단되지 않을 것입니다. -
- -
Ruby 2.0.0
-
- 2.0.0은 완전하게 지원되고 권장합니다. 현재 공식 지원 중지 계획은 없습니다. -
- -
Rubinius
-
- Rubinius는 공식적으로 지원됩니다. (Rubinius >= 2.x) - gem install puma를 권장합니다. -
- -
JRuby
-
- JRuby의 마지막 안정판은 공식적으로 지원됩니다. C 확장을 JRuby와 사용하는 - 것은 권장되지 않습니다. - gem install trinidad를 권장합니다. -
-
- -새로 나오는 루비 버전도 주시하고 있습니다. - -다음 루비 구현체들은 공식적으로 지원하지 않지만 -여전히 Sinatra를 실행할 수 있는 것으로 알려져 있습니다. - -* JRuby와 Rubinius 예전 버전 -* Ruby Enterprise Edition -* MacRuby, Maglev, IronRuby -* Ruby 1.9.0 및 1.9.1 (이 버전들은 사용하지 말 것을 권합니다) - -공식적으로 지원하지 않는다는 것의 의미는 무언가가 그 플랫폼에서만 잘못되고 -지원되는 플랫폼에서는 그러지 않을 경우, 우리의 문제가 아니라 그 플랫폼의 문제로 -간주한다는 뜻입니다. - -또한 우리는 CI를 ruby-head (곧 나올 2.1.0) 브랜치에 맞춰 실행하지만, -계속해서 변하고 있기 때문에 아무 것도 보장할 수는 없습니다. -2.1.0가 완전히 지원되길 기대합시다. - -Sinatra는 선택한 루비 구현체가 지원하는 어떠한 운영체제에서도 작동해야 -합니다. - -현재 Cardinal, SmallRuby, BlueRuby 또는 1.8.7 이전의 루비 버전에서는 -Sinatra를 실행할 수 없을 것입니다. - -## 최신(The Bleeding Edge) - -Sinatra의 가장 최근 코드를 사용하고자 한다면, 애플리케이션을 마스터 브랜치에 맞춰 -실행하면 되므로 부담가지지 마세요. 하지만 덜 안정적일 것 입니다. - -주기적으로 사전배포(prerelease) 젬을 푸시하기 때문에, 최신 기능들을 얻기 위해 -다음과 같이 할 수도 있습니다. - -``` shell -gem install sinatra --pre -``` - -### Bundler를 사용하여 - -여러분 애플리케이션을 최신 Sinatra로 실행하고자 한다면, -[Bundler](http://gembundler.com/)를 사용할 것을 권장합니다. - -우선, 아직 설치하지 않았다면 bundler를 설치합니다. - -``` shell -gem install bundler -``` - -그런 다음, 프로젝트 디렉터리에서, `Gemfile`을 만듭니다. - -``` ruby -source 'https://rubygems.org' -gem 'sinatra', :github => "sinatra/sinatra" - -# 다른 의존관계들 -gem 'haml' # 예를 들어, haml을 사용한다면 -gem 'activerecord', '~> 3.0' # 아마도 ActiveRecord 3.x도 필요할 것 -``` - -`Gemfile`안에 애플리케이션의 모든 의존성을 적어야 합니다. -하지만, Sinatra가 직접적인 의존관계에 있는 것들(Rack과 Tilt)은 -Bundler가 자동으로 찾아서 추가할 것입니다. - -이제 앱을 실행할 수 있습니다. - -``` shell -bundle exec ruby myapp.rb -``` - -### 직접 하기(Roll Your Own) - -로컬 클론(clone)을 생성한 다음 `$LOAD_PATH`에 `sinatra/lib` 디렉터리를 주고 -여러분 앱을 실행합니다. - -``` shell -cd myapp -git clone git://github.com/sinatra/sinatra.git -ruby -I sinatra/lib myapp.rb -``` - -이후에 Sinatra 소스를 업데이트하려면 이렇게 하세요. - -``` shell -cd myapp/sinatra -git pull -``` - -### 전역으로 설치(Install Globally) - -젬을 직접 빌드할 수 있습니다. - -``` shell -git clone git://github.com/sinatra/sinatra.git -cd sinatra -rake sinatra.gemspec -rake install -``` - -만약 젬을 루트로 설치한다면, 마지막 단계는 다음과 같이 해야 합니다. - -``` shell -sudo rake install -``` - -## 버저닝(Versioning) - -Sinatra는 [시맨틱 버저닝Semantic Versioning](http://semver.org/) -[(번역)](http://surpreem.com/archives/380)의 SemVer, -SemVerTag를 준수합니다. - -## 더 읽을 거리(Further Reading) - -* [프로젝트 웹사이트](http://www.sinatrarb.com/) - 추가 문서들, 뉴스, - 그리고 다른 리소스들에 대한 링크. -* [기여하기](http://www.sinatrarb.com/contributing) - 버그를 찾았나요? - 도움이 필요한가요? 패치를 하셨나요? -* [이슈 트래커](http://github.com/sinatra/sinatra/issues) -* [트위터](http://twitter.com/sinatra) -* [메일링 리스트](http://groups.google.com/group/sinatrarb/topics) -* IRC: [#sinatra](irc://chat.freenode.net/#sinatra) http://freenode.net -* [Sinatra Book](http://sinatra-book.gittr.com) Cookbook 튜토리얼 -* [Sinatra Recipes](http://recipes.sinatrarb.com/) 커뮤니티가 만드는 레시피 -* http://rubydoc.info에 있는 [최종 릴리스](http://rubydoc.info/gems/sinatra) - 또는 [current HEAD](http://rubydoc.info/github/sinatra/sinatra)에 대한 API 문서 -* [CI server](http://travis-ci.org/sinatra/sinatra) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.md deleted file mode 100644 index f23dcc0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.md +++ /dev/null @@ -1,2980 +0,0 @@ -# Sinatra - -Sinatra is a [DSL](http://en.wikipedia.org/wiki/Domain-specific_language) for -quickly creating web applications in Ruby with minimal effort: - -``` ruby -# myapp.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -Install the gem: - -``` shell -gem install sinatra -``` - -And run with: - -``` shell -ruby myapp.rb -``` - -View at: http://localhost:4567 - -It is recommended to also run `gem install thin`, which Sinatra will -pick up if available. - -## Table of Contents - -* [Sinatra](#sinatra) - * [Table of Contents](#table-of-contents) - * [Routes](#routes) - * [Conditions](#conditions) - * [Return Values](#return-values) - * [Custom Route Matchers](#custom-route-matchers) - * [Static Files](#static-files) - * [Views / Templates](#views--templates) - * [Literal Templates](#literal-templates) - * [Available Template Languages](#available-template-languages) - * [Haml Templates](#haml-templates) - * [Erb Templates](#erb-templates) - * [Builder Templates](#builder-templates) - * [Nokogiri Templates](#nokogiri-templates) - * [Sass Templates](#sass-templates) - * [SCSS Templates](#scss-templates) - * [Less Templates](#less-templates) - * [Liquid Templates](#liquid-templates) - * [Markdown Templates](#markdown-templates) - * [Textile Templates](#textile-templates) - * [RDoc Templates](#rdoc-templates) - * [AsciiDoc Templates](#asciidoc-templates) - * [Radius Templates](#radius-templates) - * [Markaby Templates](#markaby-templates) - * [RABL Templates](#rabl-templates) - * [Slim Templates](#slim-templates) - * [Creole Templates](#creole-templates) - * [MediaWiki Templates](#mediawiki-templates) - * [CoffeeScript Templates](#coffeescript-templates) - * [Stylus Templates](#stylus-templates) - * [Yajl Templates](#yajl-templates) - * [WLang Templates](#wlang-templates) - * [Accessing Variables in Templates](#accessing-variables-in-templates) - * [Templates with `yield` and nested layouts](#templates-with-yield-and-nested-layouts) - * [Inline Templates](#inline-templates) - * [Named Templates](#named-templates) - * [Associating File Extensions](#associating-file-extensions) - * [Adding Your Own Template Engine](#adding-your-own-template-engine) - * [Filters](#filters) - * [Helpers](#helpers) - * [Using Sessions](#using-sessions) - * [Halting](#halting) - * [Passing](#passing) - * [Triggering Another Route](#triggering-another-route) - * [Setting Body, Status Code and Headers](#setting-body-status-code-and-headers) - * [Streaming Responses](#streaming-responses) - * [Logging](#logging) - * [Mime Types](#mime-types) - * [Generating URLs](#generating-urls) - * [Browser Redirect](#browser-redirect) - * [Cache Control](#cache-control) - * [Sending Files](#sending-files) - * [Accessing the Request Object](#accessing-the-request-object) - * [Attachments](#attachments) - * [Dealing with Date and Time](#dealing-with-date-and-time) - * [Looking Up Template Files](#looking-up-template-files) - * [Configuration](#configuration) - * [Configuring attack protection](#configuring-attack-protection) - * [Available Settings](#available-settings) - * [Environments](#environments) - * [Error Handling](#error-handling) - * [Not Found](#not-found) - * [Error](#error) - * [Rack Middleware](#rack-middleware) - * [Testing](#testing) - * [Sinatra::Base - Middleware, Libraries, and Modular Apps](#sinatrabase---middleware-libraries-and-modular-apps) - * [Modular vs. Classic Style](#modular-vs-classic-style) - * [Serving a Modular Application](#serving-a-modular-application) - * [Using a Classic Style Application with a config.ru](#using-a-classic-style-application-with-a-configru) - * [When to use a config.ru?](#when-to-use-a-configru) - * [Using Sinatra as Middleware](#using-sinatra-as-middleware) - * [Dynamic Application Creation](#dynamic-application-creation) - * [Scopes and Binding](#scopes-and-binding) - * [Application/Class Scope](#applicationclass-scope) - * [Request/Instance Scope](#requestinstance-scope) - * [Delegation Scope](#delegation-scope) - * [Command Line](#command-line) - * [Requirement](#requirement) - * [The Bleeding Edge](#the-bleeding-edge) - * [With Bundler](#with-bundler) - * [Roll Your Own](#roll-your-own) - * [Install Globally](#install-globally) - * [Versioning](#versioning) - * [Further Reading](#further-reading) - -## Routes - -In Sinatra, a route is an HTTP method paired with a URL-matching pattern. -Each route is associated with a block: - -``` ruby -get '/' do - .. show something .. -end - -post '/' do - .. create something .. -end - -put '/' do - .. replace something .. -end - -patch '/' do - .. modify something .. -end - -delete '/' do - .. annihilate something .. -end - -options '/' do - .. appease something .. -end - -link '/' do - .. affiliate something .. -end - -unlink '/' do - .. separate something .. -end -``` - -Routes are matched in the order they are defined. The first route that -matches the request is invoked. - -Route patterns may include named parameters, accessible via the -`params` hash: - -``` ruby -get '/hello/:name' do - # matches "GET /hello/foo" and "GET /hello/bar" - # params[:name] is 'foo' or 'bar' - "Hello #{params[:name]}!" -end -``` - -You can also access named parameters via block parameters: - -``` ruby -get '/hello/:name' do |n| - # matches "GET /hello/foo" and "GET /hello/bar" - # params[:name] is 'foo' or 'bar' - # n stores params[:name] - "Hello #{n}!" -end -``` - -Route patterns may also include splat (or wildcard) parameters, accessible -via the `params[:splat]` array: - -``` ruby -get '/say/*/to/*' do - # matches /say/hello/to/world - params[:splat] # => ["hello", "world"] -end - -get '/download/*.*' do - # matches /download/path/to/file.xml - params[:splat] # => ["path/to/file", "xml"] -end -``` - -Or with block parameters: - -``` ruby -get '/download/*.*' do |path, ext| - [path, ext] # => ["path/to/file", "xml"] -end -``` - -Route matching with Regular Expressions: - -``` ruby -get %r{/hello/([\w]+)} do - "Hello, #{params[:captures].first}!" -end -``` - -Or with a block parameter: - -``` ruby -get %r{/hello/([\w]+)} do |c| - "Hello, #{c}!" -end -``` - -Route patterns may have optional parameters: - -``` ruby -get '/posts.?:format?' do - # matches "GET /posts" and any extension "GET /posts.json", "GET /posts.xml" etc. -end -``` - -Routes may also utilize query parameters: - -``` ruby -get '/posts' do - # matches "GET /posts?title=foo&author=bar" - title = params[:title] - author = params[:author] - # uses title and author variables; query is optional to the /posts route -end -``` - -By the way, unless you disable the path traversal attack protection (see below), -the request path might be modified before matching against your routes. - -## Conditions - -Routes may include a variety of matching conditions, such as the user agent: - -``` ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "You're using Songbird version #{params[:agent][0]}" -end - -get '/foo' do - # Matches non-songbird browsers -end -``` - -Other available conditions are `host_name` and `provides`: - -``` ruby -get '/', :host_name => /^admin\./ do - "Admin Area, Access denied!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -You can easily define your own conditions: - -``` ruby -set(:probability) { |value| condition { rand <= value } } - -get '/win_a_car', :probability => 0.1 do - "You won!" -end - -get '/win_a_car' do - "Sorry, you lost." -end -``` - -For a condition that takes multiple values use a splat: - -``` ruby -set(:auth) do |*roles| # <- notice the splat here - condition do - unless logged_in? && roles.any? {|role| current_user.in_role? role } - redirect "/login/", 303 - end - end -end - -get "/my/account/", :auth => [:user, :admin] do - "Your Account Details" -end - -get "/only/admin/", :auth => :admin do - "Only admins are allowed here!" -end -``` - -## Return Values - -The return value of a route block determines at least the response body passed -on to the HTTP client, or at least the next middleware in the Rack stack. -Most commonly, this is a string, as in the above examples. But other values are -also accepted. - -You can return any object that would either be a valid Rack response, Rack -body object or HTTP status code: - -* An Array with three elements: `[status (Fixnum), headers (Hash), response - body (responds to #each)]` -* An Array with two elements: `[status (Fixnum), response body (responds to - #each)]` -* An object that responds to `#each` and passes nothing but strings to - the given block -* A Fixnum representing the status code - -That way we can, for instance, easily implement a streaming example: - -``` ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -You can also use the `stream` helper method (described below) to reduce boiler -plate and embed the streaming logic in the route. - -## Custom Route Matchers - -As shown above, Sinatra ships with built-in support for using String patterns -and regular expressions as route matches. However, it does not stop there. You -can easily define your own matchers: - -``` ruby -class AllButPattern - Match = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Match.new([]) - end - - def match(str) - @captures unless @except === str - end -end - -def all_but(pattern) - AllButPattern.new(pattern) -end - -get all_but("/index") do - # ... -end -``` - -Note that the above example might be over-engineered, as it can also be -expressed as: - -``` ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -Or, using negative look ahead: - -``` ruby -get %r{^(?!/index$)} do - # ... -end -``` - -## Static Files - -Static files are served from the `./public` directory. You can specify -a different location by setting the `:public_folder` option: - -``` ruby -set :public_folder, File.dirname(__FILE__) + '/static' -``` - -Note that the public directory name is not included in the URL. A file -`./public/css/style.css` is made available as -`http://example.com/css/style.css`. - -Use the `:static_cache_control` setting (see below) to add -`Cache-Control` header info. - -## Views / Templates - -Each template language is exposed via its own rendering method. These -methods simply return a string: - -``` ruby -get '/' do - erb :index -end -``` - -This renders `views/index.erb`. - -Instead of a template name, you can also just pass in the template content -directly: - -``` ruby -get '/' do - code = "<%= Time.now %>" - erb code -end -``` - -Templates take a second argument, the options hash: - -``` ruby -get '/' do - erb :index, :layout => :post -end -``` - -This will render `views/index.erb` embedded in the -`views/post.erb` (default is `views/layout.erb`, if it exists). - -Any options not understood by Sinatra will be passed on to the template -engine: - -``` ruby -get '/' do - haml :index, :format => :html5 -end -``` - -You can also set options per template language in general: - -``` ruby -set :haml, :format => :html5 - -get '/' do - haml :index -end -``` - -Options passed to the render method override options set via `set`. - -Available Options: - -
-
locals
-
- List of locals passed to the document. Handy with partials. - Example: erb "<%= foo %>", :locals => {:foo => "bar"} -
- -
default_encoding
-
- String encoding to use if uncertain. Defaults to - settings.default_encoding. -
- -
views
-
- Views folder to load templates from. Defaults to settings.views. -
- -
layout
-
- Whether to use a layout (true or false). If it's a Symbol, specifies - what template to use. Example: erb :index, :layout => !request.xhr? -
- -
content_type
-
- Content-Type the template produces. Default depends on template language. -
- -
scope
-
- Scope to render template under. Defaults to the application instance. If you - change this, instance variables and helper methods will not be available. -
- -
layout_engine
-
- Template engine to use for rendering the layout. Useful for languages that - do not support layouts otherwise. Defaults to the engine used for the - template. Example: set :rdoc, :layout_engine => :erb -
- -
layout_options
-
- Special options only used for rendering the layout. Example: - set :rdoc, :layout_options => { :views => 'views/layouts' } -
-
- -Templates are assumed to be located directly under the `./views` directory. To -use a different views directory: - -``` ruby -set :views, settings.root + '/templates' -``` - - -One important thing to remember is that you always have to reference templates -with symbols, even if they're in a subdirectory (in this case, use: -`:'subdir/template'` or `'subdir/template'.to_sym`). You must use a symbol -because otherwise rendering methods will render any strings passed to them -directly. - -### Literal Templates - -``` ruby -get '/' do - haml '%div.title Hello World' -end -``` - -Renders the template string. - -### Available Template Languages - -Some languages have multiple implementations. To specify what implementation -to use (and to be thread-safe), you should simply require it first: - -``` ruby -require 'rdiscount' # or require 'bluecloth' -get('/') { markdown :index } -``` - -#### Haml Templates - - - - - - - - - - - - - - -
Dependencyhaml
File Extension.haml
Examplehaml :index, :format => :html5
- -#### Erb Templates - - - - - - - - - - - - - - -
Dependency - erubis - or erb (included in Ruby) -
File Extensions.erb, .rhtml or .erubis (Erubis only)
Exampleerb :index
- -#### Builder Templates - - - - - - - - - - - - - - -
Dependency - builder -
File Extension.builder
Examplebuilder { |xml| xml.em "hi" }
- -It also takes a block for inline templates (see example). - -#### Nokogiri Templates - - - - - - - - - - - - - - -
Dependencynokogiri
File Extension.nokogiri
Examplenokogiri { |xml| xml.em "hi" }
- -It also takes a block for inline templates (see example). - -#### Sass Templates - - - - - - - - - - - - - - -
Dependencysass
File Extension.sass
Examplesass :stylesheet, :style => :expanded
- -#### SCSS Templates - - - - - - - - - - - - - - -
Dependencysass
File Extension.scss
Examplescss :stylesheet, :style => :expanded
- -#### Less Templates - - - - - - - - - - - - - - -
Dependencyless
File Extension.less
Exampleless :stylesheet
- -#### Liquid Templates - - - - - - - - - - - - - - -
Dependencyliquid
File Extension.liquid
Exampleliquid :index, :locals => { :key => 'value' }
- -Since you cannot call Ruby methods (except for `yield`) from a Liquid -template, you almost always want to pass locals to it. - -#### Markdown Templates - - - - - - - - - - - - - - -
Dependency - Anyone of: - RDiscount, - RedCarpet, - BlueCloth, - kramdown, - maruku -
File Extensions.markdown, .mkd and .md
Examplemarkdown :index, :layout_engine => :erb
- -It is not possible to call methods from markdown, nor to pass locals to it. -You therefore will usually use it in combination with another rendering -engine: - -``` ruby -erb :overview, :locals => { :text => markdown(:introduction) } -``` - -Note that you may also call the `markdown` method from within other templates: - -``` ruby -%h1 Hello From Haml! -%p= markdown(:greetings) -``` - -Since you cannot call Ruby from Markdown, you cannot use layouts written in -Markdown. However, it is possible to use another rendering engine for the -template than for the layout by passing the `:layout_engine` option. - -#### Textile Templates - - - - - - - - - - - - - - -
DependencyRedCloth
File Extension.textile
Exampletextile :index, :layout_engine => :erb
- -It is not possible to call methods from textile, nor to pass locals to it. You -therefore will usually use it in combination with another rendering engine: - -``` ruby -erb :overview, :locals => { :text => textile(:introduction) } -``` - -Note that you may also call the `textile` method from within other templates: - -``` ruby -%h1 Hello From Haml! -%p= textile(:greetings) -``` - -Since you cannot call Ruby from Textile, you cannot use layouts written in -Textile. However, it is possible to use another rendering engine for the -template than for the layout by passing the `:layout_engine` option. - -#### RDoc Templates - - - - - - - - - - - - - - -
DependencyRDoc
File Extension.rdoc
Examplerdoc :README, :layout_engine => :erb
- -It is not possible to call methods from rdoc, nor to pass locals to it. You -therefore will usually use it in combination with another rendering engine: - -``` ruby -erb :overview, :locals => { :text => rdoc(:introduction) } -``` - -Note that you may also call the `rdoc` method from within other templates: - -``` ruby -%h1 Hello From Haml! -%p= rdoc(:greetings) -``` - -Since you cannot call Ruby from RDoc, you cannot use layouts written in -RDoc. However, it is possible to use another rendering engine for the -template than for the layout by passing the `:layout_engine` option. - -#### AsciiDoc Templates - - - - - - - - - - - - - - -
DependencyAsciidoctor
File Extension.asciidoc, .adoc and .ad
Exampleasciidoc :README, :layout_engine => :erb
- -Since you cannot call Ruby methods directly from an AsciiDoc template, you almost -always want to pass locals to it. - -#### Radius Templates - - - - - - - - - - - - - - -
DependencyRadius
File Extension.radius
Exampleradius :index, :locals => { :key => 'value' }
- -Since you cannot call Ruby methods directly from a Radius template, you almost -always want to pass locals to it. - -#### Markaby Templates - - - - - - - - - - - - - - -
DependencyMarkaby
File Extension.mab
Examplemarkaby { h1 "Welcome!" }
- -It also takes a block for inline templates (see example). - -#### RABL Templates - - - - - - - - - - - - - - -
DependencyRabl
File Extension.rabl
Examplerabl :index
- -#### Slim Templates - - - - - - - - - - - - - - -
DependencySlim Lang
File Extension.slim
Exampleslim :index
- -#### Creole Templates - - - - - - - - - - - - - - -
DependencyCreole
File Extension.creole
Examplecreole :wiki, :layout_engine => :erb
- -It is not possible to call methods from creole, nor to pass locals to it. You -therefore will usually use it in combination with another rendering engine: - -``` ruby -erb :overview, :locals => { :text => creole(:introduction) } -``` - -Note that you may also call the `creole` method from within other templates: - -``` ruby -%h1 Hello From Haml! -%p= creole(:greetings) -``` - -Since you cannot call Ruby from Creole, you cannot use layouts written in -Creole. However, it is possible to use another rendering engine for the -template than for the layout by passing the `:layout_engine` option. - -#### MediaWiki Templates - - - - - - - - - - - - - - -
DependencyWikiCloth
File Extension.mediawiki and .mw
Examplemediawiki :wiki, :layout_engine => :erb
- -It is not possible to call methods from MediaWiki markup, nor to pass locals to it. -You therefore will usually use it in combination with another rendering engine: - -``` ruby -erb :overview, :locals => { :text => mediawiki(:introduction) } -``` - -Note that you may also call the `mediawiki` method from within other templates: - -``` ruby -%h1 Hello From Haml! -%p= mediawiki(:greetings) -``` - -Since you cannot call Ruby from MediaWiki, you cannot use layouts written in -MediaWiki. However, it is possible to use another rendering engine for the -template than for the layout by passing the `:layout_engine` option. - -#### CoffeeScript Templates - - - - - - - - - - - - - - -
Dependency - - CoffeeScript - and a - - way to execute javascript - -
File Extension.coffee
Examplecoffee :index
- -#### Stylus Templates - - - - - - - - - - - - - - -
Dependency - - Stylus - and a - - way to execute javascript - -
File Extension.styl
Examplestylus :index
- -Before being able to use Stylus templates, you need to load `stylus` and -`stylus/tilt` first: - -``` ruby -require 'sinatra' -require 'stylus' -require 'stylus/tilt' - -get '/' do - stylus :example -end -``` - -#### Yajl Templates - - - - - - - - - - - - - - -
Dependencyyajl-ruby
File Extension.yajl
Example - - yajl :index, - :locals => { :key => 'qux' }, - :callback => 'present', - :variable => 'resource' - -
- - -The template source is evaluated as a Ruby string, and the -resulting json variable is converted using `#to_json`: - -``` ruby -json = { :foo => 'bar' } -json[:baz] = key -``` - -The `:callback` and `:variable` options can be used to decorate the rendered -object: - -``` javascript -var resource = {"foo":"bar","baz":"qux"}; -present(resource); -``` - -#### WLang Templates - - - - - - - - - - - - - - -
DependencyWLang
File Extension.wlang
Examplewlang :index, :locals => { :key => 'value' }
- -Since calling ruby methods is not idiomatic in WLang, you almost always want to pass locals -to it. Layouts written in WLang and `yield` are supported, though. - -### Accessing Variables in Templates - -Templates are evaluated within the same context as route handlers. Instance -variables set in route handlers are directly accessible by templates: - -``` ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.name' -end -``` - -Or, specify an explicit Hash of local variables: - -``` ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= bar.name', :locals => { :bar => foo } -end -``` - -This is typically used when rendering templates as partials from within -other templates. - -### Templates with `yield` and nested layouts - -A layout is usually just a template that calls `yield`. -Such a template can be used either through the `:template` option as -described above, or it can be rendered with a block as follows: - -``` ruby -erb :post, :layout => false do - erb :index -end -``` - -This code is mostly equivalent to `erb :index, :layout => :post`. - -Passing blocks to rendering methods is most useful for creating nested -layouts: - -``` ruby -erb :main_layout, :layout => false do - erb :admin_layout do - erb :user - end -end -``` - -This can also be done in fewer lines of code with: - -``` ruby -erb :admin_layout, :layout => :main_layout do - erb :user -end -``` - -Currently, the following rendering methods accept a block: `erb`, `haml`, -`liquid`, `slim `, `wlang`. -Also the general `render` method accepts a block. - -### Inline Templates - -Templates may be defined at the end of the source file: - -``` ruby -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Hello world. -``` - -NOTE: Inline templates defined in the source file that requires sinatra are -automatically loaded. Call `enable :inline_templates` explicitly if you -have inline templates in other source files. - -### Named Templates - -Templates may also be defined using the top-level `template` method: - -``` ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Hello World!' -end - -get '/' do - haml :index -end -``` - -If a template named "layout" exists, it will be used each time a template -is rendered. You can individually disable layouts by passing -`:layout => false` or disable them by default via -`set :haml, :layout => false`: - -``` ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -### Associating File Extensions - -To associate a file extension with a template engine, use -`Tilt.register`. For instance, if you like to use the file extension -`tt` for Textile templates, you can do the following: - -``` ruby -Tilt.register :tt, Tilt[:textile] -``` - -### Adding Your Own Template Engine - -First, register your engine with Tilt, then create a rendering method: - -``` ruby -Tilt.register :myat, MyAwesomeTemplateEngine - -helpers do - def myat(*args) render(:myat, *args) end -end - -get '/' do - myat :index -end -``` - -Renders `./views/index.myat`. See https://github.com/rtomayko/tilt to -learn more about Tilt. - -## Filters - -Before filters are evaluated before each request within the same -context as the routes will be and can modify the request and response. Instance -variables set in filters are accessible by routes and templates: - -``` ruby -before do - @note = 'Hi!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @note #=> 'Hi!' - params[:splat] #=> 'bar/baz' -end -``` - -After filters are evaluated after each request within the same -context as the routes will be and can also modify the request and response. Instance -variables set in before filters and routes are accessible by after filters: - -``` ruby -after do - puts response.status -end -``` - -Note: Unless you use the `body` method rather than just returning a String from -the routes, the body will not yet be available in the after filter, since it is -generated later on. - -Filters optionally take a pattern, causing them to be evaluated only if the -request path matches that pattern: - -``` ruby -before '/protected/*' do - authenticate! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -``` - -Like routes, filters also take conditions: - -``` ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'example.com' do - # ... -end -``` - -## Helpers - -Use the top-level `helpers` method to define helper methods for use in -route handlers and templates: - -``` ruby -helpers do - def bar(name) - "#{name}bar" - end -end - -get '/:name' do - bar(params[:name]) -end -``` - -Alternatively, helper methods can be separately defined in a module: - -``` ruby -module FooUtils - def foo(name) "#{name}foo" end -end - -module BarUtils - def bar(name) "#{name}bar" end -end - -helpers FooUtils, BarUtils -``` - -The effect is the same as including the modules in the application class. - -### Using Sessions - -A session is used to keep state during requests. If activated, you have one -session hash per user session: - -``` ruby -enable :sessions - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -Note that `enable :sessions` actually stores all data in a cookie. This -might not always be what you want (storing lots of data will increase your -traffic, for instance). You can use any Rack session middleware: in order to -do so, do **not** call `enable :sessions`, but instead pull in your -middleware of choice as you would any other middleware: - -``` ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -To improve security, the session data in the cookie is signed with a session -secret. A random secret is generated for you by Sinatra. However, since this -secret will change with every start of your application, you might want to -set the secret yourself, so all your application instances share it: - -``` ruby -set :session_secret, 'super secret' -``` - -If you want to configure it further, you may also store a hash with options in -the `sessions` setting: - -``` ruby -set :sessions, :domain => 'foo.com' -``` - -To share your session across other apps on subdomains of foo.com, prefix the -domain with a *.* like this instead: - -``` ruby -set :sessions, :domain => '.foo.com' -``` - -### Halting - -To immediately stop a request within a filter or route use: - -``` ruby -halt -``` - -You can also specify the status when halting: - -``` ruby -halt 410 -``` - -Or the body: - -``` ruby -halt 'this will be the body' -``` - -Or both: - -``` ruby -halt 401, 'go away!' -``` - -With headers: - -``` ruby -halt 402, {'Content-Type' => 'text/plain'}, 'revenge' -``` - -It is of course possible to combine a template with `halt`: - -``` ruby -halt erb(:error) -``` - -### Passing - -A route can punt processing to the next matching route using `pass`: - -``` ruby -get '/guess/:who' do - pass unless params[:who] == 'Frank' - 'You got me!' -end - -get '/guess/*' do - 'You missed!' -end -``` - -The route block is immediately exited and control continues with the next -matching route. If no matching route is found, a 404 is returned. - -### Triggering Another Route - -Sometimes `pass` is not what you want, instead you would like to get the result -of calling another route. Simply use `call` to achieve this: - -``` ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do - "bar" -end -``` - -Note that in the example above, you would ease testing and increase performance -by simply moving `"bar"` into a helper used by both `/foo` -and `/bar`. - -If you want the request to be sent to the same application instance rather than -a duplicate, use `call!` instead of `call`. - -Check out the Rack specification if you want to learn more about `call`. - -### Setting Body, Status Code and Headers - -It is possible and recommended to set the status code and response body with the -return value of the route block. However, in some scenarios you might want to -set the body at an arbitrary point in the execution flow. You can do so with the -`body` helper method. If you do so, you can use that method from there on to -access the body: - -``` ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -``` - -It is also possible to pass a block to `body`, which will be executed by the -Rack handler (this can be used to implement streaming, see "Return Values"). - -Similar to the body, you can also set the status code and headers: - -``` ruby -get '/foo' do - status 418 - headers \ - "Allow" => "BREW, POST, GET, PROPFIND, WHEN", - "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - body "I'm a tea pot!" -end -``` - -Like `body`, `headers` and `status` with no arguments can be used to access -their current values. - -### Streaming Responses - -Sometimes you want to start sending out data while still generating parts of -the response body. In extreme examples, you want to keep sending data until -the client closes the connection. You can use the `stream` helper to avoid -creating your own wrapper: - -``` ruby -get '/' do - stream do |out| - out << "It's gonna be legen -\n" - sleep 0.5 - out << " (wait for it) \n" - sleep 1 - out << "- dary!\n" - end -end -``` - -This allows you to implement streaming APIs, -[Server Sent Events](http://dev.w3.org/html5/eventsource/), and can be used as -the basis for [WebSockets](http://en.wikipedia.org/wiki/WebSocket). It can also be -used to increase throughput if some but not all content depends on a slow -resource. - -Note that the streaming behavior, especially the number of concurrent requests, -highly depends on the web server used to serve the application. Some servers, -like WEBRick, might not even support streaming at all. If the server does not -support streaming, the body will be sent all at once after the block passed to -`stream` finishes executing. Streaming does not work at all with Shotgun. - -If the optional parameter is set to `keep_open`, it will not call `close` on -the stream object, allowing you to close it at any later point in the -execution flow. This only works on evented servers, like Thin and Rainbows. -Other servers will still close the stream: - -``` ruby -# long polling - -set :server, :thin -connections = [] - -get '/subscribe' do - # register a client's interest in server events - stream(:keep_open) { |out| connections << out } - - # purge dead connections - connections.reject!(&:closed?) - - # acknowledge - "subscribed" -end - -post '/message' do - connections.each do |out| - # notify client that a new message has arrived - out << params[:message] << "\n" - - # indicate client to connect again - out.close - end - - # acknowledge - "message received" -end -``` - -### Logging - -In the request scope, the `logger` helper exposes a `Logger` instance: - -``` ruby -get '/' do - logger.info "loading data" - # ... -end -``` - -This logger will automatically take your Rack handler's logging settings into -account. If logging is disabled, this method will return a dummy object, so -you do not have to worry about it in your routes and filters. - -Note that logging is only enabled for `Sinatra::Application` by -default, so if you inherit from `Sinatra::Base`, you probably want to -enable it yourself: - -``` ruby -class MyApp < Sinatra::Base - configure :production, :development do - enable :logging - end -end -``` - -To avoid any logging middleware to be set up, set the `logging` setting to -`nil`. However, keep in mind that `logger` will in that case return `nil`. A -common use case is when you want to set your own logger. Sinatra will use -whatever it will find in `env['rack.logger']`. - -### Mime Types - -When using `send_file` or static files you may have mime types Sinatra -doesn't understand. Use `mime_type` to register them by file extension: - -``` ruby -configure do - mime_type :foo, 'text/foo' -end -``` - -You can also use it with the `content_type` helper: - -``` ruby -get '/' do - content_type :foo - "foo foo foo" -end -``` - -### Generating URLs - -For generating URLs you should use the `url` helper method, for instance, in -Haml: - -``` ruby -%a{:href => url('/foo')} foo -``` - -It takes reverse proxies and Rack routers into account, if present. - -This method is also aliased to `to` (see below for an example). - -### Browser Redirect - -You can trigger a browser redirect with the `redirect` helper method: - -``` ruby -get '/foo' do - redirect to('/bar') -end -``` - -Any additional parameters are handled like arguments passed to `halt`: - -``` ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'wrong place, buddy' -``` - -You can also easily redirect back to the page the user came from with -`redirect back`: - -``` ruby -get '/foo' do - "do something" -end - -get '/bar' do - do_something - redirect back -end -``` - -To pass arguments with a redirect, either add them to the query: - -``` ruby -redirect to('/bar?sum=42') -``` - -Or use a session: - -``` ruby -enable :sessions - -get '/foo' do - session[:secret] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secret] -end -``` - -### Cache Control - -Setting your headers correctly is the foundation for proper HTTP caching. - -You can easily set the Cache-Control header like this: - -``` ruby -get '/' do - cache_control :public - "cache it!" -end -``` - -Pro tip: Set up caching in a before filter: - -``` ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -``` - -If you are using the `expires` helper to set the corresponding header, -`Cache-Control` will be set automatically for you: - -``` ruby -before do - expires 500, :public, :must_revalidate -end -``` - -To properly use caches, you should consider using `etag` or `last_modified`. -It is recommended to call those helpers *before* doing any heavy lifting, as they -will immediately flush a response if the client already has the current -version in its cache: - -``` ruby -get '/article/:id' do - @article = Article.find params[:id] - last_modified @article.updated_at - etag @article.sha1 - erb :article -end -``` - -It is also possible to use a -[weak ETag](http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation): - -``` ruby -etag @article.sha1, :weak -``` - -These helpers will not do any caching for you, but rather feed the necessary -information to your cache. If you are looking for a quick reverse-proxy caching -solution, try [rack-cache](https://github.com/rtomayko/rack-cache): - -``` ruby -require "rack/cache" -require "sinatra" - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hello" -end -``` - -Use the `:static_cache_control` setting (see below) to add -`Cache-Control` header info to static files. - -According to RFC 2616, your application should behave differently if the If-Match -or If-None-Match header is set to `*`, depending on whether the resource -requested is already in existence. Sinatra assumes resources for safe (like get) -and idempotent (like put) requests are already in existence, whereas other -resources (for instance post requests) are treated as new resources. You -can change this behavior by passing in a `:new_resource` option: - -``` ruby -get '/create' do - etag '', :new_resource => true - Article.create - erb :new_article -end -``` - -If you still want to use a weak ETag, pass in a `:kind` option: - -``` ruby -etag '', :new_resource => true, :kind => :weak -``` - -### Sending Files - -For sending files, you can use the `send_file` helper method: - -``` ruby -get '/' do - send_file 'foo.png' -end -``` - -It also takes options: - -``` ruby -send_file 'foo.png', :type => :jpg -``` - -The options are: - -
-
filename
-
file name, in response, defaults to the real file name.
- -
last_modified
-
value for Last-Modified header, defaults to the file's mtime.
- -
type
-
content type to use, guessed from the file extension if missing.
- - disposition -
- used for Content-Disposition, possible value: nil (default), - :attachment and :inline -
- -
length
-
Content-Length header, defaults to file size.
- -
status
-
- Status code to be sent. Useful when sending a static file as an error page. - - If supported by the Rack handler, other means than streaming from the Ruby - process will be used. If you use this helper method, Sinatra will automatically - handle range requests. -
-
- -### Accessing the Request Object - -The incoming request object can be accessed from request level (filter, routes, -error handlers) through the `request` method: - -``` ruby -# app running on http://example.com/example -get '/foo' do - t = %w[text/css text/html application/javascript] - request.accept # ['text/html', '*/*'] - request.accept? 'text/xml' # true - request.preferred_type(t) # 'text/html' - request.body # request body sent by the client (see below) - request.scheme # "http" - request.script_name # "/example" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # length of request.body - request.media_type # media type of request.body - request.host # "example.com" - request.get? # true (similar methods for other verbs) - request.form_data? # false - request["some_param"] # value of some_param parameter. [] is a shortcut to the params hash. - request.referrer # the referrer of the client or '/' - request.user_agent # user agent (used by :agent condition) - request.cookies # hash of browser cookies - request.xhr? # is this an ajax request? - request.url # "http://example.com/example/foo" - request.path # "/example/foo" - request.ip # client IP address - request.secure? # false (would be true over ssl) - request.forwarded? # true (if running behind a reverse proxy) - request.env # raw env hash handed in by Rack -end -``` - -Some options, like `script_name` or `path_info`, can also be -written: - -``` ruby -before { request.path_info = "/" } - -get "/" do - "all requests end up here" -end -``` - -The `request.body` is an IO or StringIO object: - -``` ruby -post "/api" do - request.body.rewind # in case someone already read it - data = JSON.parse request.body.read - "Hello #{data['name']}!" -end -``` - -### Attachments - -You can use the `attachment` helper to tell the browser the response should be -stored on disk rather than displayed in the browser: - -``` ruby -get '/' do - attachment - "store it!" -end -``` - -You can also pass it a file name: - -``` ruby -get '/' do - attachment "info.txt" - "store it!" -end -``` - -### Dealing with Date and Time - -Sinatra offers a `time_for` helper method that generates a Time object -from the given value. It is also able to convert `DateTime`, `Date` and -similar classes: - -``` ruby -get '/' do - pass if Time.now > time_for('Dec 23, 2012') - "still time" -end -``` - -This method is used internally by `expires`, `last_modified` and akin. You can -therefore easily extend the behavior of those methods by overriding `time_for` -in your application: - -``` ruby -helpers do - def time_for(value) - case value - when :yesterday then Time.now - 24*60*60 - when :tomorrow then Time.now + 24*60*60 - else super - end - end -end - -get '/' do - last_modified :yesterday - expires :tomorrow - "hello" -end -``` - -### Looking Up Template Files - -The `find_template` helper is used to find template files for rendering: - -``` ruby -find_template settings.views, 'foo', Tilt[:haml] do |file| - puts "could be #{file}" -end -``` - -This is not really useful. But it is useful that you can actually override this -method to hook in your own lookup mechanism. For instance, if you want to be -able to use more than one view directory: - -``` ruby -set :views, ['views', 'templates'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -``` - -Another example would be using different directories for different engines: - -``` ruby -set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:default] - super(folder, name, engine, &block) - end -end -``` - -You can also easily wrap this up in an extension and share with others! - -Note that `find_template` does not check if the file really exists but -rather calls the given block for all possible paths. This is not a performance -issue, since `render` will use `break` as soon as a file is found. Also, -template locations (and content) will be cached if you are not running in -development mode. You should keep that in mind if you write a really crazy -method. - -## Configuration - -Run once, at startup, in any environment: - -``` ruby -configure do - # setting one option - set :option, 'value' - - # setting multiple options - set :a => 1, :b => 2 - - # same as `set :option, true` - enable :option - - # same as `set :option, false` - disable :option - - # you can also have dynamic settings with blocks - set(:css_dir) { File.join(views, 'css') } -end -``` - -Run only when the environment (`RACK_ENV` environment variable) is set to -`:production`: - -``` ruby -configure :production do - ... -end -``` - -Run when the environment is set to either `:production` or `:test`: - -```ruby -configure :production, :test do - ... -end -``` - -You can access those options via `settings`: - -``` ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -``` - -### Configuring attack protection - -Sinatra is using -[Rack::Protection](https://github.com/rkh/rack-protection#readme) to defend -your application against common, opportunistic attacks. You can easily disable -this behavior (which will open up your application to tons of common -vulnerabilities): - -``` ruby -disable :protection -``` - -To skip a single defense layer, set `protection` to an options hash: - -``` ruby -set :protection, :except => :path_traversal -``` -You can also hand in an array in order to disable a list of protections: - -``` ruby -set :protection, :except => [:path_traversal, :session_hijacking] -``` - -By default, Sinatra will only set up session based protection if `:sessions` -has been enabled. Sometimes you want to set up sessions on your own, though. In -that case you can get it to set up session based protections by passing the -`:session` option: - -``` ruby -use Rack::Session::Pool -set :protection, :session => true -``` - -### Available Settings - -
-
absolute_redirects
-
- If disabled, Sinatra will allow relative redirects, however, Sinatra will no - longer conform with RFC 2616 (HTTP 1.1), which only allows absolute redirects. -
-
- Enable if your app is running behind a reverse proxy that has not been set up - properly. Note that the url helper will still produce absolute URLs, unless you - pass in false as the second parameter. -
-
Disabled by default.
- -
add_charsets
-
- Mime types the content_type helper will automatically add the charset info to. - You should add to it rather than overriding this option: - settings.add_charsets << "application/foobar" -
- -
app_file
-
- Path to the main application file, used to detect project root, views and public - folder and inline templates. -
- -
bind
-
IP address to bind to (default: 0.0.0.0 or localhost if your `environment` is set to development.). Only used for built-in server.
- -
default_encoding
-
Encoding to assume if unknown (defaults to "utf-8").
- -
dump_errors
-
Display errors in the log.
- -
environment
-
- Current environment. Defaults to ENV['RACK_ENV'], or "development" if - not available. -
- -
logging
-
Use the logger.
- -
lock
-
- Places a lock around every request, only running processing on request - per Ruby process concurrently. -
-
Enabled if your app is not thread-safe. Disabled per default.
- -
method_override
-
- Use _method magic to allow put/delete forms in browsers that - don't support it. -
- -
port
-
Port to listen on. Only used for built-in server.
- -
prefixed_redirects
-
- Whether or not to insert request.script_name into redirects if no - absolute path is given. That way redirect '/foo' would behave like - redirect to('/foo'). Disabled per default. -
- -
protection
-
Whether or not to enable web attack protections. See protection section above.
- -
public_dir
-
Alias for public_folder. See below.
- -
public_folder
-
- Path to the folder public files are served from. Only used if static - file serving is enabled (see static setting below). Inferred from - app_file setting if not set. -
- -
reload_templates
-
- Whether or not to reload templates between requests. Enabled in development mode. -
- -
root
-
- Path to project root folder. Inferred from app_file setting if not set. -
- -
raise_errors
-
- Raise exceptions (will stop application). Enabled by default when - environment is set to "test", disabled otherwise. -
- -
run
-
- If enabled, Sinatra will handle starting the web server. Do not - enable if using rackup or other means. -
- -
running
-
Is the built-in server running now? Do not change this setting!
- -
server
-
- Server or list of servers to use for built-in server. Order indicates - priority, default depends on Ruby implementation. -
- -
sessions
-
- Enable cookie-based sessions support using Rack::Session::Cookie. - See 'Using Sessions' section for more information. -
- -
show_exceptions
-
- Show a stack trace in the browser when an exception - happens. Enabled by default when environment - is set to "development", disabled otherwise. -
-
- Can also be set to :after_handler to trigger - app-specified error handling before showing a stack - trace in the browser. -
- -
static
-
Whether Sinatra should handle serving static files.
-
Disable when using a server able to do this on its own.
-
Disabling will boost performance.
-
- Enabled per default in classic style, disabled for - modular apps. -
- -
static_cache_control
-
- When Sinatra is serving static files, set this to add - Cache-Control headers to the responses. Uses the - cache_control helper. Disabled by default. -
-
- Use an explicit array when setting multiple values: - set :static_cache_control, [:public, :max_age => 300] -
- -
threaded
-
- If set to true, will tell Thin to use EventMachine.defer - for processing the request. -
- -
traps
-
Whether Sinatra should handle system signals.
- -
views
-
- Path to the views folder. Inferred from app_file setting if - not set. -
- -
x_cascade
-
- Whether or not to set the X-Cascade header if no route matches. - Defaults to true. -
-
- -## Environments - -There are three predefined `environments`: `"development"`, -`"production"` and `"test"`. Environments can be set -through the `RACK_ENV` environment variable. The default value is -`"development"`. In the `"development"` environment all templates are reloaded between -requests, and special `not_found` and `error` handlers -display stack traces in your browser. -In the `"production"` and `"test"` environments, templates are cached by default. - -To run different environments, set the `RACK_ENV` environment variable: - -``` shell -RACK_ENV=production ruby my_app.rb -``` - -You can use predefined methods: `development?`, `test?` and `production?` to -check the current environment setting: - -``` ruby -get '/' do - if settings.development? - "development!" - else - "not development!" - end -end -``` - -## Error Handling - -Error handlers run within the same context as routes and before filters, which -means you get all the goodies it has to offer, like `haml`, -`erb`, `halt`, etc. - -### Not Found - -When a `Sinatra::NotFound` exception is raised, or the response's status -code is 404, the `not_found` handler is invoked: - -``` ruby -not_found do - 'This is nowhere to be found.' -end -``` - -### Error - -The `error` handler is invoked any time an exception is raised from a route -block or a filter. The exception object can be obtained from the -`sinatra.error` Rack variable: - -``` ruby -error do - 'Sorry there was a nasty error - ' + env['sinatra.error'].name -end -``` - -Custom errors: - -``` ruby -error MyCustomError do - 'So what happened was...' + env['sinatra.error'].message -end -``` - -Then, if this happens: - -``` ruby -get '/' do - raise MyCustomError, 'something bad' -end -``` - -You get this: - -``` -So what happened was... something bad -``` - -Alternatively, you can install an error handler for a status code: - -``` ruby -error 403 do - 'Access forbidden' -end - -get '/secret' do - 403 -end -``` - -Or a range: - -``` ruby -error 400..510 do - 'Boom' -end -``` - -Sinatra installs special `not_found` and `error` handlers when -running under the development environment to display nice stack traces -and additional debugging information in your browser. - -## Rack Middleware - -Sinatra rides on [Rack](http://rack.rubyforge.org/), a minimal standard -interface for Ruby web frameworks. One of Rack's most interesting capabilities -for application developers is support for "middleware" -- components that sit -between the server and your application monitoring and/or manipulating the -HTTP request/response to provide various types of common functionality. - -Sinatra makes building Rack middleware pipelines a cinch via a top-level -`use` method: - -``` ruby -require 'sinatra' -require 'my_custom_middleware' - -use Rack::Lint -use MyCustomMiddleware - -get '/hello' do - 'Hello World' -end -``` - -The semantics of `use` are identical to those defined for the -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html) DSL -(most frequently used from rackup files). For example, the `use` method -accepts multiple/variable args as well as blocks: - -``` ruby -use Rack::Auth::Basic do |username, password| - username == 'admin' && password == 'secret' -end -``` - -Rack is distributed with a variety of standard middleware for logging, -debugging, URL routing, authentication, and session handling. Sinatra uses -many of these components automatically based on configuration so you -typically don't have to `use` them explicitly. - -You can find useful middleware in -[rack](https://github.com/rack/rack/tree/master/lib/rack), -[rack-contrib](https://github.com/rack/rack-contrib#readm), -or in the [Rack wiki](https://github.com/rack/rack/wiki/List-of-Middleware). - -## Testing - -Sinatra tests can be written using any Rack-based testing library or framework. -[Rack::Test](http://rdoc.info/github/brynary/rack-test/master/frames) -is recommended: - -``` ruby -require 'my_sinatra_app' -require 'test/unit' -require 'rack/test' - -class MyAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_my_default - get '/' - assert_equal 'Hello World!', last_response.body - end - - def test_with_params - get '/meet', :name => 'Frank' - assert_equal 'Hello Frank!', last_response.body - end - - def test_with_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "You're using Songbird!", last_response.body - end -end -``` - -Note: If you are using Sinatra in the modular style, replace `Sinatra::Application` -above with the class name of your app. - -## Sinatra::Base - Middleware, Libraries, and Modular Apps - -Defining your app at the top-level works well for micro-apps but has -considerable drawbacks when building reusable components such as Rack -middleware, Rails metal, simple libraries with a server component, or even -Sinatra extensions. The top-level assumes a micro-app style configuration -(e.g., a single application file, `./public` and `./views` -directories, logging, exception detail page, etc.). That's where -`Sinatra::Base` comes into play: - -``` ruby -require 'sinatra/base' - -class MyApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Hello world!' - end -end -``` - -The methods available to `Sinatra::Base` subclasses are exactly the same as those -available via the top-level DSL. Most top-level apps can be converted to -`Sinatra::Base` components with two modifications: - -* Your file should require `sinatra/base` instead of `sinatra`; - otherwise, all of Sinatra's DSL methods are imported into the main - namespace. -* Put your app's routes, error handlers, filters, and options in a subclass - of `Sinatra::Base`. - -`Sinatra::Base` is a blank slate. Most options are disabled by default, -including the built-in server. See -[Configuring Settings](http://sinatra.github.com/configuration.html) -for details on available options and their behavior. If you want -behavior more similar to when you define your app at the top level (also -know as Classic style), you -can subclass `Sinatra::Application`. - -``` ruby -require 'sinatra/base' - -class MyApp < Sinatra::Application - get '/' do - 'Hello world!' - end -end -``` - -### Modular vs. Classic Style - -Contrary to common belief, there is nothing wrong with the classic style. If it -suits your application, you do not have to switch to a modular application. - -The main disadvantage of using the classic style rather than the modular style is that -you will only have one Sinatra application per Ruby process. If you plan to use -more than one, switch to the modular style. There is no reason you cannot mix -the modular and the classic styles. - -If switching from one style to the other, you should be aware of slightly -different default settings: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SettingClassicModularModular
app_filefile loading sinatrafile subclassing Sinatra::Basefile subclassing Sinatra::Application
run$0 == app_filefalsefalse
loggingtruefalsetrue
method_overridetruefalsetrue
inline_templatestruefalsetrue
statictruefalsetrue
- -### Serving a Modular Application - -There are two common options for starting a modular app, actively starting with -`run!`: - -``` ruby -# my_app.rb -require 'sinatra/base' - -class MyApp < Sinatra::Base - # ... app code here ... - - # start the server if ruby file executed directly - run! if app_file == $0 -end -``` - -Start with: - -``` shell -ruby my_app.rb -``` - -Or with a `config.ru` file, which allows using any Rack handler: - -``` ruby -# config.ru (run with rackup) -require './my_app' -run MyApp -``` - -Run: - -``` shell -rackup -p 4567 -``` - -### Using a Classic Style Application with a config.ru - -Write your app file: - -``` ruby -# app.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -And a corresponding `config.ru`: - -``` ruby -require './app' -run Sinatra::Application -``` - -### When to use a config.ru? - -A `config.ru` file is recommended if: - -* You want to deploy with a different Rack handler (Passenger, Unicorn, - Heroku, ...). -* You want to use more than one subclass of `Sinatra::Base`. -* You want to use Sinatra only for middleware, and not as an endpoint. - -**There is no need to switch to a `config.ru` simply because you -switched to the modular style, and you don't have to use the modular style for running -with a `config.ru`.** - -### Using Sinatra as Middleware - -Not only is Sinatra able to use other Rack middleware, any Sinatra application -can in turn be added in front of any Rack endpoint as middleware itself. This -endpoint could be another Sinatra application, or any other Rack-based -application (Rails/Ramaze/Camping/...): - -``` ruby -require 'sinatra/base' - -class LoginScreen < Sinatra::Base - enable :sessions - - get('/login') { haml :login } - - post('/login') do - if params[:name] == 'admin' && params[:password] == 'admin' - session['user_name'] = params[:name] - else - redirect '/login' - end - end -end - -class MyApp < Sinatra::Base - # middleware will run before filters - use LoginScreen - - before do - unless session['user_name'] - halt "Access denied, please login." - end - end - - get('/') { "Hello #{session['user_name']}." } -end -``` - -### Dynamic Application Creation - -Sometimes you want to create new applications at runtime without having to -assign them to a constant. You can do this with `Sinatra.new`: - -``` ruby -require 'sinatra/base' -my_app = Sinatra.new { get('/') { "hi" } } -my_app.run! -``` - -It takes the application to inherit from as an optional argument: - -```ruby -# config.ru (run with rackup) -require 'sinatra/base' - -controller = Sinatra.new do - enable :logging - helpers MyHelpers -end - -map('/a') do - run Sinatra.new(controller) { get('/') { 'a' } } -end - -map('/b') do - run Sinatra.new(controller) { get('/') { 'b' } } -end -``` - -This is especially useful for testing Sinatra extensions or using Sinatra in -your own library. - -This also makes using Sinatra as middleware extremely easy: - -``` ruby -require 'sinatra/base' - -use Sinatra do - get('/') { ... } -end - -run RailsProject::Application -``` - -## Scopes and Binding - -The scope you are currently in determines what methods and variables are -available. - -### Application/Class Scope - -Every Sinatra application corresponds to a subclass of `Sinatra::Base`. -If you are using the top-level DSL (`require 'sinatra'`), then this -class is `Sinatra::Application`, otherwise it is the subclass you -created explicitly. At class level you have methods like `get` or `before`, but -you cannot access the `request` or `session` objects, as there is only a -single application class for all requests. - -Options created via `set` are methods at class level: - -``` ruby -class MyApp < Sinatra::Base - # Hey, I'm in the application scope! - set :foo, 42 - foo # => 42 - - get '/foo' do - # Hey, I'm no longer in the application scope! - end -end -``` - -You have the application scope binding inside: - -* Your application class body -* Methods defined by extensions -* The block passed to `helpers` -* Procs/blocks used as value for `set` -* The block passed to `Sinatra.new` - -You can reach the scope object (the class) like this: - -* Via the object passed to configure blocks (`configure { |c| ... }`) -* `settings` from within the request scope - -### Request/Instance Scope - -For every incoming request, a new instance of your application class is -created, and all handler blocks run in that scope. From within this scope you -can access the `request` and `session` objects or call rendering methods like -`erb` or `haml`. You can access the application scope from within the request -scope via the `settings` helper: - -``` ruby -class MyApp < Sinatra::Base - # Hey, I'm in the application scope! - get '/define_route/:name' do - # Request scope for '/define_route/:name' - @value = 42 - - settings.get("/#{params[:name]}") do - # Request scope for "/#{params[:name]}" - @value # => nil (not the same request) - end - - "Route defined!" - end -end -``` - -You have the request scope binding inside: - -* get, head, post, put, delete, options, patch, link, and unlink blocks -* before and after filters -* helper methods -* templates/views - -### Delegation Scope - -The delegation scope just forwards methods to the class scope. However, it -does not behave exactly like the class scope, as you do not have the class -binding. Only methods explicitly marked for delegation are available, and you -do not share variables/state with the class scope (read: you have a different -`self`). You can explicitly add method delegations by calling -`Sinatra::Delegator.delegate :method_name`. - -You have the delegate scope binding inside: - -* The top level binding, if you did `require "sinatra"` -* An object extended with the `Sinatra::Delegator` mixin - -Have a look at the code for yourself: here's the -[Sinatra::Delegator mixin](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633) -being [extending the main object](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30). - -## Command Line - -Sinatra applications can be run directly: - -``` shell -ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER] -``` - -Options are: - -``` --h # help --p # set the port (default is 4567) --o # set the host (default is 0.0.0.0) --e # set the environment (default is development) --s # specify rack server/handler (default is thin) --x # turn on the mutex lock (default is off) -``` - -## Requirement - -The following Ruby versions are officially supported: -
-
Ruby 1.8.7
-
- 1.8.7 is fully supported, however, if nothing is keeping you from it, we - recommend upgrading or switching to JRuby or Rubinius. Support for 1.8.7 - will not be dropped before Sinatra 2.0. Ruby 1.8.6 is no longer supported. -
- -
Ruby 1.9.2
-
- 1.9.2 is fully supported. Do not use 1.9.2p0, as it is known to cause - segmentation faults when running Sinatra. Official support will continue - at least until the release of Sinatra 1.5. -
- -
Ruby 1.9.3
-
- 1.9.3 is fully supported and recommended. Please note that switching to 1.9.3 - from an earlier version will invalidate all sessions. 1.9.3 will be supported - until the release of Sinatra 2.0. -
- -
Ruby 2.0.0
-
- 2.0.0 is fully supported and recommended. There are currently no plans to drop - official support for it. -
- -
Rubinius
-
- Rubinius is officially supported (Rubinius >= 2.x). It is recommended to - gem install puma. -
- -
JRuby
-
- The latest stable release of JRuby is officially supported. It is not - recommended to use C extensions with JRuby. It is recommended to - gem install trinidad. -
-
- -We also keep an eye on upcoming Ruby versions. - -The following Ruby implementations are not officially supported but still are -known to run Sinatra: - -* Older versions of JRuby and Rubinius -* Ruby Enterprise Edition -* MacRuby, Maglev, IronRuby -* Ruby 1.9.0 and 1.9.1 (but we do recommend against using those) - -Not being officially supported means if things only break there and not on a -supported platform, we assume it's not our issue but theirs. - -We also run our CI against ruby-head (the upcoming 2.1.0), but we can't -guarantee anything, since it is constantly moving. Expect 2.1.0 to be fully -supported. - -Sinatra should work on any operating system supported by the chosen Ruby -implementation. - -If you run MacRuby, you should `gem install control_tower`. - -Sinatra currently doesn't run on Cardinal, SmallRuby, BlueRuby or any -Ruby version prior to 1.8.7. - -## The Bleeding Edge - -If you would like to use Sinatra's latest bleeding-edge code, feel free to run your -application against the master branch, it should be rather stable. - -We also push out prerelease gems from time to time, so you can do a - -``` shell -gem install sinatra --pre -``` - -to get some of the latest features. - -### With Bundler - -If you want to run your application with the latest Sinatra, using -[Bundler](http://gembundler.com/) is the recommended way. - -First, install bundler, if you haven't: - -``` shell -gem install bundler -``` - -Then, in your project directory, create a `Gemfile`: - -```ruby -source 'https://rubygems.org' -gem 'sinatra', :github => "sinatra/sinatra" - -# other dependencies -gem 'haml' # for instance, if you use haml -gem 'activerecord', '~> 3.0' # maybe you also need ActiveRecord 3.x -``` - -Note that you will have to list all your application's dependencies in the `Gemfile`. -Sinatra's direct dependencies (Rack and Tilt) will, however, be automatically -fetched and added by Bundler. - -Now you can run your app like this: - -``` shell -bundle exec ruby myapp.rb -``` - -### Roll Your Own - -Create a local clone and run your app with the `sinatra/lib` directory -on the `$LOAD_PATH`: - -``` shell -cd myapp -git clone git://github.com/sinatra/sinatra.git -ruby -I sinatra/lib myapp.rb -``` - -To update the Sinatra sources in the future: - -``` shell -cd myapp/sinatra -git pull -``` - -### Install Globally - -You can build the gem on your own: - -``` shell -git clone git://github.com/sinatra/sinatra.git -cd sinatra -rake sinatra.gemspec -rake install -``` - -If you install gems as root, the last step should be: - -``` shell -sudo rake install -``` - -## Versioning - -Sinatra follows [Semantic Versioning](http://semver.org/), both SemVer and -SemVerTag. - -## Further Reading - -* [Project Website](http://www.sinatrarb.com/) - Additional documentation, - news, and links to other resources. -* [Contributing](http://www.sinatrarb.com/contributing) - Find a bug? Need - help? Have a patch? -* [Issue tracker](http://github.com/sinatra/sinatra/issues) -* [Twitter](http://twitter.com/sinatra) -* [Mailing List](http://groups.google.com/group/sinatrarb/topics) -* IRC: [#sinatra](irc://chat.freenode.net/#sinatra) on http://freenode.net -* [Sinatra Book](http://sinatra-book.gittr.com) Cookbook Tutorial -* [Sinatra Recipes](http://recipes.sinatrarb.com/) Community - contributed recipes -* API documentation for the [latest release](http://rubydoc.info/gems/sinatra) - or the [current HEAD](http://rubydoc.info/github/sinatra/sinatra) on - http://rubydoc.info -* [CI server](http://travis-ci.org/sinatra/sinatra) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.pt-br.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.pt-br.md deleted file mode 100644 index 2ec7ffe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.pt-br.md +++ /dev/null @@ -1,965 +0,0 @@ -# Sinatra - -*Atenção: Este documento é apenas uma tradução da versão em inglês e -pode estar desatualizado.* - -Alguns dos trechos de códigos a seguir utilizam caracteres UTF-8, então caso esteja utilizando uma versão de ruby inferior a `2.0.0` adicione o enconding no início de seus arquivos: - -```ruby -# encoding: utf-8 -``` - -Sinatra é uma [DSL](http://pt.wikipedia.org/wiki/Linguagem_de_domínio_específico) para -criar aplicações web em Ruby com o mínimo de esforço e rapidez: - -``` ruby -# minha_app.rb -require 'sinatra' - -get '/' do - 'Olá Mundo!' -end -``` - -Instale a gem: - -``` shell -gem install sinatra -``` - -Em seguida execute: - -``` shell -ruby minha_app.rb -``` - -Acesse: [localhost:4567](http://localhost:4567) - -É recomendado também executar `gem install thin`. Caso esta gem esteja disponível, o -Sinatra irá utilizá-la. - - -## Rotas - -No Sinatra, uma rota é um método HTTP emparelhado com um padrão de URL. -Cada rota possui um bloco de execução: - -``` ruby -get '/' do - .. mostrando alguma coisa .. -end - -post '/' do - .. criando alguma coisa .. -end - -put '/' do - .. atualizando alguma coisa .. -end - -patch '/' do - .. modificando alguma coisa .. -end - -delete '/' do - .. removendo alguma coisa .. -end - -options '/' do - .. estabelecendo alguma coisa .. -end -``` - -As rotas são interpretadas na ordem em que são definidas. A primeira -rota encontrada responde ao pedido. - -Padrões de rota podem conter parâmetros nomeados, acessível através do -hash `params`: - -``` ruby -get '/ola/:nome' do - # corresponde a "GET /ola/foo" e "GET /ola/bar" - # params[:nome] é 'foo' ou 'bar' - "Olá #{params[:nome]}!" -end -``` - -Você também pode acessar parâmetros nomeados através dos parâmetros de -um bloco: - -``` ruby -get '/ola/:nome' do |n| - "Olá #{n}!" -end -``` - -Padrões de rota também podem conter parâmetros splat (wildcard), -acessível através do array `params[: splat]`: - -``` ruby -get '/diga/*/para/*' do - # corresponde a /diga/ola/para/mundo - params[:splat] # => ["ola", "mundo"] -end - -get '/download/*.*' do - # corresponde a /download/pasta/do/arquivo.xml - params[:splat] # => ["pasta/do/arquivo", "xml"] -end -``` - -Ou com parâmetros de um bloco: - -``` ruby -get '/download/*.*' do |pasta, ext| - [pasta, ext] # => ["pasta/do/arquivo", "xml"] -end -``` - -Rotas podem corresponder com expressões regulares: - -``` ruby -get %r{/ola/([\w]+)} do - "Olá, #{params[:captures].first}!" -end -``` - -Ou com parâmetros de um bloco: - -``` ruby -get %r{/ola/([\w]+)} do |c| - "Olá, #{c}!" -end -``` - -Padrões de rota podem contar com parâmetros opcionais: - -``` ruby -get '/posts.?:formato?' do - # corresponde a "GET /posts" e qualquer extensão "GET /posts.json", "GET /posts.xml", etc. -end -``` - -A propósito, a menos que você desative a proteção contra ataques (veja -abaixo), o caminho solicitado pode ser alterado antes de concluir a -comparação com as suas rotas. - -### Condições - -Rotas podem incluir uma variedade de condições, tal como o `user agent`: - -``` ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "Você está usando o Songbird versão #{params[:agent][0]}" -end - -get '/foo' do - # Correspondente a navegadores que não sejam Songbird -end -``` - -Outras condições disponíveis são `host_name` e `provides`: - -``` ruby -get '/', :host_name => /^admin\./ do - "Área administrativa. Acesso negado!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -Você pode facilmente definir suas próprias condições: - -``` ruby -set(:probabilidade) { |valor| condition { rand <= valor } } - -get '/ganha_um_carro', :probabilidade => 0.1 do - "Você ganhou!" -end - -get '/ganha_um_carro' do - "Sinto muito, você perdeu." -end -``` - -Use splat, para uma condição que levam vários valores: - -``` ruby -set(:auth) do |*roles| # <- observe o splat aqui - condition do - unless logged_in? && roles.any? {|role| current_user.in_role? role } - redirect "/login/", 303 - end - end -end - -get "/minha/conta/", :auth => [:usuario, :administrador] do - "Detalhes da sua conta" -end - -get "/apenas/administrador/", :auth => :administrador do - "Apenas administradores são permitidos aqui!" -end -``` - -### Retorno de valores - -O valor de retorno do bloco de uma rota determina pelo menos o corpo da -resposta passado para o cliente HTTP, ou pelo menos o próximo middleware -na pilha Rack. Frequentemente, isto é uma `string`, tal como nos -exemplos acima. Mas, outros valores também são aceitos. - -Você pode retornar uma resposta válida ou um objeto para o Rack, sendo -eles de qualquer tipo de objeto que queira. Além disto, é possível -retornar um código de status HTTP. - -- Um array com três elementros: `[status (Fixnum), cabecalho (Hash), - corpo da resposta (responde à #each)]` - -- Um array com dois elementros: `[status (Fixnum), corpo da resposta - (responde à #each)]` - -- Um objeto que responda à `#each` sem passar nada, mas, sim, `strings` - para um dado bloco - -- Um objeto `Fixnum` representando o código de status - -Dessa forma, podemos implementar facilmente um exemplo de streaming: - -``` ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -Você também pode usar o método auxiliar `stream` (descrito abaixo) para -incorporar a lógica de streaming na rota. - -### Custom Route Matchers - -Como apresentado acima, a estrutura do Sinatra conta com suporte -embutido para uso de padrões de String e expressões regulares como -validadores de rota. No entanto, ele não pára por aí. Você pode -facilmente definir os seus próprios validadores: - -``` ruby -class AllButPattern - Match = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Match.new([]) - end - - def match(str) - @captures unless @except === str - end -end - -def all_but(pattern) - AllButPattern.new(pattern) -end - -get all_but("/index") do - # ... -end -``` - -Note que o exemplo acima pode ser robusto e complicado em excesso. Pode -também ser implementado como: - -``` ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -Ou, usando algo mais denso à frente: - -``` ruby -get %r{^(?!/index$)} do - # ... -end -``` - -## Arquivos estáticos - -Arquivos estáticos são disponibilizados a partir do diretório -`./public`. Você pode especificar um local diferente pela opção -`:public_folder` - -``` ruby -set :public_folder, File.dirname(__FILE__) + '/estatico' -``` - -Note que o nome do diretório público não é incluido na URL. Um arquivo -`./public/css/style.css` é disponibilizado como -`http://example.com/css/style.css`. - -## Views / Templates - -Templates presumem-se estar localizados sob o diretório `./views`. Para -utilizar um diretório view diferente: - -``` ruby -set :views, File.dirname(__FILE__) + '/modelo' -``` - -Uma coisa importante a ser lembrada é que você sempre tem as referências -dos templates como símbolos, mesmo se eles estiverem em um sub-diretório -(nesse caso utilize `:'subdir/template'`). Métodos de renderização irão -processar qualquer string passada diretamente para elas. - -### Haml Templates - -A gem/biblioteca haml é necessária para renderizar templates HAML: - -``` ruby -# Você precisa do 'require haml' em sua aplicação. -require 'haml' - -get '/' do - haml :index -end -``` - -Renderiza `./views/index.haml`. - -[Opções -Haml](http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options) -podem ser setadas globalmente através das configurações do sinatra, veja -[Opções e Configurações](http://www.sinatrarb.com/configuration.html), e -substitua em uma requisição individual. - -``` ruby -set :haml, {:format => :html5 } # o formato padrão do Haml é :xhtml - -get '/' do - haml :index, :haml_options => {:format => :html4 } # substituido -end -``` - -### Erb Templates - -``` ruby -# Você precisa do 'require erb' em sua aplicação -require 'erb' - -get '/' do - erb :index -end -``` - -Renderiza `./views/index.erb` - -### Erubis - -A gem/biblioteca erubis é necessária para renderizar templates erubis: - -``` ruby -# Você precisa do 'require erubis' em sua aplicação. -require 'erubis' - -get '/' do - erubis :index -end -``` - -Renderiza `./views/index.erubis` - -### Builder Templates - -A gem/biblioteca builder é necessária para renderizar templates builder: - -``` ruby -# Você precisa do 'require builder' em sua aplicação. -require 'builder' - -get '/' do - content_type 'application/xml', :charset => 'utf-8' - builder :index -end -``` - -Renderiza `./views/index.builder`. - -### Sass Templates - -A gem/biblioteca sass é necessária para renderizar templates sass: - -``` ruby -# Você precisa do 'require haml' ou 'require sass' em sua aplicação. -require 'sass' - -get '/stylesheet.css' do - content_type 'text/css', :charset => 'utf-8' - sass :stylesheet -end -``` - -Renderiza `./views/stylesheet.sass`. - -[Opções -Sass](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options) -podem ser setadas globalmente através das configurações do sinatra, veja -[Opções e Configurações](http://www.sinatrarb.com/configuration.html), e -substitua em uma requisição individual. - -``` ruby -set :sass, {:style => :compact } # o estilo padrão do Sass é :nested - -get '/stylesheet.css' do - content_type 'text/css', :charset => 'utf-8' - sass :stylesheet, :style => :expanded # substituido -end -``` - -### Less Templates - -A gem/biblioteca less é necessária para renderizar templates Less: - -``` ruby -# Você precisa do 'require less' em sua aplicação. -require 'less' - -get '/stylesheet.css' do - content_type 'text/css', :charset => 'utf-8' - less :stylesheet -end -``` - -Renderiza `./views/stylesheet.less`. - -### Inline Templates - -``` ruby -get '/' do - haml '%div.title Olá Mundo' -end -``` - -Renderiza a string, em uma linha, no template. - -### Acessando Variáveis nos Templates - -Templates são avaliados dentro do mesmo contexto como manipuladores de -rota. Variáveis de instância setadas em rotas manipuladas são -diretamente acessadas por templates: - -``` ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.nome' -end -``` - -Ou, especifique um hash explícito para variáveis locais: - -``` ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= foo.nome', :locals => { :foo => foo } -end -``` - -Isso é tipicamente utilizando quando renderizamos templates como -partials dentro de outros templates. - -### Templates Inline - -Templates podem ser definidos no final do arquivo fonte(.rb): - -``` ruby -require 'rubygems' -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Olá Mundo!!!!! -``` - -NOTA: Templates inline definidos no arquivo fonte são automaticamente -carregados pelo sinatra. Digite \`enable :inline\_templates\` se você -tem templates inline no outro arquivo fonte. - -### Templates nomeados - -Templates também podem ser definidos utilizando o método top-level -`template`: - -``` ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Olá Mundo!' -end - -get '/' do - haml :index -end -``` - -Se existir um template com nome “layout”, ele será utilizado toda vez -que um template for renderizado. Você pode desabilitar layouts passando -`:layout => false`. - -``` ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -## Helpers - -Use o método de alto nível `helpers` para definir métodos auxiliares -para utilizar em manipuladores de rotas e modelos: - -``` ruby -helpers do - def bar(nome) - "#{nome}bar" - end -end - -get '/:nome' do - bar(params[:nome]) -end -``` - -## Filtros - -Filtros Before são avaliados antes de cada requisição dentro do contexto -da requisição e pode modificar a requisição e a reposta. Variáveis de -instância setadas nos filtros são acessadas através de rotas e -templates: - -``` ruby -before do - @nota = 'Oi!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @nota #=> 'Oi!' - params[:splat] #=> 'bar/baz' -end -``` - -Filtros After são avaliados após cada requisição dentro do contexto da -requisição e também podem modificar o pedido e a resposta. Variáveis de -instância definidas nos filtros before e rotas são acessadas através dos -filtros after: - -``` ruby -after do - puts response.status -end -``` - -Filtros opcionalmente tem um padrão, fazendo com que sejam avaliados -somente se o caminho do pedido coincidir com esse padrão: - -``` ruby -before '/protected/*' do - authenticate! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -``` - -## Halting - -Para parar imediatamente uma requisição com um filtro ou rota utilize: - -``` ruby -halt -``` - -Você também pode especificar o status quando parar… - -``` ruby -halt 410 -``` - -Ou com corpo de texto… - -``` ruby -halt 'isso será o corpo do texto' -``` - -Ou também… - -``` ruby -halt 401, 'vamos embora!' -``` - -Com cabeçalhos… - -``` ruby -halt 402, {'Content-Type' => 'text/plain'}, 'revanche' -``` - -## Passing - -Uma rota pode processar aposta para a próxima rota correspondente usando -`pass`: - -``` ruby -get '/adivinhar/:quem' do - pass unless params[:quem] == 'Frank' - 'Você me pegou!' -end - -get '/adivinhar/*' do - 'Você falhou!' -end -``` - -O bloqueio da rota é imediatamente encerrado e o controle continua com a -próxima rota de parâmetro. Se o parâmetro da rota não for encontrado, um -404 é retornado. - -## Configuração - -Rodando uma vez, na inicialização, em qualquer ambiente: - -``` ruby -configure do - ... -end -``` - -Rodando somente quando o ambiente (`RACK_ENV` environment variável) é -setado para `:production`: - -``` ruby -configure :production do - ... -end -``` - -Rodando quando o ambiente é setado para `:production` ou `:test`: - -``` ruby -configure :production, :test do - ... -end -``` - -## Tratamento de Erros - -Tratamento de erros rodam dentro do mesmo contexto como rotas e filtros -before, o que significa que você pega todos os presentes que tem para -oferecer, como `haml`, `erb`, `halt`, etc. - -### Não Encontrado - -Quando um `Sinatra::NotFound` exception é levantado, ou o código de -status da reposta é 404, o `not_found` manipulador é invocado: - -``` ruby -not_found do - 'Isto está longe de ser encontrado' -end -``` - -### Erro - -O manipulador `error` é invocado toda a vez que uma exceção é lançada a -partir de um bloco de rota ou um filtro. O objeto da exceção pode ser -obtido a partir da variável Rack `sinatra.error`: - -``` ruby -error do - 'Desculpe, houve um erro desagradável - ' + env['sinatra.error'].name -end -``` - -Erros customizados: - -``` ruby -error MeuErroCustomizado do - 'Então que aconteceu foi...' + env['sinatra.error'].message -end -``` - -Então, se isso acontecer: - -``` ruby -get '/' do - raise MeuErroCustomizado, 'alguma coisa ruim' -end -``` - -Você receberá isso: - - Então que aconteceu foi... alguma coisa ruim - -Alternativamente, você pode instalar manipulador de erro para um código -de status: - -``` ruby -error 403 do - 'Accesso negado' -end - -get '/secreto' do - 403 -end -``` - -Ou um range: - -``` ruby -error 400..510 do - 'Boom' -end -``` - -O Sinatra instala os manipuladores especiais `not_found` e `error` -quando roda sobre o ambiente de desenvolvimento. - -## Mime Types - -Quando utilizamos `send_file` ou arquivos estáticos você pode ter mime -types Sinatra não entendidos. Use `mime_type` para registrar eles por -extensão de arquivos: - -``` ruby -mime_type :foo, 'text/foo' -``` - -Você também pode utilizar isto com o helper `content_type`: - -``` ruby -content_type :foo -``` - -## Middleware Rack - -O Sinatra roda no [Rack](http://rack.rubyforge.org/), uma interface -padrão mínima para frameworks web em Ruby. Um das capacidades mais -interessantes do Rack para desenvolver aplicativos é suporte a -“middleware” – componentes que ficam entre o servidor e sua aplicação -monitorando e/ou manipulando o request/response do HTTP para prover -vários tipos de funcionalidades comuns. - -O Sinatra faz construtores pipelines do middleware Rack facilmente em um -nível superior utilizando o método `use`: - -``` ruby -require 'sinatra' -require 'meu_middleware_customizado' - -use Rack::Lint -use MeuMiddlewareCustomizado - -get '/ola' do - 'Olá mundo' -end -``` - -A semântica de `use` é idêntica aquela definida para a DSL -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html) -(mais frequentemente utilizada para arquivos rackup). Por exemplo, o -método `use` aceita múltiplos argumentos/variáveis bem como blocos: - -``` ruby -use Rack::Auth::Basic do |usuario, senha| - usuario == 'admin' && senha == 'secreto' -end -``` - -O Rack é distribuido com uma variedade de middleware padrões para logs, -debugs, rotas de URL, autenticação, e manipuladores de sessão. Sinatra -utilizada muitos desses componentes automaticamente baseando sobre -configuração, então, tipicamente você não tem `use` explicitamente. - -## Testando - -Testes no Sinatra podem ser escritos utilizando qualquer biblioteca ou -framework de teste baseados no Rack. -[Rack::Test](http://gitrdoc.com/brynary/rack-test) é recomendado: - -``` ruby -require 'minha_aplicacao_sinatra' -require 'rack/test' - -class MinhaAplicacaoTeste < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def meu_test_default - get '/' - assert_equal 'Ola Mundo!', last_response.body - end - - def teste_com_parametros - get '/atender', :name => 'Frank' - assert_equal 'Olá Frank!', last_response.bodymeet - end - - def test_com_ambiente_rack - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "Você está utilizando o Songbird!", last_response.body - end -end -``` - -NOTA: Os módulos de classe embutidos `Sinatra::Test` e -`Sinatra::TestHarness` são depreciados na versão 0.9.2. - -## Sinatra::Base - Middleware, Bibliotecas e aplicativos modulares - -Definir sua aplicação em um nível superior de trabalho funciona bem para -micro aplicativos, mas tem consideráveis incovenientes na construção de -componentes reutilizáveis como um middleware Rack, metal Rails, -bibliotecas simples como um componente de servidor, ou mesmo extensões -Sinatra. A DSL de nível superior polui o espaço do objeto e assume um -estilo de configuração de micro aplicativos (exemplo: uma simples -arquivo de aplicação, diretórios `./public` e `./views`, logs, página de -detalhes de exceção, etc.). É onde o `Sinatra::Base` entra em jogo: - -``` ruby -require 'sinatra/base' - -class MinhaApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Ola mundo!' - end -end -``` - -A classe `MinhaApp` é um componente Rack independente que pode agir como -um middleware Rack, uma aplicação Rack, ou metal Rails. Você pode -utilizar ou executar esta classe com um arquivo rackup `config.ru`; -ou, controlar um componente de servidor fornecendo como biblioteca: - -``` ruby -MinhaApp.run! :host => 'localhost', :port => 9090 -``` - -Os métodos disponíveis para subclasses `Sinatra::Base` são exatamente como -aqueles disponíveis via a DSL de nível superior. Aplicações de nível -mais alto podem ser convertidas para componentes `Sinatra::Base` com duas -modificações: - -- Seu arquivo deve requerer `sinatra/base` ao invés de `sinatra`; - outra coisa, todos os métodos DSL do Sinatra são importados para o - espaço principal. - -- Coloque as rotas da sua aplicação, manipuladores de erro, filtros e - opções na subclasse de um `Sinatra::Base`. - -`Sinatra::Base` é um quadro branco. Muitas opções são desabilitadas por -padrão, incluindo o servidor embutido. Veja [Opções e -Configurações](http://sinatra.github.com/configuration.html) para -detalhes de opções disponíveis e seus comportamentos. - -SIDEBAR: A DSL de alto nível do Sinatra é implementada utilizando um simples -sistema de delegação. A classe `Sinatra::Application` – uma subclasse especial -da `Sinatra::Base` – recebe todos os `:get`, `:put`, `:post`, `:delete`, -`:before`, `:error`, `:not_found`, `:configure`, e `:set messages` enviados -para o alto nível. Dê uma olhada no código você mesmo: aqui está o -[Sinatra::Delegator -mixin](http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128) -sendo [incluido dentro de um espaço -principal](http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28) - -## Linha de Comando - -Aplicações Sinatra podem ser executadas diretamente: - -``` shell -ruby minhaapp.rb [-h] [-x] [-e AMBIENTE] [-p PORTA] [-o HOST] [-s SERVIDOR] -``` - -As opções são: - -``` --h # ajuda --p # define a porta (padrão é 4567) --o # define o host (padrão é 0.0.0.0) --e # define o ambiente (padrão é development) --s # especifica o servidor/manipulador rack (padrão é thin) --x # ativa o bloqueio (padrão é desligado) -``` - -## A última versão - -Se você gostaria de utilizar o código da última versão do Sinatra, crie -um clone local e execute sua aplicação com o diretório `sinatra/lib` no -`LOAD_PATH`: - -``` shell -cd minhaapp -git clone git://github.com/sinatra/sinatra.git -ruby -I sinatra/lib minhaapp.rb -``` - -Alternativamente, você pode adicionar o diretório do `sinatra/lib` no -`LOAD_PATH` do seu aplicativo: - -``` ruby -$LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib' -require 'rubygems' -require 'sinatra' - -get '/sobre' do - "Estou rodando a versão" + Sinatra::VERSION -end -``` - -Para atualizar o código do Sinatra no futuro: - -``` shell -cd meuprojeto/sinatra -git pull -``` - -## Mais - -- [Website do Projeto](http://www.sinatrarb.com/) - Documentação - adicional, novidades e links para outros recursos. - -- [Contribuir](http://www.sinatrarb.com/contributing) - Encontrar um - bug? Precisa de ajuda? Tem um patch? - -- [Acompanhar Questões](http://github.com/sinatra/sinatra/issues) - -- [Twitter](http://twitter.com/sinatra) - -- [Lista de Email](http://groups.google.com/group/sinatrarb/topics) - -- [IRC: \#sinatra](irc://chat.freenode.net/#sinatra) em - [freenode.net](http://freenode.net) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.pt-pt.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.pt-pt.md deleted file mode 100644 index 8dfddb5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.pt-pt.md +++ /dev/null @@ -1,791 +0,0 @@ -# Sinatra - -*Atenção: Este documento é apenas uma tradução da versão em inglês e -pode estar desatualizado.* - -Sinatra é uma -[DSL](http://pt.wikipedia.org/wiki/Linguagem_de_domínio_específico) para -criar rapidamente aplicações web em Ruby com o mínimo de esforço: - -``` ruby -# minhaapp.rb -require 'rubygems' -require 'sinatra' -get '/' do - 'Olá Mundo!' -end -``` - -Instale a gem e execute com: - -``` shell -sudo gem install sinatra -ruby minhaapp.rb -``` - -Aceda em: [localhost:4567](http://localhost:4567) - -## Rotas - -No Sinatra, uma rota é um metodo HTTP associado a uma URL correspondente -padrão. Cada rota é associada a um bloco: - -``` ruby -get '/' do - .. mostrar algo .. -end - -post '/' do - .. criar algo .. -end - -put '/' do - .. atualizar algo .. -end - -delete '/' do - .. apagar algo .. -end -``` - -Rotas são encontradas na ordem em que são definidas. A primeira rota que -é encontrada invoca o pedido. - -Padrões de rota podem incluir parâmetros nomeados, acessíveis através da -hash `params`: - -``` ruby -get '/ola/:nome' do - # corresponde a "GET /ola/foo" e "GET /ola/bar" - # params[:nome] é 'foo' ou 'bar' - "Olá #{params[:nome]}!" -end -``` - -Pode também aceder a parâmetros nomeados através do bloco de parâmetros: - -``` ruby -get '/ola/:nome' do |n| - "Olá #{n}!" -end -``` - -Padrões de rota podem também incluir parâmetros splat (asteriscos), -acessíveis através do array `params[:splat]`. - -``` ruby -get '/diga/*/ao/*' do - # corresponde a /diga/ola/ao/mundo - params[:splat] # => ["ola", "mundo"] -end - -get '/download/*.*' do - # corresponde a /download/pasta/do/arquivo.xml - params[:splat] # => ["pasta/do/arquivo", "xml"] -end -``` - -Rotas correspondem-se com expressões regulares: - -``` ruby -get %r{/ola/([\w]+)} do - "Olá, #{params[:captures].first}!" -end -``` - -Ou com um bloco de parâmetro: - -``` ruby -get %r{/ola/([\w]+)} do |c| - "Olá, #{c}!" -end -``` - -Rotas podem incluir uma variedade de condições correspondentes, por -exemplo, o agente usuário: - -``` ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "Você está a utilizar a versão #{params[:agent][0]} do Songbird." -end - -get '/foo' do - # Corresponde a um navegador não Songbird -end -``` - -## Arquivos estáticos - -Arquivos estáticos são disponibilizados a partir do directório -`./public`. Você pode especificar um local diferente através da opção -`:public_folder` - -``` ruby -set :public_folder, File.dirname(__FILE__) + '/estatico' -``` - -Note que o nome do directório público não é incluido no URL. Um arquivo -`./public/css/style.css` é disponibilizado como -`http://example.com/css/style.css`. - -## Views / Templates - -Templates presumem-se estar localizados sob o directório `./views`. Para -utilizar um directório de views diferente: - -``` ruby -set :views, File.dirname(__FILE__) + '/modelo' -``` - -Uma coisa importante a ser lembrada é que você sempre tem as referências -dos templates como símbolos, mesmo se eles estiverem num sub-directório -(nesse caso utilize `:'subdir/template'`). Métodos de renderização irão -processar qualquer string passada directamente para elas. - -### Haml Templates - -A gem/biblioteca haml é necessária para renderizar templates HAML: - -``` ruby -# É necessário requerir 'haml' na aplicação. -require 'haml' - -get '/' do - haml :index -end -``` - -Renderiza `./views/index.haml`. - -[Opções -Haml](http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options) -podem ser definidas globalmente através das configurações do sinatra, -veja [Opções e -Configurações](http://www.sinatrarb.com/configuration.html), e substitua -em uma requisição individual. - -``` ruby -set :haml, {:format => :html5 } # o formato padrão do Haml é :xhtml - -get '/' do - haml :index, :haml_options => {:format => :html4 } # substituido -end -``` - -### Erb Templates - -``` ruby -# É necessário requerir 'erb' na aplicação. -require 'erb' - -get '/' do - erb :index -end -``` - -Renderiza `./views/index.erb` - -### Erubis - -A gem/biblioteca erubis é necessária para renderizar templates erubis: - -``` ruby -# É necessário requerir 'erubis' na aplicação. -require 'erubis' - -get '/' do - erubis :index -end -``` - -Renderiza `./views/index.erubis` - -### Builder Templates - -A gem/biblioteca builder é necessária para renderizar templates builder: - -``` ruby -# É necessário requerir 'builder' na aplicação. -require 'builder' - -get '/' do - content_type 'application/xml', :charset => 'utf-8' - builder :index -end -``` - -Renderiza `./views/index.builder`. - -### Sass Templates - -A gem/biblioteca sass é necessária para renderizar templates sass: - -``` ruby -# É necessário requerir 'haml' ou 'sass' na aplicação. -require 'sass' - -get '/stylesheet.css' do - content_type 'text/css', :charset => 'utf-8' - sass :stylesheet -end -``` - -Renderiza `./views/stylesheet.sass`. - -[Opções -Sass](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options) -podem ser definidas globalmente através das configurações do sinatra, -veja [Opções e -Configurações](http://www.sinatrarb.com/configuration.html), e substitua -em uma requisição individual. - -``` ruby -set :sass, {:style => :compact } # o estilo padrão do Sass é :nested - -get '/stylesheet.css' do - content_type 'text/css', :charset => 'utf-8' - sass :stylesheet, :style => :expanded # substituido -end -``` - -### Less Templates - -A gem/biblioteca less é necessária para renderizar templates Less: - -``` ruby -# É necessário requerir 'less' na aplicação. -require 'less' - -get '/stylesheet.css' do - content_type 'text/css', :charset => 'utf-8' - less :stylesheet -end -``` - -Renderiza `./views/stylesheet.less`. - -### Templates Inline - -``` ruby -get '/' do - haml '%div.title Olá Mundo' -end -``` - -Renderiza a string, em uma linha, no template. - -### Acedendo a Variáveis nos Templates - -Templates são avaliados dentro do mesmo contexto que os manipuladores de -rota. Variáveis de instância definidas em rotas manipuladas são -directamente acedidas por templates: - -``` ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.nome' -end -``` - -Ou, especifique um hash explícito para variáveis locais: - -``` ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= foo.nome', :locals => { :foo => foo } -end -``` - -Isso é tipicamente utilizado quando renderizamos templates parciais -(partials) dentro de outros templates. - -### Templates Inline - -Templates podem ser definidos no final do arquivo fonte(.rb): - -``` ruby -require 'rubygems' -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Olá Mundo!!!!! -``` - -NOTA: Templates inline definidos no arquivo fonte são automaticamente -carregados pelo sinatra. Digite \`enable :inline\_templates\` se tem -templates inline no outro arquivo fonte. - -### Templates nomeados - -Templates também podem ser definidos utilizando o método top-level -`template`: - -``` ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Olá Mundo!' -end - -get '/' do - haml :index -end -``` - -Se existir um template com nome “layout”, ele será utilizado sempre que -um template for renderizado. Pode desactivar layouts usando -`:layout => false`. - -``` ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -## Helpers - -Use o método de alto nível `helpers` para definir métodos auxiliares -para utilizar em manipuladores de rotas e modelos: - -``` ruby -helpers do - def bar(nome) - "#{nome}bar" - end -end - -get '/:nome' do - bar(params[:nome]) -end -``` - -## Filtros - -Filtros Before são avaliados antes de cada requisição dentro do contexto -da requisição e podem modificar a requisição e a reposta. Variáveis de -instância definidas nos filtros são acedidas através de rotas e -templates: - -``` ruby -before do - @nota = 'Olá!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @nota #=> 'Olá!' - params[:splat] #=> 'bar/baz' -end -``` - -Filtros After são avaliados após cada requisição dentro do contexto da -requisição e também podem modificar o pedido e a resposta. Variáveis de -instância definidas nos filtros before e rotas são acedidas através dos -filtros after: - -``` ruby -after do - puts response.status -end -``` - -Filtros opcionalmente têm um padrão, fazendo com que sejam avaliados -somente se o caminho do pedido coincidir com esse padrão: - -``` ruby -before '/protected/*' do - autenticar! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -``` - -## Halting - -Para parar imediatamente uma requisição dentro de um filtro ou rota -utilize: - -``` ruby -halt -``` - -Pode também especificar o status ao parar… - -``` ruby -halt 410 -``` - -Ou com um corpo de texto… - -``` ruby -halt 'isto será o corpo de texto' -``` - -Ou também… - -``` ruby -halt 401, 'vamos embora!' -``` - -Com cabeçalhos… - -``` ruby -halt 402, {'Content-Type' => 'text/plain'}, 'revanche' -``` - -## Passing - -Dentro de uma rota, pode passar para a próxima rota correspondente -usando `pass`: - -``` ruby -get '/adivinhar/:quem' do - pass unless params[:quem] == 'Frank' - 'Apanhaste-me!' -end - -get '/adivinhar/*' do - 'Falhaste!' -end -``` - -O bloqueio da rota é imediatamente encerrado e o controle continua com a -próxima rota de parâmetro. Se o parâmetro da rota não for encontrado, um -404 é retornado. - -## Configuração - -Correndo uma vez, na inicialização, em qualquer ambiente: - -``` ruby -configure do - ... -end -``` - -Correndo somente quando o ambiente (`RACK_ENV` environment variável) é -definido para `:production`: - -``` ruby -configure :production do - ... -end -``` - -Correndo quando o ambiente é definido para `:production` ou `:test`: - -``` ruby -configure :production, :test do - ... -end -``` - -## Lidar com Erros - -Lida-se com erros no mesmo contexto das rotas e filtros before, o que -signifca que `haml`, `erb`, etc, estão disponíveis. - -### Não Encontrado - -Quando um `Sinatra::NotFound` exception é levantado, ou o código de -status da reposta é 404, o manipulador `not_found` é invocado: - -``` ruby -not_found do - 'Isto está longe de ser encontrado' -end -``` - -### Erro - -O manipulador `error` é invocado sempre que uma exceção é lançada a -partir de um bloco de rota ou um filtro. O objecto da exceção pode ser -obtido a partir da variável Rack `sinatra.error`: - -``` ruby -error do - 'Peço desculpa, houve um erro desagradável - ' + env['sinatra.error'].name -end -``` - -Erros personalizados: - -``` ruby -error MeuErroPersonalizado do - 'O que aconteceu foi...' + env['sinatra.error'].message -end -``` - -Então, se isso acontecer: - -``` ruby -get '/' do - raise MeuErroPersonalizado, 'alguma coisa desagradável' -end -``` - -O resultado será: - -``` -O que aconteceu foi...alguma coisa desagradável -``` - -Alternativamente, pode definir um manipulador de erro para um código de -status: - -``` ruby -error 403 do - 'Accesso negado' -end - -get '/secreto' do - 403 -end -``` - -Ou um range (alcance): - -``` ruby -error 400..510 do - 'Boom' -end -``` - -O Sinatra define os manipuladores especiais `not_found` e `error` quando -corre no ambiente de desenvolvimento. - -## Mime Types - -Quando utilizamos `send_file` ou arquivos estáticos pode ter mime types -Sinatra não entendidos. Use `mime_type` para os registar por extensão de -arquivos: - -``` ruby -mime_type :foo, 'text/foo' -``` - -Pode também utilizar isto com o helper `content_type`: - -``` ruby -content_type :foo -``` - -## Middleware Rack - -O Sinatra corre no [Rack](http://rack.rubyforge.org/), uma interface -padrão mínima para frameworks web em Ruby. Uma das capacidades mais -interessantes do Rack, para desenvolver aplicações, é o suporte de -“middleware” – componentes que residem entre o servidor e a aplicação, -monitorizando e/ou manipulando o pedido/resposta (request/response) HTTP -para providenciar varios tipos de funcionalidades comuns. - -O Sinatra torna a construção de pipelines do middleware Rack fácil a um -nível superior utilizando o método `use`: - -``` ruby -require 'sinatra' -require 'meu_middleware_personalizado' - -use Rack::Lint -use MeuMiddlewarePersonalizado - -get '/ola' do - 'Olá mundo' -end -``` - -A semântica de `use` é idêntica aquela definida para a DSL -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html) -(mais frequentemente utilizada para arquivos rackup). Por exemplo, o -método `use` aceita múltiplos argumentos/variáveis, bem como blocos: - -``` ruby -use Rack::Auth::Basic do |utilizador, senha| - utilizador == 'admin' && senha == 'secreto' -end -``` - -O Rack é distribuido com uma variedade de middleware padrões para logs, -debugs, rotas de URL, autenticação, e manipuladores de sessão.Sinatra -utiliza muitos desses componentes automaticamente dependendo da -configuração, por isso, tipicamente nao é necessário utilizar `use` -explicitamente. - -## Testando - -Testes no Sinatra podem ser escritos utilizando qualquer biblioteca ou -framework de teste baseados no Rack. -[Rack::Test](http://gitrdoc.com/brynary/rack-test) é recomendado: - -``` ruby -require 'minha_aplicacao_sinatra' -require 'rack/test' - -class MinhaAplicacaoTeste < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def meu_test_default - get '/' - assert_equal 'Ola Mundo!', last_response.body - end - - def teste_com_parametros - get '/atender', :name => 'Frank' - assert_equal 'Olá Frank!', last_response.bodymeet - end - - def test_com_ambiente_rack - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "Você está utilizando o Songbird!", last_response.body - end -end -``` - -NOTA: Os módulos de classe embutidos `Sinatra::Test` e -`Sinatra::TestHarness` são depreciados na versão 0.9.2. - -## Sinatra::Base - Middleware, Bibliotecas e aplicativos modulares - -Definir sua aplicação a um nível superior de trabalho funciona bem para -micro aplicativos, mas tem consideráveis incovenientes na construção de -componentes reutilizáveis como um middleware Rack, metal Rails, -bibliotecas simples como um componente de servidor, ou mesmo extensões -Sinatra. A DSL de nível superior polui o espaço do objeto e assume um -estilo de configuração de micro aplicativos (exemplo: um simples arquivo -de aplicação, directórios `./public` e `./views`, logs, página de detalhes -de excepção, etc.). É onde o Sinatra::Base entra em jogo: - -``` ruby -require 'sinatra/base' - -class MinhaApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Olá mundo!' - end -end -``` - -A classe MinhaApp é um componente Rack independente que pode utilizar -como um middleware Rack, uma aplicação Rack, ou metal Rails. Pode -utilizar ou executar esta classe com um arquivo rackup `config.ru`; -ou, controlar um componente de servidor fornecendo como biblioteca: - -``` ruby -MinhaApp.run! :host => 'localhost', :port => 9090 -``` - -Os métodos disponíveis para subclasses `Sinatra::Base` são exatamente como -aqueles disponíveis via a DSL de nível superior. Aplicações de nível -mais alto podem ser convertidas para componentes `Sinatra::Base` com duas -modificações: - -- Seu arquivo deve requerer `sinatra/base` ao invés de `sinatra`; - outra coisa, todos os métodos DSL do Sinatra são importados para o - espaço principal. - -- Coloque as rotas da sua aplicação, manipuladores de erro, filtros e - opções na subclasse de um `Sinatra::Base`. - -`Sinatra::Base` é um quadro branco. Muitas opções são desactivadas por -padrão, incluindo o servidor embutido. Veja [Opções e -Configurações](http://sinatra.github.com/configuration.html) para -detalhes de opções disponíveis e seus comportamentos. - -SIDEBAR: A DSL de alto nível do Sinatra é implementada utilizando um simples -sistema de delegação. A classe `Sinatra::Application` – uma subclasse especial -da `Sinatra::Base` – recebe todos os `:get`, `:put`, `:post`, `:delete`, -`:before`, `:error`, `:not_found`, `:configure`, e `:set` messages enviados -para o alto nível. Dê você mesmo uma vista de olhos ao código: aqui está o -[Sinatra::Delegator -mixin](http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128) -sendo [incluido dentro de um espaço -principal](http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28) - -## Linha de Comandos - -As aplicações Sinatra podem ser executadas directamente: - -``` shell -ruby minhaapp.rb [-h] [-x] [-e AMBIENTE] [-p PORTA] [-o HOST] [-s SERVIDOR] -``` - -As opções são: - -``` --h # ajuda --p # define a porta (padrão é 4567) --o # define o host (padrão é 0.0.0.0) --e # define o ambiente (padrão é development) --s # especifica o servidor/manipulador rack (padrão é thin) --x # activa o bloqueio (padrão é desligado) -``` - -## A última versão - -Se gostaria de utilizar o código da última versão do Sinatra, crie um -clone local e execute sua aplicação com o directório `sinatra/lib` no -`LOAD_PATH`: - -``` shell -cd minhaapp -git clone git://github.com/sinatra/sinatra.git -ruby -I sinatra/lib minhaapp.rb -``` - -Alternativamente, pode adicionar o directório do `sinatra/lib` no -`LOAD_PATH` do seu aplicativo: - -``` ruby -$LOAD_PATH.unshift File.dirname(__FILE__) + '/sinatra/lib' -require 'rubygems' -require 'sinatra' - -get '/sobre' do - "Estou correndo a versão" + Sinatra::VERSION -end -``` - -Para actualizar o código do Sinatra no futuro: - -``` shell -cd meuprojeto/sinatra -git pull -``` - -## Mais - -- [Website do Projeto](http://www.sinatrarb.com/) - Documentação - adicional, novidades e links para outros recursos. - -- [Contribuir](http://www.sinatrarb.com/contributing) - Encontrou um - bug? Precisa de ajuda? Tem um patch? - -- [Acompanhar Questões](http://github.com/sinatra/sinatra/issues) - -- [Twitter](http://twitter.com/sinatra) - -- [Lista de Email](http://groups.google.com/group/sinatrarb/topics) - -- [IRC: \#sinatra](irc://chat.freenode.net/#sinatra) em - [freenode.net](http://freenode.net) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ru.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ru.md deleted file mode 100644 index af7a66c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.ru.md +++ /dev/null @@ -1,2799 +0,0 @@ -# Sinatra - -*Внимание: Этот документ является переводом английской версии и может быть -устаревшим* - -Sinatra — это предметно-ориентированный каркас -([DSL](http://ru.wikipedia.org/wiki/Предметно-ориентированный_язык_программирования)) -для быстрого создания функциональных веб-приложений на Ruby с минимумом усилий: - -```ruby -# myapp.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -Установите gem: - -``` -gem install sinatra -``` - -и запустите приложение с помощью: - -``` -ruby myapp.rb -``` - -Оцените результат: http://localhost:4567 - -Рекомендуется также установить Thin, сделать это можно командой: `gem install -thin`. Thin — это более производительный и функциональный сервер для -разработки приложений на Sinatra. - -## Маршруты - -В Sinatra маршрут — это пара: <HTTP метод> и <шаблон URL>. Каждый маршрут -связан с блоком кода: - -```ruby -get '/' do - # .. что-то показать .. -end - -post '/' do - # .. что-то создать .. -end - -put '/' do - # .. что-то заменить .. -end - -patch '/' do - # .. что-то изменить .. -end - -delete '/' do - # .. что-то удалить .. -end - -options '/' do - # .. что-то ответить .. -end - -link '/' do - .. что-то подключить .. -end - -unlink '/' do - .. что-то отключить .. -end -``` - -Маршруты сверяются с запросом в порядке очередности их записи в файле -приложения. Первый же совпавший с запросом маршрут и будет вызван. - -Шаблоны маршрутов могут включать в себя именованные параметры, доступные в xэше -`params`: - -```ruby -get '/hello/:name' do - # соответствует "GET /hello/foo" и "GET /hello/bar", - # где params[:name] 'foo' или 'bar' - "Hello #{params[:name]}!" -end -``` - -Также можно использовать именованные параметры в качестве переменных блока: - -```ruby -get '/hello/:name' do |n| - "Hello #{n}!" -end -``` - -Шаблоны маршрутов также могут включать в себя splat (или '*' маску, -обозначающую любой символ) параметры, доступные в массиве `params[:splat]`: - -```ruby -get '/say/*/to/*' do - # соответствует /say/hello/to/world - params[:splat] # => ["hello", "world"] -end - -get '/download/*.*' do - # соответствует /download/path/to/file.xml - params[:splat] # => ["path/to/file", "xml"] -end -``` - -Или с параметрами блока: - -```ruby -get '/download/*.*' do |path, ext| - [path, ext] # => ["path/to/file", "xml"] -end -``` - -Регулярные выражения в качестве шаблонов маршрутов: - -```ruby -get %r{/hello/([\w]+)} do - "Hello, #{params[:captures].first}!" -end -``` - -Или с параметром блока: - -```ruby -get %r{/hello/([\w]+)} do |c| - "Hello, #{c}!" -end -``` - -Шаблоны маршрутов могут иметь необязательные параметры: - -```ruby -get '/posts.?:format?' do - # соответствует "GET /posts", "GET /posts.json", "GET /posts.xml" и т.д. -end -``` - -Кстати, если вы не отключите защиту от обратного пути в директориях (path -traversal, см. ниже), путь запроса может быть изменен до начала поиска -подходящего маршрута. - -### Условия - -Маршруты могут включать различные условия совпадений, например, клиентское -приложение (user agent): - -```ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "You're using Songbird version #{params[:agent][0]}" -end - -get '/foo' do - # соответствует не-songbird браузерам -end -``` - -Другими доступными условиями являются `host_name` и `provides`: - -```ruby -get '/', :host_name => /^admin\./ do - "Admin Area, Access denied!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -``` - -Вы можете задать собственные условия: - -```ruby -set(:probability) { |value| condition { rand <= value } } - -get '/win_a_car', :probability => 0.1 do - "You won!" -end - -get '/win_a_car' do - "Sorry, you lost." -end -``` - -Для условия, которое принимает несколько параметров, используйте звездочку: - -```ruby -set(:auth) do |*roles| # <- обратите внимание на звездочку - condition do - unless logged_in? && roles.any? {|role| current_user.in_role? role } - redirect "/login/", 303 - end - end -end - -get "/my/account/", :auth => [:user, :admin] do - "Your Account Details" -end - -get "/only/admin/", :auth => :admin do - "Only admins are allowed here!" -end -``` - -### Возвращаемые значения - -Возвращаемое значение блока маршрута ограничивается телом ответа, которое -будет передано HTTP клиенту, или следующей "прослойкой" (middleware) в Rack -стеке. Чаще всего это строка, как в примерах выше. Но также приемлемы и -другие значения. - -Вы можете вернуть любой объект, который будет либо корректным Rack ответом, -объектом Rack body, либо кодом состояния HTTP: - -* массив с тремя переменными: `[код (Fixnum), заголовки (Hash), тело ответа - (должно отвечать на #each)]`; -* массив с двумя переменными: `[код (Fixnum), тело ответа (должно отвечать - на #each)]`; -* объект, отвечающий на `#each`, который передает только строковые типы - данных в этот блок; -* Fixnum, представляющий код состояния HTTP. - - -Таким образом, легко можно реализовать, например, поточный пример: - -```ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -``` - -Вы также можете использовать метод `stream` (описываемый ниже), чтобы -уменьшить количество дублируемого кода и держать логику стриминга прямо в -маршруте. - -### Собственные детекторы совпадений для маршрутов - -Как показано выше, Sinatra поставляется со встроенной поддержкой строк и -регулярных выражений в качестве шаблонов URL. Но и это еще не все. Вы можете -легко определить свои собственные детекторы совпадений (matchers) для -маршрутов: - -```ruby -class AllButPattern - Match = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Match.new([]) - end - - def match(str) - @captures unless @except === str - end -end - -def all_but(pattern) - AllButPattern.new(pattern) -end - -get all_but("/index") do - # ... -end -``` - -Заметьте, что предыдущий пример, возможно, чересчур усложнен, потому что он -может быть реализован так: - -```ruby -get // do - pass if request.path_info == "/index" - # ... -end -``` - -Или с использованием негативного просмотра вперед: - -```ruby -get %r{^(?!/index$)} do - # ... -end -``` - -## Статические файлы - -Статические файлы отдаются из `./public` директории. Вы можете указать другое -место, используя опцию `:public_folder`: - -```ruby -set :public_folder, File.dirname(__FILE__) + '/static' -``` - -Учтите, что имя директории со статическими файлами не включено в URL. -Например, файл `./public/css/style.css` будет доступен как -`http://example.com/css/style.css`. - -Используйте опцию `:static_cache_control` (см. ниже), чтобы добавить заголовок -`Cache-Control`. - -## Представления / Шаблоны - -Каждый шаблонизатор представлен своим собственным методом. Эти методы попросту -возвращают строку: - -```ruby -get '/' do - erb :index -end -``` - -Отобразит `views/index.erb`. - -Вместо имени шаблона вы так же можете передавать непосредственно само -содержимое шаблона: - -```ruby -get '/' do - code = "<%= Time.now %>" - erb code -end -``` - -Эти методы принимают второй аргумент, хеш с опциями: - -```ruby -get '/' do - erb :index, :layout => :post -end -``` - -Отобразит `views/index.erb`, вложенным в `views/post.erb` (по умолчанию: -`views/layout.erb`, если существует). - -Любые опции, не понимаемые Sinatra, будут переданы в шаблонизатор: - -```ruby -get '/' do - haml :index, :format => :html5 -end -``` - -Вы также можете задавать опции для шаблонизаторов в общем: - -```ruby -set :haml, :format => :html5 - -get '/' do - haml :index -end -``` - -Опции, переданные в метод, переопределяют опции, заданные с помощью `set`. - -Доступные опции: - -
-
locals
-
- Список локальных переменных, передаваемых в документ. - Например: erb "<%= foo %>", :locals => {:foo => "bar"} -
- -
default_encoding
-
- Кодировка, которую следует использовать, если не удалось определить - оригинальную. По умолчанию: settings.default_encoding. -
- -
views
-
- Директория с шаблонами. По умолчанию: settings.views. -
- -
layout
-
- Использовать или нет лэйаут (true или false). Если же значение Symbol, - то указывает, какой шаблон использовать в качестве лэйаута. Например: - erb :index, :layout => !request.xhr? -
- -
content_type
-
- Content-Type отображенного шаблона. По умолчанию: задается шаблонизатором. -
- -
scope
-
- Область видимости, в которой рендерятся шаблоны. По умолчанию: экземпляр - приложения. Если вы измените эту опцию, то переменные экземпляра и - методы-помощники станут недоступными в ваших шаблонах. -
- -
layout_engine
-
- Шаблонизатор, который следует использовать для отображения лэйаута. - Полезная опция для шаблонизаторов, в которых нет никакой поддержки - лэйаутов. По умолчанию: тот же шаблонизатор, что используется и для самого - шаблона. Пример: set :rdoc, :layout_engine => :erb -
-
- -По умолчанию считается, что шаблоны находятся в директории `./views`. Чтобы -использовать другую директорию с шаблонами: - -```ruby -set :views, settings.root + '/templates' -``` - -Важное замечание: вы всегда должны ссылаться на шаблоны с помощью символов -(Symbol), даже когда они в поддиректории (в этом случае используйте -`:'subdir/template'`). Вы должны использовать символы, потому что иначе -шаблонизаторы попросту отображают любые строки, переданные им. - -### Буквальные шаблоны - -```ruby -get '/' do - haml '%div.title Hello World' -end -``` - -Отобразит шаблон, переданный строкой. - -### Доступные шаблонизаторы - -Некоторые языки шаблонов имеют несколько реализаций. Чтобы указать, какую -реализацию использовать, вам следует просто подключить нужную библиотеку: - -```ruby -require 'rdiscount' # или require 'bluecloth' -get('/') { markdown :index } -``` - -#### Haml шаблоны - - - - - - - - - - - - - - -
Зависимостиhaml
Расширения файлов.haml
Примерhaml :index, :format => :html5
- -#### Erb шаблоны - - - - - - - - - - - - - - -
Зависимости - erubis - или erb (включен в Ruby) -
Расширения файлов.erb, .rhtml or .erubis (только Erubis)
Примерerb :index
- -#### Builder шаблоны - - - - - - - - - - - - - - -
Зависимости - builder -
Расширения файлов.builder
Примерbuilder { |xml| xml.em "hi" }
- -Блок также используется и для встроенных шаблонов (см. пример). - -#### Nokogiri шаблоны - - - - - - - - - - - - - - -
Зависимостиnokogiri
Расширения файлов.nokogiri
Примерnokogiri { |xml| xml.em "hi" }
- -Блок также используется и для встроенных шаблонов (см. пример). - -#### Sass шаблоны - - - - - - - - - - - - - - -
Зависимостиsass
Расширения файлов.sass
Примерsass :stylesheet, :style => :expanded
- -#### SCSS шаблоны - - - - - - - - - - - - - - -
Зависимостиsass
Расширения файлов.scss
Примерscss :stylesheet, :style => :expanded
- -#### Less шаблоны - - - - - - - - - - - - - - -
Зависимостиless
Расширения файлов.less
Примерless :stylesheet
- -#### Liquid шаблоны - - - - - - - - - - - - - - -
Зависимостиliquid
Расширения файлов.liquid
Примерliquid :index, :locals => { :key => 'value' }
- -Так как в Liquid шаблонах невозможно вызывать методы из Ruby (кроме `yield`), то -вы почти всегда будете передавать в шаблон локальные переменные. - -#### Markdown шаблоны - - - - - - - - - - - - - - -
Зависимости - Любая из библиотек: - RDiscount, - RedCarpet, - BlueCloth, - kramdown, - maruku -
Расширения файлов.markdown, .mkd and .md
Примерmarkdown :index, :layout_engine => :erb
- -В Markdown невозможно вызывать методы или передавать локальные переменные. -Следовательно, вам, скорее всего, придется использовать этот шаблон совместно -с другим шаблонизатором: - -```ruby -erb :overview, :locals => { :text => markdown(:introduction) } -``` - -Заметьте, что вы можете вызывать метод `markdown` из других шаблонов: - -```ruby -%h1 Hello From Haml! -%p= markdown(:greetings) -``` - -Вы не можете вызывать Ruby из Markdown, соответственно, вы не можете -использовать лэйауты на Markdown. Тем не менее, есть возможность использовать -один шаблонизатор для отображения шаблона, а другой для лэйаута с помощью -опции `:layout_engine`. - -#### Textile шаблоны - - - - - - - - - - - - - - -
ЗависимостиRedCloth
Расширения файлов.textile
Примерtextile :index, :layout_engine => :erb
- -В Textile невозможно вызывать методы или передавать локальные переменные. -Следовательно, вам, скорее всего, придется использовать этот шаблон совместно -с другим шаблонизатором: - -```ruby -erb :overview, :locals => { :text => textile(:introduction) } -``` - -Заметьте, что вы можете вызывать метод `textile` из других шаблонов: - -```ruby -%h1 Hello From Haml! -%p= textile(:greetings) -``` - -Вы не можете вызывать Ruby из Textile, соответственно, вы не можете -использовать лэйауты на Textile. Тем не менее, есть возможность использовать -один шаблонизатор для отображения шаблона, а другой для лэйаута с помощью -опции `:layout_engine`. - -#### RDoc шаблоны - - - - - - - - - - - - - - -
ЗависимостиRDoc
Расширения файлов.rdoc
Примерrdoc :README, :layout_engine => :erb
- -В RDoc невозможно вызывать методы или передавать локальные переменные. -Следовательно, вам, скорее всего, придется использовать этот шаблон совместно -с другим шаблонизатором: - -```ruby -erb :overview, :locals => { :text => rdoc(:introduction) } -``` - -Заметьте, что вы можете вызывать метод `rdoc` из других шаблонов: - -```ruby -%h1 Hello From Haml! -%p= rdoc(:greetings) -``` - -Вы не можете вызывать Ruby из RDoc, соответственно, вы не можете использовать -лэйауты на RDoc. Тем не менее, есть возможность использовать один шаблонизатор -для отображения шаблона, а другой для лэйаута с помощью опции -`:layout_engine`. - -#### AsciiDoc шаблоны - - - - - - - - - - - - - - -
ЗависимостиAsciidoctor
Расширения файлов.asciidoc, .adoc и .ad
Примерasciidoc :README, :layout_engine => :erb
- -Так как в AsciiDoc шаблонах невозможно вызывать методы из Ruby напрямую, то вы -почти всегда будете передавать в шаблон локальные переменные. - -#### Radius шаблоны - - - - - - - - - - - - - - -
ЗависимостиRadius
Расширения файлов.radius
Примерradius :index, :locals => { :key => 'value' }
- -Так как в Radius шаблонах невозможно вызывать методы из Ruby напрямую, то вы -почти всегда будете передавать в шаблон локальные переменные. - -#### Markaby шаблоны - - - - - - - - - - - - - - -
ЗависимостиMarkaby
Расширения файлов.mab
Примерmarkaby { h1 "Welcome!" }
- -Блок также используется и для встроенных шаблонов (см. пример). - -#### RABL шаблоны - - - - - - - - - - - - - - -
ЗависимостиRabl
Расширения файлов.rabl
Примерrabl :index
- -#### Slim шаблоны - - - - - - - - - - - - - - -
ЗависимостиSlim Lang
Расширения файлов.slim
Примерslim :index
- -#### Creole шаблоны - - - - - - - - - - - - - - -
ЗависимостиCreole
Расширения файлов.creole
Примерcreole :wiki, :layout_engine => :erb
- -В Creole невозможно вызывать методы или передавать локальные переменные. -Следовательно, вам, скорее всего, придется использовать этот шаблон совместно -с другим шаблонизатором: - -```ruby -erb :overview, :locals => { :text => creole(:introduction) } -``` - -Заметьте, что вы можете вызывать метод `creole` из других шаблонов: - -```ruby -%h1 Hello From Haml! -%p= creole(:greetings) -``` - -Вы не можете вызывать Ruby из Creole, соответственно, вы не можете -использовать лэйауты на Creole. Тем не менее, есть возможность использовать -один шаблонизатор для отображения шаблона, а другой для лэйаута с помощью -опции `:layout_engine`. - -#### MediaWiki шаблоны - - - - - - - - - - - - - - -
ЗависимостиWikiCloth
Расширения файлов.mediawiki и .mw
Примерmediawiki :wiki, :layout_engine => :erb
- -В разметке MediaWiki невозможно вызывать методы или передавать локальные переменные. -Следовательно, вам, скорее всего, придется использовать этот шаблон совместно -с другим шаблонизатором: - -```ruby -erb :overview, :locals => { :text => mediawiki(:introduction) } -``` - -Заметьте, что вы можете вызывать метод `mediawiki` из других шаблонов: - -```ruby -%h1 Hello From Haml! -%p= mediawiki(:greetings) -``` - -Вы не можете вызывать Ruby из MediaWiki, соответственно, вы не можете -использовать лэйауты на MediaWiki. Тем не менее, есть возможность использовать -один шаблонизатор для отображения шаблона, а другой для лэйаута с помощью -опции `:layout_engine`. - -#### CoffeeScript шаблоны - - - - - - - - - - - - - - -
Зависимости - - CoffeeScript - и способ - - запускать JavaScript - -
Расширения файлов.coffee
Примерcoffee :index
- -#### Yajl шаблоны - - - - - - - - - - - - - - -
Зависимостиyajl-ruby
Расширения файлов.yajl
Пример - - yajl :index, - :locals => { :key => 'qux' }, - :callback => 'present', - :variable => 'resource' - -
- -Содержимое шаблона интерпретируется как код на Ruby, а результирующая -переменная json затем конвертируется с помощью `#to_json`. - -```ruby -json = { :foo => 'bar' } -json[:baz] = key -``` - -Опции `:callback` и `:variable` используются для "декорирования" итогового -объекта. - -```ruby -var resource = {"foo":"bar","baz":"qux"}; present(resource); -``` - -#### WLang шаблоны - - - - - - - - - - - - - - -
Зависимостиwlang
Расширения файлов.wlang
Примерwlang :index, :locals => { :key => 'value' }
- -Так как в WLang шаблонах невозможно вызывать методы из Ruby напрямую (за -исключением `yield`), то вы почти всегда будете передавать в шаблон локальные -переменные. - -### Доступ к переменным в шаблонах - -Шаблоны интерпретируются в том же контексте, что и обработчики маршрутов. -Переменные экземпляра, установленные в процессе обработки маршрутов, будут -доступны напрямую в шаблонах: - -```ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.name' -end -``` - -Либо установите их через хеш локальных переменных: - -```ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= bar.name', :locals => { :bar => foo } -end -``` - -Это обычный подход, когда шаблоны рендерятся как части других шаблонов. - -### Шаблоны с `yield` и вложенные раскладки (layout) - -Раскладка (layout) обычно представляет собой шаблон, который исполняет -`yield`. -Такой шаблон может быть либо использован с помощью опции `:template`, -как описано выше, либо он может быть дополнен блоком: - -```ruby - erb :post, :layout => false do - erb :index - end -``` - -Эти инструкции в основном эквивалентны `erb :index, :layout => :post`. - -Передача блоков интерпретирующим шаблоны методам наиболее полезна для -создания вложенных раскладок: - -```ruby - erb :main_layout, :layout => false do - erb :admin_layout do - erb :user - end - end -``` - -Это же самое может быть сделано короче: - -```ruby - erb :admin_layout, :layout => :main_layout do - erb :user - end -``` - -В настоящее время, следующие интерпретирующие шаблоны методы -принимают блок: -`erb`, `haml`, `liquid`, `slim `, `wlang`. -Общий метод заполнения шаблонов `render` также принимает блок. - -### Включённые шаблоны - -Шаблоны также могут быть определены в конце исходного файла: - -```ruby -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Hello world. -``` - -Заметьте: включённые шаблоны, определенные в исходном файле, который подключил -Sinatra, будут загружены автоматически. Вызовите `enable :inline_templates` -напрямую, если используете включённые шаблоны в других файлах. - -### Именованные шаблоны - -Шаблоны также могут быть определены при помощи `template` метода: - -```ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Hello World!' -end - -get '/' do - haml :index -end -``` - -Если шаблон с именем "layout" существует, то он будет использоваться каждый -раз при рендеринге. Вы можете отключать лэйаут в каждом конкретном случае с -помощью `:layout => false` или отключить его для всего приложения: `set :haml, -:layout => false`: - -```ruby -get '/' do - haml :index, :layout => !request.xhr? -end -``` - -### Привязка файловых расширений - -Чтобы связать расширение файла с движком рендеринга, используйте -`Tilt.register`. Например, если вы хотите использовать расширение `tt` для -шаблонов Textile: - -```ruby -Tilt.register :tt, Tilt[:textile] -``` - -### Добавление собственного движка рендеринга - -Сначала зарегистрируйте свой движок в Tilt, а затем создайте метод, отвечающий -за рендеринг: - -```ruby -Tilt.register :myat, MyAwesomeTemplateEngine - -helpers do - def myat(*args) render(:myat, *args) end -end - -get '/' do - myat :index -end -``` - -Отобразит `./views/index.myat`. Чтобы узнать больше о Tilt, смотрите -https://github.com/rtomayko/tilt - -## Фильтры - -`before`-фильтры выполняются перед каждым запросом в том же контексте, что и -маршруты, и могут изменять как запрос, так и ответ на него. Переменные -экземпляра, установленные в фильтрах, доступны в маршрутах и шаблонах: - -```ruby -before do - @note = 'Hi!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @note #=> 'Hi!' - params[:splat] #=> 'bar/baz' -end -``` - -`after`-фильтры выполняются после каждого запроса в том же контексте -и могут изменять как запрос, так и ответ на него. Переменные -экземпляра, установленные в `before`-фильтрах и маршрутах, будут доступны в -`after`-фильтрах: - -```ruby -after do - puts response.status -end -``` - -Заметьте: если вы используете метод `body`, а не просто возвращаете строку из -маршрута, то тело ответа не будет доступно в `after`-фильтрах, так как оно -будет сгенерировано позднее. - -Фильтры могут использовать шаблоны URL и будут интерпретированы, только если -путь запроса совпадет с этим шаблоном: - -```ruby -before '/protected/*' do - authenticate! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -``` - -Как и маршруты, фильтры могут использовать условия: - -```ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'example.com' do - # ... -end -``` - -## Методы-помощники - -Используйте метод `helpers`, чтобы определить методы-помощники, которые в -дальнейшем можно будет использовать в обработчиках маршрутов и шаблонах: - -```ruby -helpers do - def bar(name) - "#{name}bar" - end -end - -get '/:name' do - bar(params[:name]) -end -``` - -Также методы-помощники могут быть заданы в отдельных модулях: - -```ruby -module FooUtils - def foo(name) "#{name}foo" end -end - -module BarUtils - def bar(name) "#{name}bar" end -end - -helpers FooUtils, BarUtils -``` - -Эффект равносилен включению модулей в класс приложения. - -### Использование сессий - -Сессия используется, чтобы сохранять состояние между запросами. Если эта опция -включена, то у вас будет один хеш сессии на одну пользовательскую сессию: - -```ruby -enable :sessions - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -Заметьте, что при использовании `enable :sessions` все данные сохраняются в -куках (cookies). Это может быть не совсем то, что вы хотите (например, -сохранение больших объемов данных увеличит ваш трафик). В таком случае вы -можете использовать альтернативную Rack "прослойку" (middleware), реализующую -механизм сессий. Для этого *не надо* вызывать `enable :sessions`, вместо этого -следует подключить ее так же, как и любую другую "прослойку": - -```ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -``` - -Для повышения безопасности данные сессии в куках подписываются секретным -ключом. Секретный ключ генерируется Sinatra. Тем не менее, так как этот ключ -будет меняться с каждым запуском приложения, вы, возможно, захотите установить -ключ вручную, чтобы у всех экземпляров вашего приложения был один и тот же -ключ: - -```ruby -set :session_secret, 'super secret' -``` - -Если вы хотите больше настроек для сессий, вы можете задать их, передав хеш -опций в параметр `sessions`: - -```ruby -set :sessions, :domain => 'foo.com' -``` - -Чтобы сделать сессию доступной другим приложениям, размещенным на поддоменах -foo.com, добавьте *.* перед доменом: - -``` ruby -set :sessions, :domain => '.foo.com' -``` - -### Прерывание - -Чтобы незамедлительно прервать обработку запроса внутри фильтра или маршрута, -используйте: - -```ruby -halt -``` - -Можно также указать статус при прерывании: - -```ruby -halt 410 -``` - -Тело: - -```ruby -halt 'this will be the body' -``` - -И то, и другое: - -```ruby -halt 401, 'go away!' -``` - -Можно указать заголовки: - -```ruby -halt 402, {'Content-Type' => 'text/plain'}, 'revenge' -``` - -И, конечно, можно использовать шаблоны с `halt`: - -```ruby -halt erb(:error) -``` - -### Передача - -Маршрут может передать обработку запроса следующему совпадающему маршруту, -используя `pass`: - -```ruby -get '/guess/:who' do - pass unless params[:who] == 'Frank' - 'You got me!' -end - -get '/guess/*' do - 'You missed!' -end -``` - -Блок маршрута сразу же прерывается, и контроль переходит к следующему -совпадающему маршруту. Если соответствующий маршрут не найден, то ответом на -запрос будет 404. - -### Вызов другого маршрута - -Иногда `pass` не подходит, например, если вы хотите получить результат вызова -другого обработчика маршрута. В таком случае просто используйте `call`: - -```ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do - "bar" -end -``` - -Заметьте, что в предыдущем примере можно облегчить тестирование и повысить -производительность, перенеся `"bar"` в метод-помощник, используемый и в -`/foo`, и в `/bar`. - -Если вы хотите, чтобы запрос был отправлен в тот же экземпляр приложения, а не -в его копию, используйте `call!` вместо `call`. - -Если хотите узнать больше о `call`, смотрите спецификацию Rack. - -### Задание тела, кода и заголовков ответа - -Хорошим тоном является установка кода состояния HTTP и тела ответа в -возвращаемом значении обработчика маршрута. Тем не менее, в некоторых -ситуациях вам, возможно, понадобится задать тело ответа в произвольной точке -потока исполнения. Вы можете сделать это с помощью метода-помощника `body`. -Если вы задействуете метод `body`, то вы можете использовать его и в -дальнейшем, чтобы получить доступ к телу ответа. - -```ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -``` - -Также можно передать блок в метод `body`, который затем будет вызван -обработчиком Rack (такой подход может быть использован для реализации -поточного ответа, см. "Возвращаемые значения"). - -Аналогично вы можете установить код ответа и его заголовки: - -```ruby -get '/foo' do - status 418 - headers \ - "Allow" => "BREW, POST, GET, PROPFIND, WHEN", - "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - body "I'm a tea pot!" -end -``` - -Как и `body`, методы `headers` и `status`, вызванные без аргументов, -возвращают свои текущие значения. - -### Стриминг ответов - -Иногда требуется начать отправлять данные клиенту прямо в процессе -генерирования частей этих данных. В особых случаях требуется постоянно -отправлять данные до тех пор, пока клиент не закроет соединение. Вы можете -использовать метод `stream` вместо написания собственных "оберток". - -```ruby -get '/' do - stream do |out| - out << "It's gonna be legen -\n" - sleep 0.5 - out << " (wait for it) \n" - sleep 1 - out << "- dary!\n" - end -end -``` - -Что позволяет вам реализовать стриминговые API, -[Server Sent Events](http://dev.w3.org/html5/eventsource/), -и может служить основой для [WebSockets](http://en.wikipedia.org/wiki/WebSocket). -Также такой подход можно использовать для увеличения производительности в случае, -когда какая-то часть контента зависит от медленного ресурса. - -Заметьте, что возможности стриминга, особенно количество одновременно -обслуживаемых запросов, очень сильно зависят от используемого веб-сервера. -Некоторые серверы, например, WEBRick, могут и вовсе не поддерживать стриминг. -Если сервер не поддерживает стриминг, то все данные будут отправлены за один -раз сразу после того, как блок, переданный в `stream`, завершится. Стриминг -вообще не работает при использовании Shotgun. - -Если метод используется с параметром `keep_open`, то он не будет вызывать -`close` у объекта потока, что позволит вам закрыть его позже в любом другом -месте. Это работает только с событийными серверами, например, с Thin и -Rainbows. Другие же серверы все равно будут закрывать поток: - -```ruby -# long polling - -set :server, :thin -connections = [] - -get '/subscribe' do - # регистрация клиента - stream(:keep_open) { |out| connections << out } - - # удаление "мертвых клиентов" - connections.reject!(&:closed?) - - # допуск - "subscribed" -end - -post '/message' do - connections.each do |out| - # уведомить клиента о новом сообщении - out << params[:message] << "\n" - - # указать клиенту на необходимость снова соединиться - out.close - end - - # допуск - "message received" -end -``` - -### Логирование - -В области видимости запроса метод `logger` предоставляет доступ к экземпляру -`Logger`: - -```ruby -get '/' do - logger.info "loading data" - # ... -end -``` - -Этот логер автоматически учитывает ваши настройки логирования в Rack. Если -логирование выключено, то этот метод вернет пустой (dummy) объект, поэтому вы -можете смело использовать его в маршрутах и фильтрах. - -Заметьте, что логирование включено по умолчанию только для -`Sinatra::Application`, а если ваше приложение — подкласс `Sinatra::Base`, то -вы, наверное, захотите включить его вручную: - -```ruby -class MyApp < Sinatra::Base - configure :production, :development do - enable :logging - end -end -``` - -Чтобы избежать использования любой логирующей "прослойки", задайте опции -`logging` значение `nil`. Тем не менее, не забывайте, что в такой ситуации -`logger` вернет `nil`. Чаще всего так делают, когда задают свой собственный -логер. Sinatra будет использовать то, что находится в `env['rack.logger']`. - -### Mime-типы - -Когда вы используете `send_file` или статические файлы, у вас могут быть -mime-типы, которые Sinatra не понимает по умолчанию. Используйте `mime_type` -для их регистрации по расширению файла: - -```ruby -configure do - mime_type :foo, 'text/foo' -end -``` - -Вы также можете использовать это в `content_type` методе-помощнике: - -```ruby -get '/' do - content_type :foo - "foo foo foo" -end -``` - -### Генерирование URL - -Чтобы сформировать URL, вам следует использовать метод `url`, например, в Haml: - -```ruby -%a{:href => url('/foo')} foo -``` - -Этот метод учитывает обратные прокси и маршрутизаторы Rack, если они -присутствуют. - -Наряду с `url` вы можете использовать `to` (смотрите пример ниже). - -### Перенаправление (редирект) - -Вы можете перенаправить браузер пользователя с помощью метода `redirect`: - -```ruby -get '/foo' do - redirect to('/bar') -end -``` - -Любые дополнительные параметры используются по аналогии с аргументами метода -`halt`: - -```ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'wrong place, buddy' -``` - -Вы также можете перенаправить пользователя обратно, на страницу, с которой он -пришел, с помощью `redirect back`: - -```ruby -get '/foo' do - "do something" -end - -get '/bar' do - do_something - redirect back -end -``` - -Чтобы передать какие-либо параметры вместе с перенаправлением, либо добавьте -их в строку запроса: - -```ruby -redirect to('/bar?sum=42') -``` - -либо используйте сессию: - -```ruby -enable :sessions - -get '/foo' do - session[:secret] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secret] -end -``` - -### Управление кэшированием - -Установка корректных заголовков — основа правильного HTTP кэширования. - -Вы можете легко выставить заголовок Cache-Control таким образом: - -```ruby -get '/' do - cache_control :public - "cache it!" -end -``` - -Совет: задавайте кэширование в `before`-фильтре: - -```ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -``` - -Если вы используете метод `expires` для задания соответствующего заголовка, то -`Cache-Control` будет выставлен автоматически: - -```ruby -before do - expires 500, :public, :must_revalidate -end -``` - -Чтобы как следует использовать кэширование, вам следует подумать об -использовании `etag` или `last_modified`. Рекомендуется использовать эти -методы-помощники *до* выполнения ресурсоемких вычислений, так как они -немедленно отправят ответ клиенту, если текущая версия уже есть в их кэше: - -```ruby -get '/article/:id' do - @article = Article.find params[:id] - last_modified @article.updated_at - etag @article.sha1 - erb :article -end -``` - -Также вы можете использовать -[weak ETag](http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation): - -```ruby -etag @article.sha1, :weak -``` - -Эти методы-помощники не станут ничего кэшировать для вас, но они дадут -необходимую информацию для вашего кэша. Если вы ищете легкое решение для -кэширования, попробуйте [rack-cache](https://github.com/rtomayko/rack-cache): - -```ruby -require 'rack/cache' -require 'sinatra' - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hello" -end -``` - -Используйте опцию `:static_cache_control` (см. ниже), чтобы добавить заголовок -`Cache-Control` к статическим файлам. - -В соответствии с RFC 2616 ваше приложение должно вести себя по-разному, когда -заголовки If-Match или If-None-Match имеют значение `*`, в зависимости от -того, существует или нет запрашиваемый ресурс. Sinatra предполагает, что -ресурсы, к которым обращаются с помощью безопасных (GET) и идемпотентных (PUT) -методов, уже существуют, а остальные ресурсы (к которым обращаются, например, -с помощью POST) считает новыми. Вы можете изменить данное поведение с помощью -опции `:new_resource`: - -```ruby -get '/create' do - etag '', :new_resource => true - Article.create - erb :new_article -end -``` - -Если вы хотите использовать weak ETag, задайте опцию `:kind`: - -```ruby -etag '', :new_resource => true, :kind => :weak -``` - -### Отправка файлов - -Для отправки файлов пользователю вы можете использовать метод `send_file`: - -```ruby -get '/' do - send_file 'foo.png' -end -``` - -Этот метод имеет несколько опций: - -```ruby -send_file 'foo.png', :type => :jpg -``` - -Возможные опции: - -
-
filename
-
имя файла, по умолчанию: реальное имя файла.
- -
last_modified
-
значение для заголовка Last-Modified, по умолчанию: mtime (время - изменения) файла.
- -
type
-
тип файла, по умолчанию: определяется по расширению файла.
- -
disposition
-
используется для заголовка Content-Disposition, возможные значения: nil - (по умолчанию), :attachment и :inline.
- -
length
-
значения для заголовка Content-Length, по умолчанию: размер файла.
- -
status
-
Код ответа. Полезно, когда отдается статический файл в качестве страницы с - сообщением об ошибке.
-
- -Этот метод будет использовать возможности Rack сервера для отправки файлов, -если они доступны, в противном случае будет напрямую отдавать файл из Ruby -процесса. Метод `send_file` также обеспечивает автоматическую обработку -частичных (range) запросов с помощью Sinatra. - -### Доступ к объекту запроса - -Объект входящего запроса доступен на уровне обработки запроса (в фильтрах, -маршрутах, обработчиках ошибок) с помощью `request` метода: - -```ruby -# приложение запущено на http://example.com/example -get '/foo' do - t = %w[text/css text/html application/javascript] - request.accept # ['text/html', '*/*'] - request.accept? 'text/xml' # true - request.preferred_type(t) # 'text/html' - request.body # тело запроса, посланное клиентом (см. ниже) - request.scheme # "http" - request.script_name # "/example" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # длина тела запроса - request.media_type # медиатип тела запроса - request.host # "example.com" - request.get? # true (есть аналоги для других методов HTTP) - request.form_data? # false - request["some_param"] # значение параметра some_param. Шорткат для хеша params - request.referrer # источник запроса клиента либо '/' - request.user_agent # user agent (используется для :agent условия) - request.cookies # хеш, содержащий cookies браузера - request.xhr? # является ли запрос ajax запросом? - request.url # "http://example.com/example/foo" - request.path # "/example/foo" - request.ip # IP-адрес клиента - request.secure? # false (true, если запрос сделан через SSL) - request.forwarded? # true (если сервер работает за обратным прокси) - request.env # "сырой" env хеш, полученный Rack -end -``` - -Некоторые опции, такие как `script_name` или `path_info`, доступны для -изменения: - -```ruby -before { request.path_info = "/" } - -get "/" do - "all requests end up here" -end -``` - -`request.body` является IO или StringIO объектом: - -```ruby -post "/api" do - request.body.rewind # в случае, если кто-то уже прочитал тело запроса - data = JSON.parse request.body.read - "Hello #{data['name']}!" -end -``` - -### Вложения - -Вы можете использовать метод `attachment`, чтобы сказать браузеру, что ответ -сервера должен быть сохранен на диск, а не отображен: - -```ruby -get '/' do - attachment - "store it!" -end -``` - -Вы также можете указать имя файла: - -```ruby -get '/' do - attachment "info.txt" - "store it!" -end -``` - -### Работа со временем и датами - -Sinatra предлагает метод-помощник `time_for`, который из заданного значения -создает объект Time. Он также может конвертировать `DateTime`, `Date` и -подобные классы: - -```ruby -get '/' do - pass if Time.now > time_for('Dec 23, 2012') - "still time" -end -``` - -Этот метод используется внутри Sinatra методами `expires`, `last_modified` и -им подобными. Поэтому вы легко можете расширить функционал этих методов, -переопределив `time_for` в своем приложении: - -```ruby -helpers do - def time_for(value) - case value - when :yesterday then Time.now - 24*60*60 - when :tomorrow then Time.now + 24*60*60 - else super - end - end -end - -get '/' do - last_modified :yesterday - expires :tomorrow - "hello" -end -``` - -### Поиск шаблонов - -Для поиска шаблонов и их последующего рендеринга используется метод -`find_template`: - -```ruby -find_template settings.views, 'foo', Tilt[:haml] do |file| - puts "could be #{file}" -end -``` - -Это не слишком полезный пример. Зато полезен тот факт, что вы можете -переопределить этот метод, чтобы использовать свой собственный механизм -поиска. Например, если вы хотите, чтобы можно было использовать несколько -директорий с шаблонами: - -```ruby -set :views, ['views', 'templates'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -``` - -Другой пример, в котором используются разные директории для движков -рендеринга: - -```ruby -set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:default] - super(folder, name, engine, &block) - end -end -``` - -Вы можете легко вынести этот код в расширение и поделиться им с остальными! - -Заметьте, что `find_template` не проверяет, существует ли файл на самом деле, -а вызывает заданный блок для всех возможных путей. Дело тут не в -производительности, дело в том, что `render` вызовет `break`, как только файл -не будет найден. Содержимое и местонахождение шаблонов будет закэшировано, -если приложение запущено не в режиме разработки (`set :environment, -:development`). Вы должны помнить об этих нюансах, если пишите по-настоящему -"сумасшедший" метод. - -## Конфигурация - -Этот блок исполняется один раз при старте в любом окружении, режиме -(environment): - -```ruby -configure do - # задание одной опции - set :option, 'value' - - # устанавливаем несколько опций - set :a => 1, :b => 2 - - # то же самое, что и `set :option, true` - enable :option - - # то же самое, что и `set :option, false` - disable :option - - # у вас могут быть "динамические" опции с блоками - set(:css_dir) { File.join(views, 'css') } -end -``` - -Будет запущено, когда окружение (RACK_ENV переменная) `:production`: - -```ruby -configure :production do - ... -end -``` - -Будет запущено, когда окружение `:production` или `:test`: - -```ruby -configure :production, :test do - ... -end -``` - -Вы можете получить доступ к этим опциям с помощью `settings`: - -```ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -``` - -### Настройка защиты от атак - -Sinatra использует -[Rack::Protection](https://github.com/rkh/rack-protection#readme) для защиты -приложения от простых атак. Вы можете легко выключить эту защиту (что сделает -ваше приложение чрезвычайно уязвимым): - -```ruby -disable :protection -``` - -Чтобы пропустить какой-либо уровень защиты, передайте хеш опций в параметр -`protection`: - -```ruby -set :protection, :except => :path_traversal -``` - -Вы также можете отключить сразу несколько уровней защиты: - -```ruby -set :protection, :except => [:path_traversal, :session_hijacking] -``` - -### Доступные настройки - -
-
absolute_redirects
-
- если отключено, то Sinatra будет позволять использование относительных - перенаправлений, но при этом перестанет соответствовать RFC 2616 (HTTP - 1.1), который разрешает только абсолютные перенаправления. -
-
- Включайте эту опцию, если ваше приложение работает за обратным прокси, - который настроен не совсем корректно. Обратите внимание, метод url все - равно будет генерировать абсолютные URL, если вы не передадите false - вторым аргументом. -
-
Отключено по умолчанию.
- -
add_charsets
-
- mime-типы, к которым метод content_type будет автоматически добавлять - информацию о кодировке. Вам следует добавлять значения к этой опции - вместо ее переопределения: settings.add_charsets << "application/foobar" -
- -
app_file
-
- путь к главному файлу приложения, используется для нахождения корневой - директории проекта, директорий с шаблонами и статическими файлами, - вложенных шаблонов. -
- -
bind
-
- используемый IP-адрес (по умолчанию: 0.0.0.0). Используется только - встроенным сервером. -
- -
default_encoding
-
кодировка, если неизвестна (по умолчанию: "utf-8").
- -
dump_errors
-
отображать ошибки в логе.
- -
environment
-
- текущее окружение, по умолчанию, значение ENV['RACK_ENV'] или - "development", если ENV['RACK_ENV'] недоступна. -
- -
logging
-
использовать логер.
- -
lock
-
- создает блокировку для каждого запроса, которая гарантирует обработку - только одного запроса в текущий момент времени в Ruby процессе. -
-
- Включайте, если ваше приложение не потоко-безопасно (thread-safe). - Отключено по умолчанию.
- -
method_override
-
- использовать "магический" параметр _method, для поддержки - PUT/DELETE форм в браузерах, которые не поддерживают эти методы. -
- -
port
-
- порт, на котором будет работать сервер. - Используется только встроенным сервером. -
- -
prefixed_redirects
-
- добавлять или нет параметр request.script_name к редиректам, если не - задан абсолютный путь. Таким образом, redirect '/foo' будет вести себя - как redirect to('/foo'). Отключено по умолчанию. -
- -
protection
-
включена или нет защита от атак. Смотрите секцию выше.
- -
public_dir
-
Алиас для public_folder.
- -
public_folder
-
- путь к директории, откуда будут раздаваться статические файлы. - Используется, только если включена раздача статических файлов - (см. опцию static ниже). -
- -
reload_templates
-
- перезагружать или нет шаблоны на каждый запрос. Включено в режиме - разработки. -
- -
root
-
путь к корневой директории проекта.
- -
raise_errors
-
- выбрасывать исключения (будет останавливать приложение). - По умолчанию включено только в окружении test. -
- -
run
-
- если включено, Sinatra будет самостоятельно запускать веб-сервер. Не - включайте, если используете rackup или аналогичные средства. -
- -
running
-
работает ли сейчас встроенный сервер? Не меняйте эту опцию!
- -
server
-
- сервер или список серверов, которые следует использовать в качестве - встроенного сервера. По умолчанию: ['thin', 'mongrel', 'webrick'], порядок - задает приоритет.
- -
sessions
-
- включить сессии на основе кук (cookie) на базе Rack::Session::Cookie. - Смотрите секцию "Использование сессий" выше. -
- -
show_exceptions
-
- показывать исключения/стек вызовов (stack trace) в браузере. По умолчанию - включено только в окружении development. -
-
- Может быть установлено в - :after_handler для запуска специфичной для приложения обработки ошибок, - перед показом трассировки стека в браузере. -
- -
static
-
должна ли Sinatra осуществлять раздачу статических файлов.
-
Отключите, когда используете какой-либо веб-сервер для этой цели.
-
Отключение значительно улучшит производительность приложения.
-
По умолчанию включено в классических и отключено в модульных приложениях.
- -
static_cache_control
-
- когда Sinatra отдает статические файлы, используйте эту опцию, чтобы - добавить им заголовок Cache-Control. Для этого используется - метод-помощник cache_control. По умолчанию отключено. -
-
- Используйте массив, когда надо задать несколько значений: - set :static_cache_control, [:public, :max_age => 300] -
- -
threaded
-
- если включено, то Thin будет использовать EventMachine.defer для - обработки запросов. -
- -
traps
-
должна ли Синатра обрабатывать системные сигналы или нет.
- -
views
-
путь к директории с шаблонами.
-
- -## Режим, окружение - -Есть 3 предопределенных режима, окружения: `"development"`, `"production"` и -`"test"`. Режим может быть задан через переменную окружения `RACK_ENV`. -Значение по умолчанию — `"development"`. В этом режиме работы все шаблоны -перезагружаются между запросами. А также задаются специальные обработчики -`not_found` и `error`, чтобы вы могли увидеть стек вызовов. В окружениях -`"production"` и `"test"` шаблоны по умолчанию кэшируются. - -Для запуска приложения в определенном окружении используйте ключ `-e` - -``` -ruby my_app.rb -e [ENVIRONMENT] -``` - -Вы можете использовать предопределенные методы `development?`, `test?` и -+production?, чтобы определить текущее окружение. - -## Обработка ошибок - -Обработчики ошибок исполняются в том же контексте, что и маршруты, и -`before`-фильтры, а это означает, что всякие прелести вроде `haml`, `erb`, -`halt` и т.д. доступны и им. - -### Not Found - -Когда выброшено исключение `Sinatra::NotFound`, или кодом ответа является 404, -то будет вызван `not_found` обработчик: - -```ruby -not_found do - 'This is nowhere to be found.' -end -``` - -### Ошибки - -Обработчик ошибок `error` будет вызван, когда исключение выброшено из блока -маршрута, либо из фильтра. Объект-исключение доступен как переменная -`sinatra.error` в Rack: - -```ruby -error do - 'Sorry there was a nasty error - ' + env['sinatra.error'].name -end -``` - -Конкретные ошибки: - -```ruby -error MyCustomError do - 'So what happened was...' + env['sinatra.error'].message -end -``` - -Тогда, если это произошло: - -```ruby -get '/' do - raise MyCustomError, 'something bad' -end -``` - -То вы получите: - -``` -So what happened was... something bad -``` - -Также вы можете установить обработчик ошибок для кода состояния HTTP: - -```ruby -error 403 do - 'Access forbidden' -end - -get '/secret' do - 403 -end -``` - -Либо набора кодов: - -```ruby -error 400..510 do - 'Boom' -end -``` - -Sinatra устанавливает специальные `not_found` и `error` обработчики, когда -приложение запущено в режиме разработки (окружение `:development`). - -## Rack "прослойки" - -Sinatra использует [Rack](http://rack.rubyforge.org/), минимальный стандартный -интерфейс для веб-фреймворков на Ruby. Одной из самых интересных для -разработчиков возможностей Rack является поддержка "прослоек" ("middleware") — -компонентов, находящихся "между" сервером и вашим приложением, которые -отслеживают и/или манипулируют HTTP запросами/ответами для предоставления -различной функциональности. - -В Sinatra очень просто использовать такие "прослойки" с помощью метода `use`: - -```ruby -require 'sinatra' -require 'my_custom_middleware' - -use Rack::Lint -use MyCustomMiddleware - -get '/hello' do - 'Hello World' -end -``` - -Семантика `use` идентична той, что определена для -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html) DSL -(чаще всего используется в rackup файлах). Например, метод `use` принимает как -множественные переменные, так и блоки: - -```ruby -use Rack::Auth::Basic do |username, password| - username == 'admin' && password == 'secret' -end -``` - -Rack распространяется с различными стандартными "прослойками" для логирования, -отладки, маршрутизации URL, аутентификации, обработки сессий. Sinatra -использует многие из этих компонентов автоматически, основываясь на -конфигурации, чтобы вам не приходилось подключать (`use`) их вручную. - -Вы можете найти полезные прослойки в -[rack](https://github.com/rack/rack/tree/master/lib/rack), -[rack-contrib](https://github.com/rack/rack-contrib#readme), -или в -[Rack wiki](https://github.com/rack/rack/wiki/List-of-Middleware). - -## Тестирование - -Тесты для Sinatra приложений могут быть написаны с помощью библиотек, -фреймворков, поддерживающих тестирование Rack. -[Rack::Test](http://rdoc.info/github/brynary/rack-test/master/frames) -рекомендован: - -```ruby -require 'my_sinatra_app' -require 'test/unit' -require 'rack/test' - -class MyAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_my_default - get '/' - assert_equal 'Hello World!', last_response.body - end - - def test_with_params - get '/meet', :name => 'Frank' - assert_equal 'Hello Frank!', last_response.body - end - - def test_with_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "You're using Songbird!", last_response.body - end -end -``` - -## Sinatra::Base — "прослойки", библиотеки и модульные приложения - -Описание своего приложения самым простейшим способом (с помощью DSL верхнего -уровня, классический стиль) отлично работает для крохотных приложений. В таких -случаях используется конфигурация, рассчитанная на микро-приложения -(единственный файл приложения, `./public` и `./views` директории, логирование, -страница информации об исключении и т.д.). Тем не менее, такой метод имеет -множество недостатков при создании компонентов, таких как Rack middleware -("прослоек"), Rails metal, простых библиотек с серверными компонентами, -расширений Sinatra. И тут на помощь приходит `Sinatra::Base`: - -```ruby -require 'sinatra/base' - -class MyApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Hello world!' - end -end -``` - -Методы, доступные `Sinatra::Base` подклассам идентичны тем, что доступны -приложениям в DSL верхнего уровня. Большинство таких приложений могут быть -конвертированы в `Sinatra::Base` компоненты с помощью двух модификаций: - -* Вы должны подключать `sinatra/base` вместо `sinatra`, иначе все методы, - предоставляемые Sinatra, будут импортированы в глобальное пространство - имен. -* Поместите все маршруты, обработчики ошибок, фильтры и опции в подкласс - `Sinatra::Base`. - -`Sinatra::Base` — это чистый лист. Большинство опций, включая встроенный -сервер, по умолчанию отключены. Смотрите -[Опции и конфигурация](http://www.sinatrarb.com/configuration.html) -для детальной информации об опциях и их поведении. - -### Модульные приложения против классических - -Вопреки всеобщему убеждению, в классическом стиле (самом простом) нет ничего -плохого. Если этот стиль подходит вашему приложению, вы не обязаны -переписывать его в модульное приложение. - -Основным недостатком классического стиля является тот факт, что у вас может -быть только одно приложение Sinatra на один процесс Ruby. Если вы планируете -использовать больше, переключайтесь на модульный стиль. Вы можете смело -смешивать модульный и классический стили. - -Переходя с одного стиля на другой, примите во внимание следующие изменения в -настройках: - - Опция Классический Модульный - - app_file файл с приложением файл с подклассом Sinatra::Base - run $0 == app_file false - logging true false - method_override true false - inline_templates true false - static true false - -### Запуск модульных приложений - -Есть два общепринятых способа запускать модульные приложения: запуск напрямую -с помощью `run!`: - -```ruby -# my_app.rb -require 'sinatra/base' - -class MyApp < Sinatra::Base - # ... здесь код приложения ... - - # запускаем сервер, если исполняется текущий файл - run! if app_file == $0 -end -``` - -Затем: - -``` -ruby my_app.rb -``` - -Или с помощью конфигурационного файла `config.ru`, который позволяет -использовать любой Rack-совместимый сервер приложений. - -```ruby -# config.ru -require './my_app' -run MyApp -``` - -Запускаем: - -``` -rackup -p 4567 -``` - -### Запуск классических приложений с config.ru - -Файл приложения: - -```ruby -# app.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -``` - -И соответствующий `config.ru`: - -```ruby -require './app' -run Sinatra::Application -``` - -### Когда использовать config.ru? - -Вот несколько причин, по которым вы, возможно, захотите использовать -`config.ru`: - -* вы хотите разворачивать свое приложение на различных Rack-совместимых - серверах (Passenger, Unicorn, Heroku, ...); -* вы хотите использовать более одного подкласса `Sinatra::Base`; -* вы хотите использовать Sinatra только в качестве "прослойки" Rack. - -**Совсем необязательно переходить на использование `config.ru` лишь потому, -что вы стали использовать модульный стиль приложения. И необязательно -использовать модульный стиль, чтобы запускать приложение с помощью -`config.ru`.** - -### Использование Sinatra в качестве "прослойки" - -Не только сама Sinatra может использовать "прослойки" Rack, но и любое Sinatra -приложение само может быть добавлено к любому Rack endpoint в качестве -"прослойки". Этим endpoint (конечной точкой) может быть другое Sinatra -приложение, или приложение, основанное на Rack (Rails/Ramaze/Camping/...): - -```ruby -require 'sinatra/base' - -class LoginScreen < Sinatra::Base - enable :sessions - - get('/login') { haml :login } - - post('/login') do - if params[:name] == 'admin' && params[:password] == 'admin' - session['user_name'] = params[:name] - else - redirect '/login' - end - end -end - -class MyApp < Sinatra::Base - # "прослойка" будет запущена перед фильтрами - use LoginScreen - - before do - unless session['user_name'] - halt "Access denied, please login." - end - end - - get('/') { "Hello #{session['user_name']}." } -end -``` - -### Создание приложений "на лету" - -Иногда требуется создавать Sinatra приложения "на лету" (например, из другого -приложения). Это возможно с помощью `Sinatra.new`: - -```ruby -require 'sinatra/base' -my_app = Sinatra.new { get('/') { "hi" } } -my_app.run! -``` - -Этот метод может принимать аргументом приложение, от которого следует -наследоваться: - -```ruby -# config.ru -require 'sinatra/base' - -controller = Sinatra.new do - enable :logging - helpers MyHelpers -end - -map('/a') do - run Sinatra.new(controller) { get('/') { 'a' } } -end - -map('/b') do - run Sinatra.new(controller) { get('/') { 'b' } } -end -``` - -Это особенно полезно для тестирования расширений Sinatra и при использовании -Sinatra внутри вашей библиотеки. - -Благодаря этому, использовать Sinatra как "прослойку" очень просто: - -```ruby -require 'sinatra/base' - -use Sinatra do - get('/') { ... } -end - -run RailsProject::Application -``` - -## Области видимости и привязка - -Текущая область видимости определяет методы и переменные, доступные в данный -момент. - -### Область видимости приложения / класса - -Любое Sinatra приложение соответствует подклассу `Sinatra::Base`. Если вы -используете DSL верхнего уровня (`require 'sinatra'`), то этим классом будет -`Sinatra::Application`, иначе это будет подкласс, который вы создали вручную. -На уровне класса вам будут доступны такие методы, как `get` или `before`, но -вы не сможете получить доступ к объектам `request` или `session`, так как -существует только один класс приложения для всех запросов. - -Опции, созданные с помощью `set`, являются методами уровня класса: - -```ruby -class MyApp < Sinatra::Base - # Я в области видимости приложения! - set :foo, 42 - foo # => 42 - - get '/foo' do - # Я больше не в области видимости приложения! - end -end -``` - -У вас будет область видимости приложения внутри: - -* тела вашего класса приложения; -* методов, определенных расширениями; -* блока, переданного в `helpers`; -* блоков, использованных как значения для `set`; -* блока, переданного в `Sinatra.new`. - -Вы можете получить доступ к объекту области видимости (классу приложения) -следующими способами: - -* через объект, переданный блокам конфигурации (`configure { |c| ... }`); -* `settings` внутри области видимости запроса. - -### Область видимости запроса/экземпляра - -Для каждого входящего запроса будет создан новый экземпляр вашего приложения, -и все блоки обработчика будут запущены в этом контексте. В этой области -видимости вам доступны `request` и `session` объекты, вызовы методов -рендеринга, такие как `erb` или `haml`. Вы можете получить доступ к области -видимости приложения из контекста запроса, используя метод-помощник -`settings`: - -```ruby -class MyApp < Sinatra::Base - # Я в области видимости приложения! - get '/define_route/:name' do - # Область видимости запроса '/define_route/:name' - @value = 42 - - settings.get("/#{params[:name]}") do - # Область видимости запроса "/#{params[:name]}" - @value # => nil (другой запрос) - end - - "Route defined!" - end -end -``` - -У вас будет область видимости запроса в: - -* get/head/post/put/delete/options блоках; -* before/after фильтрах; -* методах-помощниках; -* шаблонах/отображениях. - -### Область видимости делегирования - -Область видимости делегирования просто перенаправляет методы в область -видимости класса. Однако, она не полностью ведет себя как область видимости -класса, так как у вас нет привязки к классу. Только методы, явно помеченные -для делегирования, будут доступны, а переменных/состояний области видимости -класса не будет (иначе говоря, у вас будет другой `self` объект). Вы можете -непосредственно добавить методы делегирования, используя -`Sinatra::Delegator.delegate :method_name`. - -У вас будет контекст делегирования внутри: - -* привязки верхнего уровня, если вы сделали `require 'sinatra'`; -* объекта, расширенного с помощью `Sinatra::Delegator`. - -Посмотрите сами в код: вот -[примесь Sinatra::Delegator](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/base.rb#L1609-1633) -[расширяет главный объект](https://github.com/sinatra/sinatra/blob/ca06364/lib/sinatra/main.rb#L28-30). - -## Командная строка - -Sinatra приложения могут быть запущены напрямую: - -``` -ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER] -``` - -Опции включают: - -``` --h # раздел помощи --p # указание порта (по умолчанию 4567) --o # указание хоста (по умолчанию 0.0.0.0) --e # указание окружения, режима (по умолчанию development) --s # указание rack сервера/обработчика (по умолчанию thin) --x # включить мьютекс-блокировку (по умолчанию выключена) -``` - -## Системные требования - -Следующие версии Ruby официально поддерживаются: - -
-
Ruby 1.8.7
-
1.8.7 полностью поддерживается, тем не менее, если вас ничто не держит на - этой версии, рекомендуем обновиться до 1.9.2 или перейти на JRuby или - Rubinius. Поддержка 1.8.7 не будет прекращена до выхода Sinatra 2.0 и Ruby - 2.0, разве что в случае релиза 1.8.8 (что маловероятно). Но даже тогда, - возможно, поддержка не будет прекращена. Ruby 1.8.6 больше не - поддерживается. Если вы хотите использовать 1.8.6, откатитесь до Sinatra - 1.2, которая будет получать все исправления ошибок до тех пор, пока не - будет выпущена Sinatra 1.4.0.
- -
Ruby 1.9.2
-
1.9.2 полностью поддерживается и рекомендована к использованию. - Не используйте 1.9.2p0, - известно, что эта версия очень нестабильна при использовании Sinatra. Эта - версия будет поддерживаться по крайней мере до выхода Ruby 1.9.4/2.0, а - поддержка последней версии 1.9 будет осуществляться до тех пор, пока она - поддерживается командой разработчиков Ruby.
- -
Ruby 1.9.3
-
1.9.3 полностью поддерживается. Заметьте, что переход на 1.9.3 с - ранних версий сделает недействительными все сессии.
- -
Rubinius
-
Rubinius официально поддерживается (Rubinius >= 1.2.4), всё, включая все - языки шаблонов, работает. Предстоящий релиз 2.0 также поддерживается.
- -
JRuby
-
JRuby официально поддерживается (JRuby >= 1.6.5). Нет никаких проблем с - использованием альтернативных шаблонов. Тем не менее, если вы выбираете - JRuby, то, пожалуйста, посмотрите на JRuby Rack-серверы, так как Thin не - поддерживается полностью на JRuby. Поддержка расширений на C в JRuby все - еще экспериментальная, что на данный момент затрагивает только RDiscount, - Redcarpet и RedCloth.
-
- -Мы также следим за предстоящими к выходу версиями Ruby. - -Следующие реализации Ruby не поддерживаются официально, но известно, что на -них запускается Sinatra: - -* старые версии JRuby и Rubinius; -* Ruby Enterprise Edition; -* MacRuby, Maglev, IronRuby; -* Ruby 1.9.0 и 1.9.1 (настоятельно не рекомендуются к использованию). - -То, что версия официально не поддерживается, означает, что, если что-то не -работает на этой версии, а на поддерживаемой работает — это не наша проблема, -а их. - -Мы также запускаем наши CI-тесты на версии Ruby, находящейся в разработке -(предстоящей 2.0.0), и на 1.9.4, но мы не можем ничего гарантировать, так как -они находятся в разработке. Предполагается, что 1.9.4p0 и 2.0.0p0 будут -поддерживаться. - -Sinatra должна работать на любой операционной системе, в которой есть одна из -указанных выше версий Ruby. - -Пока невозможно запустить Sinatra на Cardinal, SmallRuby, BlueRuby и на любой -версии Ruby до 1.8.7. - -## На острие - -Если вы хотите использовать самый последний код Sinatra, не бойтесь запускать -свое приложение вместе с кодом из master ветки Sinatra, она весьма стабильна. - -Мы также время от времени выпускаем предварительные версии, так что вы можете -делать так: - -``` -gem install sinatra --pre -``` - -Чтобы воспользоваться некоторыми самыми последними возможностями. - -### С помощью Bundler - -Если вы хотите запускать свое приложение с последней версией Sinatra, то -рекомендуем использовать [Bundler](http://gembundler.com/). - -Сначала установите Bundler, если у вас его еще нет: - -``` -gem install bundler -``` - -Затем создайте файл `Gemfile` в директории вашего проекта: - -```ruby -source :rubygems -gem 'sinatra', :git => "git://github.com/sinatra/sinatra.git" - -# другие зависимости -gem 'haml' # например, если используете haml -gem 'activerecord', '~> 3.0' # может быть, вам нужен и ActiveRecord 3.x -``` - -Обратите внимание, вам нужно будет указывать все зависимости вашего приложения -в этом файле. Однако, непосредственные зависимости Sinatra (Rack и Tilt) -Bundler автоматически скачает и добавит. - -Теперь вы можете запускать свое приложение так: - -``` -bundle exec ruby myapp.rb -``` - -### Вручную - -Создайте локальный клон репозитория и запускайте свое приложение с -`sinatra/lib` директорией в `$LOAD_PATH`: - -``` -cd myapp -git clone git://github.com/sinatra/sinatra.git -ruby -Isinatra/lib myapp.rb -``` - -Чтобы обновить исходники Sinatra: - -``` -cd myapp/sinatra -git pull -``` - -### Установка глобально - -Вы можете самостоятельно собрать gem: - -``` -git clone git://github.com/sinatra/sinatra.git -cd sinatra -rake sinatra.gemspec -rake install -``` - -Если вы устанавливаете пакеты (gem) от пользователя root, то вашим последним -шагом должна быть команда - -``` -sudo rake install -``` - -## Версии - -Sinatra использует [Semantic Versioning](http://semver.org/), SemVer и -SemVerTag. - -## Дальнейшее чтение - -* [Веб-сайт проекта](http://www.sinatrarb.com/) — Дополнительная - документация, новости и ссылки на другие ресурсы. -* [Участие в проекте](http://www.sinatrarb.com/contributing) — Обнаружили - баг? Нужна помощь? Написали патч? -* [Слежение за проблемами/ошибками](http://github.com/sinatra/sinatra/issues) -* [Twitter](http://twitter.com/sinatra) -* [Группы рассылки](http://groups.google.com/group/sinatrarb/topics) -* [#sinatra](irc://chat.freenode.net/#sinatra) на http://freenode.net -* [Sinatra Book](http://sinatra-book.gittr.com) учебник и сборник рецептов -* [Sinatra Recipes](http://recipes.sinatrarb.com/) сборник рецептов -* API документация к [последнему релизу](http://rubydoc.info/gems/sinatra) - или [текущему HEAD](http://rubydoc.info/github/sinatra/sinatra) на - http://rubydoc.info -* [Сервер непрерывной интеграции](http://travis-ci.org/sinatra/sinatra) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.zh.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.zh.md deleted file mode 100644 index 83b5b60..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/README.zh.md +++ /dev/null @@ -1,2158 +0,0 @@ -# Sinatra - -*注:本文档是英文版的翻译,内容更新有可能不及时。 -如有不一致的地方,请以英文版为准。* - -Sinatra是一个基于Ruby语言的[DSL](http://en.wikipedia.org/wiki/Domain-specific_language)( -领域专属语言),可以轻松、快速的创建web应用。 - -~~~~ ruby -# myapp.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -~~~~ - -安装gem,然后运行: - -~~~~ shell -gem install sinatra -ruby myapp.rb -~~~~ - -在该地址查看: [localhost:4567](http://localhost:4567) - -安装Sintra后,最好再运行`gem install thin`安装Thin。这样,Sinatra会优先选择Thin作为服务器。 - -## 路由(route) - -在Sinatra中,一个路由分为两部分:HTTP方法(GET, POST等)和URL匹配范式。 -每个路由都有一个要执行的代码块: - -~~~~ ruby -get '/' do - .. 显示内容 .. -end - -post '/' do - .. 创建内容 .. -end - -put '/' do - .. 更新内容 .. -end - -delete '/' do - .. 删除内容 .. -end - -options '/' do - .. 显示命令列表 .. -end - -link '/' do - .. 建立某种联系 .. -end - -unlink '/' do - .. 解除某种联系 .. -end - - -~~~~ - -路由按照它们被定义的顺序进行匹配。 第一个与请求匹配的路由会被调用。 - -路由范式可以包括具名参数,可通过`params`哈希表获得: - -~~~~ ruby -get '/hello/:name' do - # 匹配 "GET /hello/foo" 和 "GET /hello/bar" - # params[:name] 的值是 'foo' 或者 'bar' - "Hello #{params[:name]}!" -end -~~~~ - -你同样可以通过代码块参数获得具名参数: - -~~~~ ruby -get '/hello/:name' do |n| - "Hello #{n}!" -end -~~~~ - -路由范式也可以包含通配符参数, 可以通过`params[:splat]`数组获得。 - -~~~~ ruby -get '/say/*/to/*' do - # 匹配 /say/hello/to/world - params[:splat] # => ["hello", "world"] -end - -get '/download/*.*' do - # 匹配 /download/path/to/file.xml - params[:splat] # => ["path/to/file", "xml"] -end -~~~~ - -通过正则表达式匹配的路由: - -~~~~ ruby -get %r{/hello/([\w]+)} do - "Hello, #{params[:captures].first}!" -end -~~~~ - -或者使用代码块参数: - -~~~~ ruby -get %r{/hello/([\w]+)} do |c| - "Hello, #{c}!" -end -~~~~ - -### 条件 - -路由也可以包含多样的匹配条件,比如user agent: - -~~~~ ruby -get '/foo', :agent => /Songbird (\d\.\d)[\d\/]*?/ do - "你正在使用Songbird,版本是 #{params[:agent][0]}" -end - -get '/foo' do - # 匹配除Songbird以外的浏览器 -end -~~~~ - -其他可选的条件是 `host_name` 和 `provides`: - -~~~~ ruby -get '/', :host_name => /^admin\./ do - "管理员区域,无权进入!" -end - -get '/', :provides => 'html' do - haml :index -end - -get '/', :provides => ['rss', 'atom', 'xml'] do - builder :feed -end -~~~~ - -你也可以自定义条件: - -~~~~ ruby -set(:probability) { |value| condition { rand <= value } } - -get '/win_a_car', :probability => 0.1 do - "You won!" -end - -get '/win_a_car' do - "Sorry, you lost." -end -~~~~ - -### 返回值 - -路由代码块的返回值至少决定了返回给HTTP客户端的响应体, -或者至少决定了在Rack堆栈中的下一个中间件。 -大多数情况下,将是一个字符串,就像上面的例子中的一样。 -但是其他值也是可以接受的。 - -你可以返回任何对象,或者是一个合理的Rack响应, Rack -body对象或者HTTP状态码: - -- 一个包含三个元素的数组: - `[状态 (Fixnum), 头 (Hash), 响应体 (回应 #each)]` - -- 一个包含两个元素的数组: `[状态 (Fixnum), 响应体 (回应 #each)]` - -- 一个能够回应 `#each` ,只传回字符串的对象 - -- 一个代表状态码的数字 - -那样,我们可以轻松的实现例如流式传输的例子: - -~~~~ ruby -class Stream - def each - 100.times { |i| yield "#{i}\n" } - end -end - -get('/') { Stream.new } -~~~~ - -### 自定义路由匹配器 - -如上显示,Sinatra内置了对于使用字符串和正则表达式作为路由匹配的支持。 -但是,它并没有只限于此。 你可以非常容易地定义你自己的匹配器: - -~~~~ ruby -class AllButPattern - Match = Struct.new(:captures) - - def initialize(except) - @except = except - @captures = Match.new([]) - end - - def match(str) - @captures unless @except === str - end -end - -def all_but(pattern) - AllButPattern.new(pattern) -end - -get all_but("/index") do - # ... -end -~~~~ - -上面的例子可能太繁琐了, 因为它也可以用更简单的方式表述: - -~~~~ ruby -get // do - pass if request.path_info == "/index" - # ... -end -~~~~ - -或者,使用消极向前查找: - -~~~~ ruby -get %r{^(?!/index$)} do - # ... -end -~~~~ - -## 静态文件 - -静态文件是从 `./public_folder` 目录提供服务。你可以通过设置`:public` -选项设定一个不同的位置: - -~~~~ ruby -set :public_folder, File.dirname(__FILE__) + '/static' -~~~~ - -请注意public目录名并没有被包含在URL之中。文件 -`./public/css/style.css`是通过 -`http://example.com/css/style.css`地址访问的。 - -## 视图 / 模板 - -模板被假定直接位于`./views`目录。 要使用不同的视图目录: - -~~~~ ruby -set :views, File.dirname(__FILE__) + '/templates' -~~~~ - -请记住一件非常重要的事情,你只可以通过符号引用模板, 即使它们在子目录下 -(在这种情况下,使用 `:'subdir/template'`)。 你必须使用一个符号, -因为渲染方法会直接地渲染任何传入的字符串。 - -### Haml模板 - -需要引入 `haml` gem/library以渲染 HAML 模板: - -~~~~ ruby -# 你需要在你的应用中引入 haml -require 'haml' - -get '/' do - haml :index -end -~~~~ - -渲染 `./views/index.haml`。 - -[Haml的选项](http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options) -可以通过Sinatra的配置全局设定, 参见 -[选项和配置](http://www.sinatrarb.com/configuration.html), -也可以个别的被覆盖。 - -~~~~ ruby -set :haml, {:format => :html5 } # 默认的Haml输出格式是 :xhtml - -get '/' do - haml :index, :haml_options => {:format => :html4 } # 被覆盖,变成:html4 -end -~~~~ - -### Erb模板 - -~~~~ ruby -# 你需要在你的应用中引入 erb -require 'erb' - -get '/' do - erb :index -end -~~~~ - -这里调用的是 `./views/index.erb` - -### Erubis - -需要引入 `erubis` gem/library以渲染 erubis 模板: - -~~~~ ruby -# 你需要在你的应用中引入 erubis -require 'erubis' - -get '/' do - erubis :index -end -~~~~ - -这里调用的是 `./views/index.erubis` - -使用Erubis代替Erb也是可能的: - -~~~~ ruby -require 'erubis' -Tilt.register :erb, Tilt[:erubis] - -get '/' do - erb :index -end -~~~~ - -使用Erubis来渲染 `./views/index.erb`。 - -### Builder 模板 - -需要引入 `builder` gem/library 以渲染 builder templates: - -~~~~ ruby -# 需要在你的应用中引入builder -require 'builder' - -get '/' do - builder :index -end -~~~~ - -这里调用的是 `./views/index.builder`。 - -### Nokogiri 模板 - -需要引入 `nokogiri` gem/library 以渲染 nokogiri 模板: - -~~~~ ruby -# 需要在你的应用中引入 nokogiri -require 'nokogiri' - -get '/' do - nokogiri :index -end -~~~~ - -这里调用的是 `./views/index.nokogiri`。 - -### Sass 模板 - -需要引入 `haml` 或者 `sass` gem/library 以渲染 Sass 模板: - -~~~~ ruby -# 需要在你的应用中引入 haml 或者 sass -require 'sass' - -get '/stylesheet.css' do - sass :stylesheet -end -~~~~ - -这里调用的是 `./views/stylesheet.sass`。 - -[Sass -的选项](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options) -可以通过Sinatra选项全局设定, 参考 -[选项和配置(英文)](http://www.sinatrarb.com/configuration.html), -也可以在个体的基础上覆盖。 - -~~~~ ruby -set :sass, {:style => :compact } # 默认的 Sass 样式是 :nested - -get '/stylesheet.css' do - sass :stylesheet, :style => :expanded # 覆盖 -end -~~~~ - -### Scss 模板 - -需要引入 `haml` 或者 `sass` gem/library 来渲染 Scss templates: - -~~~~ ruby -# 需要在你的应用中引入 haml 或者 sass -require 'sass' - -get '/stylesheet.css' do - scss :stylesheet -end -~~~~ - -这里调用的是 `./views/stylesheet.scss`。 - -[Scss的选项](http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#options) -可以通过Sinatra选项全局设定, 参考 -[选项和配置(英文)](http://www.sinatrarb.com/configuration.html), -也可以在个体的基础上覆盖。 - -~~~~ ruby -set :scss, :style => :compact # default Scss style is :nested - -get '/stylesheet.css' do - scss :stylesheet, :style => :expanded # overridden -end -~~~~ - -### Less 模板 - -需要引入 `less` gem/library 以渲染 Less 模板: - -~~~~ ruby -# 需要在你的应用中引入 less -require 'less' - -get '/stylesheet.css' do - less :stylesheet -end -~~~~ - -这里调用的是 `./views/stylesheet.less`。 - -### Liquid 模板 - -需要引入 `liquid` gem/library 来渲染 Liquid 模板: - -~~~~ ruby -# 需要在你的应用中引入 liquid -require 'liquid' - -get '/' do - liquid :index -end -~~~~ - -这里调用的是 `./views/index.liquid`。 - -因为你不能在Liquid 模板中调用 Ruby 方法 (除了 `yield`) , -你几乎总是需要传递locals给它: - -~~~~ ruby -liquid :index, :locals => { :key => 'value' } -~~~~ - -### Markdown 模板 - -需要引入 `rdiscount` gem/library 以渲染 Markdown 模板: - -~~~~ ruby -# 需要在你的应用中引入rdiscount -require "rdiscount" - -get '/' do - markdown :index -end -~~~~ - -这里调用的是 `./views/index.markdown` (`md` 和 `mkd` 也是合理的文件扩展名)。 - -在markdown中是不可以调用方法的,也不可以传递 locals给它。 -你因此一般会结合其他的渲染引擎来使用它: - -~~~~ ruby -erb :overview, :locals => { :text => markdown(:introduction) } -~~~~ - -请注意你也可以从其他模板中调用 markdown 方法: - -~~~~ ruby -%h1 Hello From Haml! -%p= markdown(:greetings) -~~~~ - -既然你不能在Markdown中调用Ruby,你不能使用Markdown编写的布局。 -不过,使用其他渲染引擎作为模版的布局是可能的, -通过传递`:layout_engine`选项: - -~~~~ ruby -get '/' do - markdown :index, :layout_engine => :erb -end -~~~~ - -这将会调用 `./views/index.md` 并使用 `./views/layout.erb` 作为布局。 - -请记住你可以全局设定这个选项: - -~~~~ ruby -set :markdown, :layout_engine => :haml, :layout => :post - -get '/' do - markdown :index -end -~~~~ - -这将会调用 `./views/index.markdown` (和任何其他的 Markdown 模版) 并使用 -`./views/post.haml` 作为布局. - -也可能使用BlueCloth而不是RDiscount来解析Markdown文件: - -~~~~ ruby -require 'bluecloth' - -Tilt.register 'markdown', BlueClothTemplate -Tilt.register 'mkd', BlueClothTemplate -Tilt.register 'md', BlueClothTemplate - -get '/' do - markdown :index -end -~~~~ - -使用BlueCloth来渲染 `./views/index.md` 。 - -### Textile 模板 - -需要引入 `RedCloth` gem/library 以渲染 Textile 模板: - -~~~~ ruby -# 在你的应用中引入redcloth -require "redcloth" - -get '/' do - textile :index -end -~~~~ - -这里调用的是 `./views/index.textile`。 - -在textile中是不可以调用方法的,也不可以传递 locals给它。 -你因此一般会结合其他的渲染引擎来使用它: - -~~~~ ruby -erb :overview, :locals => { :text => textile(:introduction) } -~~~~ - -请注意你也可以从其他模板中调用`textile`方法: - -~~~~ ruby -%h1 Hello From Haml! -%p= textile(:greetings) -~~~~ - -既然你不能在Textile中调用Ruby,你不能使用Textile编写的布局。 -不过,使用其他渲染引擎作为模版的布局是可能的, -通过传递`:layout_engine`选项: - -~~~~ ruby -get '/' do - textile :index, :layout_engine => :erb -end -~~~~ - -这将会渲染 `./views/index.textile` 并使用 `./views/layout.erb` -作为布局。 - -请记住你可以全局设定这个选项: - -~~~~ ruby -set :textile, :layout_engine => :haml, :layout => :post - -get '/' do - textile :index -end -~~~~ - -这将会调用 `./views/index.textile` (和任何其他的 Textile 模版) 并使用 -`./views/post.haml` 作为布局. - -### RDoc 模板 - -需要引入 `RDoc` gem/library 以渲染RDoc模板: - -~~~~ ruby -# 需要在你的应用中引入rdoc/markup/to_html -require "rdoc" -require "rdoc/markup/to_html" - -get '/' do - rdoc :index -end -~~~~ - -这里调用的是 `./views/index.rdoc`。 - -在rdoc中是不可以调用方法的,也不可以传递locals给它。 -你因此一般会结合其他的渲染引擎来使用它: - -~~~~ ruby -erb :overview, :locals => { :text => rdoc(:introduction) } -~~~~ - -请注意你也可以从其他模板中调用`rdoc`方法: - -~~~~ ruby -%h1 Hello From Haml! -%p= rdoc(:greetings) -~~~~ - -既然你不能在RDoc中调用Ruby,你不能使用RDoc编写的布局。 -不过,使用其他渲染引擎作为模版的布局是可能的, -通过传递`:layout_engine`选项: - -~~~~ ruby -get '/' do - rdoc :index, :layout_engine => :erb -end -~~~~ - -这将会调用 `./views/index.rdoc` 并使用 `./views/layout.erb` 作为布局。 - -请记住你可以全局设定这个选项: - -~~~~ ruby -set :rdoc, :layout_engine => :haml, :layout => :post - -get '/' do - rdoc :index -end -~~~~ - -这将会调用 `./views/index.rdoc` (和任何其他的 RDoc 模版) 并使用 -`./views/post.haml` 作为布局. - -### Radius 模板 - -需要引入 `radius` gem/library 以渲染 Radius 模板: - -~~~~ ruby -# 需要在你的应用中引入radius -require 'radius' - -get '/' do - radius :index -end -~~~~ - -这里调用的是 `./views/index.radius`。 - -因为你不能在Radius 模板中调用 Ruby 方法 (除了 `yield`) , -你几乎总是需要传递locals给它: - -~~~~ ruby -radius :index, :locals => { :key => 'value' } -~~~~ - -### Markaby 模板 - -需要引入`markaby` gem/library以渲染Markaby模板: - -~~~~ ruby -#需要在你的应用中引入 markaby -require 'markaby' - -get '/' do - markaby :index -end -~~~~ - -这里调用的是 `./views/index.mab`。 - -你也可以使用嵌入的 Markaby: - -~~~~ ruby -get '/' do - markaby { h1 "Welcome!" } -end -~~~~ - -### Slim 模板 - -需要引入 `slim` gem/library 来渲染 Slim 模板: - -~~~~ ruby -# 需要在你的应用中引入 slim -require 'slim' - -get '/' do - slim :index -end -~~~~ - -这里调用的是 `./views/index.slim`。 - -### Creole 模板 - -需要引入 `creole` gem/library 来渲染 Creole 模板: - -~~~~ ruby -# 需要在你的应用中引入 creole -require 'creole' - -get '/' do - creole :index -end -~~~~ - -这里调用的是 `./views/index.creole`。 - -### CoffeeScript 模板 - -需要引入 `coffee-script` gem/library 并至少满足下面条件一项 -以执行Javascript: - -- `node` (来自 Node.js) 在你的路径中 - -- 你正在运行 OSX - -- `therubyracer` gem/library - -请察看 -[github.com/josh/ruby-coffee-script](http://github.com/josh/ruby-coffee-script) -获取更新的选项。 - -现在你可以调用 CoffeeScript 模版了: - -~~~~ ruby -# 需要在你的应用中引入coffee-script -require 'coffee-script' - -get '/application.js' do - coffee :application -end -~~~~ - -这里调用的是 `./views/application.coffee`。 - -### 嵌入模板字符串 - -~~~~ ruby -get '/' do - haml '%div.title Hello World' -end -~~~~ - -调用嵌入模板字符串。 - -### 在模板中访问变量 - -模板和路由执行器在同样的上下文求值。 -在路由执行器中赋值的实例变量可以直接被模板访问。 - -~~~~ ruby -get '/:id' do - @foo = Foo.find(params[:id]) - haml '%h1= @foo.name' -end -~~~~ - -或者,显式地指定一个本地变量的哈希: - -~~~~ ruby -get '/:id' do - foo = Foo.find(params[:id]) - haml '%h1= foo.name', :locals => { :foo => foo } -end -~~~~ - -典型的使用情况是在别的模板中按照局部模板的方式来渲染。 - -### 内联模板 - -模板可以在源文件的末尾定义: - -~~~~ ruby -require 'sinatra' - -get '/' do - haml :index -end - -__END__ - -@@ layout -%html - = yield - -@@ index -%div.title Hello world!!!!! -~~~~ - -注意:引入sinatra的源文件中定义的内联模板才能被自动载入。 -如果你在其他源文件中有内联模板, -需要显式执行调用`enable :inline_templates`。 - -### 具名模板 - -模板可以通过使用顶层 `template` 方法定义: - -~~~~ ruby -template :layout do - "%html\n =yield\n" -end - -template :index do - '%div.title Hello World!' -end - -get '/' do - haml :index -end -~~~~ - -如果存在名为“layout”的模板,该模板会在每个模板渲染的时候被使用。 -你可以单独地通过传送 `:layout => false`来禁用, -或者通过`set :haml, :layout => false`来禁用他们。 - -~~~~ ruby -get '/' do - haml :index, :layout => !request.xhr? -end -~~~~ - -### 关联文件扩展名 - -为了关联一个文件扩展名到一个模版引擎,使用 -`Tilt.register`。比如,如果你喜欢使用 `tt` -作为Textile模版的扩展名,你可以这样做: - -~~~~ ruby -Tilt.register :tt, Tilt[:textile] -~~~~ - -### 添加你自己的模版引擎 - -首先,通过Tilt注册你自己的引擎,然后创建一个渲染方法: - -~~~~ ruby -Tilt.register :myat, MyAwesomeTemplateEngine - -helpers do - def myat(*args) render(:myat, *args) end -end - -get '/' do - myat :index -end -~~~~ - -这里调用的是 `./views/index.myat`。察看 -[github.com/rtomayko/tilt](https://github.com/rtomayko/tilt) -来更多了解Tilt. - -## 过滤器 - -前置过滤器在每个请求前,在请求的上下文环境中被执行, -而且可以修改请求和响应。 在过滤器中设定的实例变量可以被路由和模板访问: - -~~~~ ruby -before do - @note = 'Hi!' - request.path_info = '/foo/bar/baz' -end - -get '/foo/*' do - @note #=> 'Hi!' - params[:splat] #=> 'bar/baz' -end -~~~~ - -后置过滤器在每个请求之后,在请求的上下文环境中执行, -而且可以修改请求和响应。 -在前置过滤器和路由中设定的实例变量可以被后置过滤器访问: - -~~~~ ruby -after do - puts response.status -end -~~~~ - -请注意:除非你显式使用 `body` 方法,而不是在路由中直接返回字符串, -消息体在后置过滤器是不可用的, 因为它在之后才会生成。 - -过滤器可以可选地带有范式, 只有请求路径满足该范式时才会执行: - -~~~~ ruby -before '/protected/*' do - authenticate! -end - -after '/create/:slug' do |slug| - session[:last_slug] = slug -end -~~~~ - -和路由一样,过滤器也可以带有条件: - -~~~~ ruby -before :agent => /Songbird/ do - # ... -end - -after '/blog/*', :host_name => 'example.com' do - # ... -end -~~~~ - -## 辅助方法 - -使用顶层的 `helpers` 方法来定义辅助方法, 以便在路由处理器和模板中使用: - -~~~~ ruby -helpers do - def bar(name) - "#{name}bar" - end -end - -get '/:name' do - bar(params[:name]) -end -~~~~ - -### 使用 Sessions - -Session被用来在请求之间保持状态。如果被激活,每一个用户会话 -对应有一个session哈希: - -~~~~ ruby -enable :sessions - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -~~~~ - -请注意 `enable :sessions` 实际上保存所有的数据在一个cookie之中。 -这可能不会总是做你想要的(比如,保存大量的数据会增加你的流量)。 -你可以使用任何的Rack session中间件,为了这么做, \*不要\*调用 -`enable :sessions`,而是 按照自己的需要引入你的中间件: - -~~~~ ruby -use Rack::Session::Pool, :expire_after => 2592000 - -get '/' do - "value = " << session[:value].inspect -end - -get '/:value' do - session[:value] = params[:value] -end -~~~~ - -### 挂起 - -要想直接地停止请求,在过滤器或者路由中使用: - -~~~~ ruby -halt -~~~~ - -你也可以指定挂起时的状态码: - -~~~~ ruby -halt 410 -~~~~ - -或者消息体: - -~~~~ ruby -halt 'this will be the body' -~~~~ - -或者两者; - -~~~~ ruby -halt 401, 'go away!' -~~~~ - -也可以带消息头: - -~~~~ ruby -halt 402, {'Content-Type' => 'text/plain'}, 'revenge' -~~~~ - -### 让路 - -一个路由可以放弃处理,将处理让给下一个匹配的路由,使用 `pass`: - -~~~~ ruby -get '/guess/:who' do - pass unless params[:who] == 'Frank' - 'You got me!' -end - -get '/guess/*' do - 'You missed!' -end -~~~~ - -路由代码块被直接退出,控制流继续前进到下一个匹配的路由。 -如果没有匹配的路由,将返回404。 - -### 触发另一个路由 - -有些时候,`pass` 并不是你想要的,你希望得到的是另一个路由的结果 -。简单的使用 `call` 可以做到这一点: - -~~~~ ruby -get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.map(&:upcase)] -end - -get '/bar' do - "bar" -end -~~~~ - -请注意在以上例子中,你可以更加简化测试并增加性能,只要简单的移动 - - "bar"到一个被/foo - -和 `/bar`同时使用的helper。 - -如果你希望请求被发送到同一个应用,而不是副本, 使用 `call!` 而不是 -`call`. - -如果想更多了解 `call`,请察看 Rack specification。 - -### 设定 消息体,状态码和消息头 - -通过路由代码块的返回值来设定状态码和消息体不仅是可能的,而且是推荐的。 -但是,在某些场景中你可能想在作业流程中的特定点上设置消息体。 你可以通过 -`body` 辅助方法这么做。 如果你这样做了, -你可以在那以后使用该方法获得消息体: - -~~~~ ruby -get '/foo' do - body "bar" -end - -after do - puts body -end -~~~~ - -也可以传一个代码块给 `body`,它将会被Rack处理器执行( -这将可以被用来实现streaming,参见“返回值”)。 - -和消息体类似,你也可以设定状态码和消息头: - -~~~~ ruby -get '/foo' do - status 418 - headers \ - "Allow" => "BREW, POST, GET, PROPFIND, WHEN", - "Refresh" => "Refresh: 20; http://www.ietf.org/rfc/rfc2324.txt" - body "I'm a tea pot!" -end -~~~~ - -如同 `body`, 不带参数的 `headers` 和 `status` 可以用来访问 -他们你的当前值. - -### 媒体(MIME)类型 - -使用 `send_file` 或者静态文件的时候,Sinatra可能不能识别你的媒体类型。 -使用 `mime_type` 通过文件扩展名来注册它们: - -~~~~ ruby -mime_type :foo, 'text/foo' -~~~~ - -你也可以使用 `content_type` 辅助方法: - -~~~~ ruby -get '/' do - content_type :foo - "foo foo foo" -end -~~~~ - -### 生成 URL - -为了生成URL,你需要使用 `url` 辅助方法, 例如,在Haml中: - -~~~~ ruby -%a{:href => url('/foo')} foo -~~~~ - -如果使用反向代理和Rack路由,生成URL的时候会考虑这些因素。 - -这个方法还有一个别名 `to` (见下面的例子). - -### 浏览器重定向 - -你可以通过 `redirect` 辅助方法触发浏览器重定向: - -~~~~ ruby -get '/foo' do - redirect to('/bar') -end -~~~~ - -其他参数的用法,与 `halt`相同: - -~~~~ ruby -redirect to('/bar'), 303 -redirect 'http://google.com', 'wrong place, buddy' -~~~~ - -用 `redirect back`可以把用户重定向到原始页面: - -~~~~ ruby -get '/foo' do - "do something" -end - -get '/bar' do - do_something - redirect back -end -~~~~ - -如果想传递参数给redirect,可以用query string: - -~~~~ ruby -redirect to('/bar?sum=42') -~~~~ - -或者用session: - -~~~~ ruby -enable :sessions - -get '/foo' do - session[:secret] = 'foo' - redirect to('/bar') -end - -get '/bar' do - session[:secret] -end -~~~~ - -### 缓存控制 - -要使用HTTP缓存,必须正确地设定消息头。 - -你可以这样设定 Cache-Control 消息头: - -~~~~ ruby -get '/' do - cache_control :public - "cache it!" -end -~~~~ - -核心提示: 在前置过滤器中设定缓存. - -~~~~ ruby -before do - cache_control :public, :must_revalidate, :max_age => 60 -end -~~~~ - -如果你正在用 `expires` 辅助方法设定对应的消息头 `Cache-Control` -会自动设定: - -~~~~ ruby -before do - expires 500, :public, :must_revalidate -end -~~~~ - -为了合适地使用缓存,你应该考虑使用 `etag` 和 `last_modified`方法。 -推荐在执行繁重任务\*之前\*使用这些helpers,这样一来, -如果客户端在缓存中已经有相关内容,就会立即得到显示。 - - -~~~~ ruby -get '/article/:id' do - @article = Article.find params[:id] - last_modified @article.updated_at - etag @article.sha1 - erb :article -end -~~~~ - -使用 [weak -ETag](http://en.wikipedia.org/wiki/HTTP_ETag#Strong_and_weak_validation) -也是有可能的: - -~~~~ ruby -etag @article.sha1, :weak -~~~~ - -这些辅助方法并不会为你做任何缓存,而是将必要的信息传送给你的缓存 -如果你在寻找缓存的快速解决方案,试试 -[rack-cache](https://github.com/rtomayko/rack-cache): - -~~~~ ruby -require "rack/cache" -require "sinatra" - -use Rack::Cache - -get '/' do - cache_control :public, :max_age => 36000 - sleep 5 - "hello" -end -~~~~ - -### 发送文件 - -为了发送文件,你可以使用 `send_file` 辅助方法: - -~~~~ ruby -get '/' do - send_file 'foo.png' -end -~~~~ - -也可以带一些选项: - -~~~~ ruby -send_file 'foo.png', :type => :jpg -~~~~ - -可用的选项有: - -
-
filename
-
响应中的文件名,默认是真实文件的名字。
- -
last_modified
-
Last-Modified 消息头的值,默认是文件的mtime(修改时间)。
- -
type
-
使用的内容类型,如果没有会从文件扩展名猜测。
- -
disposition
-
- 用于 Content-Disposition,可能的包括: nil (默认), :attachment 和 - :inline -
- -
length
-
Content-Length 的值,默认是文件的大小。
-
- -如果Rack处理器支持的话,Ruby进程也能使用除streaming以外的方法。 -如果你使用这个辅助方法, Sinatra会自动处理range请求。 - -### 访问请求对象 - -传入的请求对象可以在请求层(过滤器,路由,错误处理) 通过 `request` -方法被访问: - -~~~~ ruby -# 在 http://example.com/example 上运行的应用 -get '/foo' do - request.body # 被客户端设定的请求体(见下) - request.scheme # "http" - request.script_name # "/example" - request.path_info # "/foo" - request.port # 80 - request.request_method # "GET" - request.query_string # "" - request.content_length # request.body的长度 - request.media_type # request.body的媒体类型 - request.host # "example.com" - request.get? # true (其他动词也具有类似方法) - request.form_data? # false - request["SOME_HEADER"] # SOME_HEADER header的值 - request.referrer # 客户端的referrer 或者 '/' - request.user_agent # user agent (被 :agent 条件使用) - request.cookies # 浏览器 cookies 哈希 - request.xhr? # 这是否是ajax请求? - request.url # "http://example.com/example/foo" - request.path # "/example/foo" - request.ip # 客户端IP地址 - request.secure? # false(如果是ssl则为true) - request.forwarded? # true (如果是运行在反向代理之后) - request.env # Rack中使用的未处理的env哈希 -end -~~~~ - -一些选项,例如 `script_name` 或者 `path_info` 也是可写的: - -~~~~ ruby -before { request.path_info = "/" } - -get "/" do - "all requests end up here" -end -~~~~ - -`request.body` 是一个IO或者StringIO对象: - -~~~~ ruby -post "/api" do - request.body.rewind # 如果已经有人读了它 - data = JSON.parse request.body.read - "Hello #{data['name']}!" -end -~~~~ - -### 附件 - -你可以使用 `attachment` 辅助方法来告诉浏览器响应 -应当被写入磁盘而不是在浏览器中显示。 - -~~~~ ruby -get '/' do - attachment - "store it!" -end -~~~~ - -你也可以传递一个文件名: - -~~~~ ruby -get '/' do - attachment "info.txt" - "store it!" -end -~~~~ - -### 查找模板文件 - -`find_template` 辅助方法被用于在渲染时查找模板文件: - -~~~~ ruby -find_template settings.views, 'foo', Tilt[:haml] do |file| - puts "could be #{file}" -end -~~~~ - -这并不是很有用。但是在你需要重载这个方法 -来实现你自己的查找机制的时候有用。 比如,如果你想支持多于一个视图目录: - -~~~~ ruby -set :views, ['views', 'templates'] - -helpers do - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end -end -~~~~ - -另一个例子是为不同的引擎使用不同的目录: - -~~~~ ruby -set :views, :sass => 'views/sass', :haml => 'templates', :default => 'views' - -helpers do - def find_template(views, name, engine, &block) - _, folder = views.detect { |k,v| engine == Tilt[k] } - folder ||= views[:default] - super(folder, name, engine, &block) - end -end -~~~~ - -你可以很容易地包装成一个扩展然后与他人分享! - -请注意 `find_template` 并不会检查文件真的存在, -而是对任何可能的路径调用给入的代码块。这并不会带来性能问题, 因为 -`render` 会在找到文件的时候马上使用 `break` 。 -同样的,模板的路径(和内容)会在除development mode以外的场合 -被缓存。你应该时刻提醒自己这一点, 如果你真的想写一个非常疯狂的方法。 - -## 配置 - -运行一次,在启动的时候,在任何环境下: - -~~~~ ruby -configure do - # setting one option - set :option, 'value' - - # setting multiple options - set :a => 1, :b => 2 - - # same as `set :option, true` - enable :option - - # same as `set :option, false` - disable :option - - # you can also have dynamic settings with blocks - set(:css_dir) { File.join(views, 'css') } -end -~~~~ - -只当环境 (RACK\_ENV environment 变量) 被设定为 `:production`的时候运行: - -~~~~ ruby -configure :production do - ... -end -~~~~ - -当环境被设定为 `:production` 或者 `:test`的时候运行: - -~~~~ ruby -configure :production, :test do - ... -end -~~~~ - -你可以使用 `settings` 获得这些配置: - -~~~~ ruby -configure do - set :foo, 'bar' -end - -get '/' do - settings.foo? # => true - settings.foo # => 'bar' - ... -end -~~~~ - -### 可选的设置 - -
-
absolute_redirects
-
-

- 如果被禁用,Sinatra会允许使用相对路径重定向, 但是,Sinatra就不再遵守 - RFC 2616标准 (HTTP 1.1), 该标准只允许绝对路径重定向。 -

- -

- 如果你的应用运行在一个未恰当设置的反向代理之后, - 你需要启用这个选项。注意 url 辅助方法 仍然会生成绝对 URL,除非你传入 - false 作为第二参数。 -

-

- 默认禁用。 -

-
- -
add_charsets
-
-

- 设定 content_type 辅助方法会 自动加上字符集信息的多媒体类型。 -

- -

- 你应该添加而不是覆盖这个选项: - settings.add_charsets << "application/foobar" -

-
- -
app_file
-
- 主应用文件,用来检测项目的根路径, views和public文件夹和内联模板。 -
- -
bind
-
- 绑定的IP 地址 (默认: 0.0.0.0)。 仅对于内置的服务器有用。 -
- -
default_encoding
-
- 默认编码 (默认为 "utf-8")。 -
- -
dump_errors
-
- 在log中显示错误。 -
- -
environment
-
- 当前环境,默认是 ENV['RACK_ENV'], 或者 "development" 如果不可用。 -
- -
logging
-
- 使用logger -
- -
lock
-
-

- 对每一个请求放置一个锁, 只使用进程并发处理请求。 -

- -

- 如果你的应用不是线程安全则需启动。 默认禁用。 -

-
- -
method_override
-
- 使用 _method 魔法以允许在旧的浏览器中在 表单中使用 put/delete 方法 -
- -
port
-
- 监听的端口号。只对内置服务器有用。 -
- -
prefixed_redirects
-
- 是否添加 request.script_name 到 - 重定向请求,如果没有设定绝对路径。那样的话 redirect '/foo' 会和 - redirect to('/foo')起相同作用。默认禁用。 -
- -
public_folder
-
- public文件夹的位置。 -
- -
reload_templates
-
- 是否每个请求都重新载入模板。 在development mode和 Ruby 1.8.6 - 中被企业(用来 消除一个Ruby内存泄漏的bug)。 -
- -
root
-
- 项目的根目录。 -
- -
raise_errors
-
- 抛出异常(应用会停下)。 -
- -
run
-
- 如果启用,Sinatra会开启web服务器。 如果使用rackup或其他方式则不要启用。 -
- -
running
-
- 内置的服务器在运行吗? 不要修改这个设置! -
- -
server
-
- 服务器,或用于内置服务器的列表。 默认是 [‘thin’, ‘mongrel’, ‘webrick’], - 顺序表明了 优先级。 -
- -
sessions
-
- 开启基于cookie的sesson。 -
- -
show_exceptions
-
- 在浏览器中显示一个stack trace。 -
- -
static
-
- Sinatra是否处理静态文件。 当服务器能够处理则禁用。 禁用会增强性能。 - 默认开启。 -
- -
views
-
- views 文件夹。 -
-
- - -## 错误处理 - -错误处理在与路由和前置过滤器相同的上下文中运行, -这意味着你可以使用许多好东西,比如 `haml`, `erb`, `halt`,等等。 - -### 未找到 - -当一个 `Sinatra::NotFound` 错误被抛出的时候, -或者响应状态码是404,`not_found` 处理器会被调用: - -~~~~ ruby -not_found do - 'This is nowhere to be found' -end -~~~~ - -### 错误 - -`error` 处理器,在任何路由代码块或者过滤器抛出异常的时候会被调用。 -异常对象可以通过`sinatra.error` Rack 变量获得: - -~~~~ ruby -error do - 'Sorry there was a nasty error - ' + env['sinatra.error'].name -end -~~~~ - -自定义错误: - -~~~~ ruby -error MyCustomError do - 'So what happened was...' + env['sinatra.error'].message -end -~~~~ - -那么,当这个发生的时候: - -~~~~ ruby -get '/' do - raise MyCustomError, 'something bad' -end -~~~~ - -你会得到: - - So what happened was... something bad - -另一种替代方法是,为一个状态码安装错误处理器: - -~~~~ ruby -error 403 do - 'Access forbidden' -end - -get '/secret' do - 403 -end -~~~~ - -或者一个范围: - -~~~~ ruby -error 400..510 do - 'Boom' -end -~~~~ - -在运行在development环境下时,Sinatra会安装特殊的 `not_found` 和 `error` -处理器。 - -## Rack 中间件 - -Sinatra 依靠 [Rack](http://rack.rubyforge.org/), 一个面向Ruby -web框架的最小标准接口。 -Rack的一个最有趣的面向应用开发者的能力是支持“中间件”——坐落在服务器和你的应用之间, -监视 并/或 操作HTTP请求/响应以 提供多样类型的常用功能。 - -Sinatra 让建立Rack中间件管道异常简单, 通过顶层的 `use` 方法: - -~~~~ ruby -require 'sinatra' -require 'my_custom_middleware' - -use Rack::Lint -use MyCustomMiddleware - -get '/hello' do - 'Hello World' -end -~~~~ - -`use` 的语义和在 -[Rack::Builder](http://rack.rubyforge.org/doc/classes/Rack/Builder.html) -DSL(在rack文件中最频繁使用)中定义的完全一样。例如,`use` 方法接受 -多个/可变 参数,包括代码块: - -~~~~ ruby -use Rack::Auth::Basic do |username, password| - username == 'admin' && password == 'secret' -end -~~~~ - -Rack中分布有多样的标准中间件,针对日志, -调试,URL路由,认证和session处理。 Sinatra会自动使用这里面的大部分组件, -所以你一般不需要显示地 `use` 他们。 - -## 测试 - -Sinatra的测试可以使用任何基于Rack的测试程序库或者框架来编写。 -[Rack::Test](http://gitrdoc.com/brynary/rack-test) 是推荐候选: - -~~~~ ruby -require 'my_sinatra_app' -require 'test/unit' -require 'rack/test' - -class MyAppTest < Test::Unit::TestCase - include Rack::Test::Methods - - def app - Sinatra::Application - end - - def test_my_default - get '/' - assert_equal 'Hello World!', last_response.body - end - - def test_with_params - get '/meet', :name => 'Frank' - assert_equal 'Hello Frank!', last_response.body - end - - def test_with_rack_env - get '/', {}, 'HTTP_USER_AGENT' => 'Songbird' - assert_equal "You're using Songbird!", last_response.body - end -end -~~~~ - -请注意: 内置的 Sinatra::Test 模块和 Sinatra::TestHarness 类 在 0.9.2 -版本已废弃。 - -## Sinatra::Base - 中间件,程序库和模块化应用 - -把你的应用定义在顶层,对于微型应用这会工作得很好, -但是在构建可复用的组件时候会带来客观的不利, 比如构建Rack中间件,Rails -metal,带有服务器组件的简单程序库, -或者甚至是Sinatra扩展。顶层的DSL污染了Object命名空间, -并假定了一个微型应用风格的配置 (例如, 单一的应用文件, ./public 和 -./views 目录,日志,异常细节页面,等等)。 这时应该让 Sinatra::Base -走到台前了: - -~~~~ ruby -require 'sinatra/base' - -class MyApp < Sinatra::Base - set :sessions, true - set :foo, 'bar' - - get '/' do - 'Hello world!' - end -end -~~~~ - -Sinatra::Base子类可用的方法实际上就是通过顶层 DSL 可用的方法。 -大部分顶层应用可以通过两个改变转换成Sinatra::Base组件: - -- 你的文件应当引入 `sinatra/base` 而不是 `sinatra`; - 否则,所有的Sinatra的 DSL 方法将会被引进到 主命名空间。 - -- 把你的应用的路由,错误处理,过滤器和选项放在 - 一个Sinatra::Base的子类中。 - -`+Sinatra::Base+` 是一张白纸。大部分的选项默认是禁用的, -包含内置的服务器。参见 -[选项和配置](http://sinatra.github.com/configuration.html) -查看可用选项的具体细节和他们的行为。 - -### 模块化 vs. 传统的方式 - -与通常的认识相反,传统的方式没有任何错误。 -如果它适合你的应用,你不需要转换到模块化的应用。 - -和模块化方式相比只有两个缺点: - -- 你对每个Ruby进程只能定义一个Sinatra应用,如果你需要更多, - 切换到模块化方式。 - -- 传统方式使用代理方法污染了 Object 。如果你打算 把你的应用封装进一个 - library/gem,转换到模块化方式。 - -没有任何原因阻止你混合模块化和传统方式。 - -如果从一种转换到另一种,你需要注意settings中的 一些微小的不同: - - Setting Classic Modular - - app_file file loading sinatra nil - run $0 == app_file false - logging true false - method_override true false - inline_templates true false - -### 运行一个模块化应用 - -有两种方式运行一个模块化应用,使用 `run!`来运行: - -~~~~ ruby -# my_app.rb -require 'sinatra/base' - -class MyApp < Sinatra::Base - # ... app code here ... - - # start the server if ruby file executed directly - run! if app_file == $0 -end -~~~~ - -运行: - - ruby my_app.rb - -或者使用一个 `config.ru`,允许你使用任何Rack处理器: - -~~~~ ruby -# config.ru -require './my_app' -run MyApp -~~~~ - -运行: - - rackup -p 4567 - -### 使用config.ru运行传统方式的应用 - -编写你的应用: - -~~~~ ruby -# app.rb -require 'sinatra' - -get '/' do - 'Hello world!' -end -~~~~ - -加入相应的 `config.ru`: - -~~~~ ruby -require './app' -run Sinatra::Application -~~~~ - -### 什么时候用 config.ru? - -以下情况你可能需要使用 `config.ru`: - -- 你要使用不同的 Rack 处理器部署 (Passenger, Unicorn, Heroku, …). - -- 你想使用一个或者多个 `Sinatra::Base`的子类. - -- 你只想把Sinatra当作中间件使用,而不是端点。 - -**你并不需要切换到`config.ru`仅仅因为你切换到模块化方式, -你同样不需要切换到模块化方式, 仅仅因为要运行 `config.ru`.** - -### 把Sinatra当成中间件来使用 - -不仅Sinatra有能力使用其他的Rack中间件,任何Sinatra -应用程序都可以反过来自身被当作中间件,被加在任何Rack端点前面。 -这个端点可以是任何Sinatra应用,或者任何基于Rack的应用程序 -(Rails/Ramaze/Camping/…)。 - -~~~~ ruby -require 'sinatra/base' - -class LoginScreen < Sinatra::Base - enable :sessions - - get('/login') { haml :login } - - post('/login') do - if params[:name] = 'admin' and params[:password] = 'admin' - session['user_name'] = params[:name] - else - redirect '/login' - end - end -end - -class MyApp < Sinatra::Base - # 在前置过滤器前运行中间件 - use LoginScreen - - before do - unless session['user_name'] - halt "Access denied, please login." - end - end - - get('/') { "Hello #{session['user_name']}." } -end -~~~~ - -## 变量域和绑定 - -当前所在的变量域决定了哪些方法和变量是可用的。 - -### 应用/类 变量域 - -每个Sinatra应用相当与Sinatra::Base的一个子类。 -如果你在使用顶层DSL(`require 'sinatra'`),那么这个类就是 -Sinatra::Application,或者这个类就是你显式创建的子类。 -在类层面,你具有的方法类似于 \`get\` 或者 \`before\`,但是你不能访问 -\`request\` 对象或者 \`session\`, 因为对于所有的请求, -只有单一的应用类。 - -通过 \`set\` 创建的选项是类层面的方法: - -~~~~ ruby -class MyApp < Sinatra::Base - # 嘿,我在应用变量域! - set :foo, 42 - foo # => 42 - - get '/foo' do - # 嘿,我不再处于应用变量域了! - end -end -~~~~ - -在下列情况下你将拥有应用变量域的绑定: - -- 在应用类中 - -- 在扩展中定义的方法 - -- 传递给 \`helpers\` 的代码块 - -- 用作\`set\`值的过程/代码块 - -你可以访问变量域对象(就是应用类)就像这样: - -- 通过传递给代码块的对象 (`configure { |c| ... }`) - -- 在请求变量域中使用\`settings\` - -### 请求/实例 变量域 - -对于每个进入的请求,一个新的应用类的实例会被创建 -所有的处理器代码块在该变量域被运行。在这个变量域中, 你可以访问 -\`request\` 和 \`session\` 对象,或者调用渲染方法比如 \`erb\` 或者 -\`haml\`。你可以在请求变量域当中通过\`settings\`辅助方法 -访问应用变量域: - -~~~~ ruby -class MyApp < Sinatra::Base - # 嘿,我在应用变量域! - get '/define_route/:name' do - # 针对 '/define_route/:name' 的请求变量域 - @value = 42 - - settings.get("/#{params[:name]}") do - # 针对 "/#{params[:name]}" 的请求变量域 - @value # => nil (并不是相同的请求) - end - - "Route defined!" - end -end -~~~~ - -在以下情况将获得请求变量域: - -- get/head/post/put/delete 代码块 - -- 前置/后置 过滤器 - -- 辅助方法 - -- 模板/视图 - -### 代理变量域 - -代理变量域只是把方法转送到类变量域。可是, -他并非表现得100%类似于类变量域, 因为你并不能获得类的绑定: -只有显式地标记为供代理使用的方法才是可用的, -而且你不能和类变量域共享变量/状态。(解释:你有了一个不同的 \`self\`)。 -你可以显式地增加方法代理,通过调用 -`Sinatra::Delegator.delegate :method_name`。 - -在以下情况将获得代理变量域: - -- 顶层的绑定,如果你做过 `require "sinatra"` - -- 在扩展了 \`Sinatra::Delegator\` mixin的对象 - -自己在这里看一下代码: [Sinatra::Delegator -mixin](http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/base.rb#L1128) -已经 -[被包含进了主命名空间](http://github.com/sinatra/sinatra/blob/ceac46f0bc129a6e994a06100aa854f606fe5992/lib/sinatra/main.rb#L28)。 - -## 命令行 - -Sinatra 应用可以被直接运行: - - ruby myapp.rb [-h] [-x] [-e ENVIRONMENT] [-p PORT] [-o HOST] [-s HANDLER] - -选项是: - - -h # help - -p # 设定端口 (默认是 4567) - -o # 设定主机名 (默认是 0.0.0.0) - -e # 设定环境 (默认是 development) - -s # 限定 rack 服务器/处理器 (默认是 thin) - -x # 打开互斥锁 (默认是 off) - -## 必要条件 - -推荐在 Ruby 1.8.7, 1.9.2, JRuby 或者 Rubinius 上安装Sinatra。 - -下面的Ruby版本是官方支持的: - -
-
Ruby 1.8.6
-
- 不推荐在1.8.6上安装Sinatra, 但是直到Sinatra - 1.3.0发布才会放弃对它的支持。 RDoc 和 - CoffeScript模板不被这个Ruby版本支持。 - 1.8.6在它的Hash实现中包含一个内存泄漏问题, - 该问题会被1.1.1版本之前的Sinatra引发。 - 当前版本使用性能下降的代价排除了这个问题。你需要把Rack降级到1.1.x, - 因为Rack \>= 1.2不再支持1.8.6。 -
- -
Ruby 1.8.7
-
- 1.8.7 被完全支持,但是,如果没有特别原因, 我们推荐你升级到 1.9.2 - 或者切换到 JRuby 或者 Rubinius. -
- -
Ruby 1.9.2
-
- 1.9.2 被支持而且推荐。注意 Radius 和 Markaby 模板并不和1.9兼容。不要使用 - 1.9.2p0, 它被已知会产生 segmentation faults. -
- -
Rubinius
-
- Rubinius 被官方支持 (Rubinius \>= 1.2.2), 除了Textile模板。 -
- -
JRuby
-
- JRuby 被官方支持 (JRuby \>= 1.5.6)。 目前未知和第三方模板库有关的问题, - 但是,如果你选择了JRuby,请查看一下JRuby rack 处理器, 因为 Thin web - 服务器还没有在JRuby上获得支持。 -
-
- -我们也会时刻关注新的Ruby版本。 - -下面的 Ruby 实现没有被官方支持, 但是已知可以运行 Sinatra: - -- JRuby 和 Rubinius 老版本 - -- MacRuby - -- Maglev - -- IronRuby - -- Ruby 1.9.0 and 1.9.1 - -不被官方支持的意思是,如果在不被支持的平台上有运行错误, -我们假定不是我们的问题,而是平台的问题。 - -Sinatra应该会运行在任何支持上述Ruby实现的操作系统。 - -## 紧追前沿 - -如果你喜欢使用 Sinatra 的最新鲜的代码,请放心的使用 master -分支来运行你的程序,它会非常的稳定。 - - cd myapp - git clone git://github.com/sinatra/sinatra.git - ruby -Isinatra/lib myapp.rb - -我们也会不定期的发布预发布gems,所以你也可以运行 - - gem install sinatra --pre - -来获得最新的特性。 - -### 通过Bundler - -如果你想使用最新的Sinatra运行你的应用,通过 -[Bundler](http://gembundler.com/) 是推荐的方式。 - -首先,安装bundler,如果你还没有安装: - - gem install bundler - -然后,在你的项目目录下,创建一个 `Gemfile`: - -~~~~ ruby -source :rubygems -gem 'sinatra', :git => "git://github.com/sinatra/sinatra.git" - -# 其他的依赖关系 -gem 'haml' # 举例,如果你想用haml -gem 'activerecord', '~> 3.0' # 也许你还需要 ActiveRecord 3.x -~~~~ - -请注意在这里你需要列出你的应用的所有依赖关系。 Sinatra的直接依赖关系 -(Rack and Tilt) 将会, 自动被Bundler获取和添加。 - -现在你可以像这样运行你的应用: - - bundle exec ruby myapp.rb - -### 使用自己的 - -创建一个本地克隆并通过 `sinatra/lib` 目录运行你的应用, 通过 -`$LOAD_PATH`: - - cd myapp - git clone git://github.com/sinatra/sinatra.git - ruby -Isinatra/lib myapp.rb - -为了在未来更新 Sinatra 源代码: - - cd myapp/sinatra - git pull - -### 全局安装 - -你可以自行编译 gem : - - git clone git://github.com/sinatra/sinatra.git - cd sinatra - rake sinatra.gemspec - rake install - -如果你以root身份安装 gems,最后一步应该是 - - sudo rake install - -## 更多 - -- [项目主页(英文)](http://www.sinatrarb.com/) - 更多的文档, - 新闻,和其他资源的链接。 - -- [贡献](http://www.sinatrarb.com/contributing) - 找到了一个bug? - 需要帮助?有了一个 patch? - -- [问题追踪](http://github.com/sinatra/sinatra/issues) - -- [Twitter](http://twitter.com/sinatra) - -- [邮件列表](http://groups.google.com/group/sinatrarb/topics) - -- [IRC: \#sinatra](irc://chat.freenode.net/#sinatra) on - [freenode.net](http://freenode.net) - -- [Sinatra宝典](http://sinatra-book.gittr.com/) Cookbook教程 - -- [Sinatra使用技巧](http://recipes.sinatrarb.com/) 网友贡献的实用技巧 - -- [最新版本](http://rubydoc.info/gems/sinatra)API文档;[http://rubydoc.info](http://rubydoc.info)的[当前HEAD](http://rubydoc.info/github/sinatra/sinatra) - -- [CI服务器](http://travis-ci.org/sinatra/sinatra) diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/Rakefile b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/Rakefile deleted file mode 100644 index d4a6bf1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/Rakefile +++ /dev/null @@ -1,199 +0,0 @@ -require 'rake/clean' -require 'rake/testtask' -require 'fileutils' -require 'date' - -# CI Reporter is only needed for the CI -begin - require 'ci/reporter/rake/test_unit' -rescue LoadError -end - -task :default => :test -task :spec => :test - -CLEAN.include "**/*.rbc" - -def source_version - @source_version ||= begin - load './lib/sinatra/version.rb' - Sinatra::VERSION - end -end - -def prev_feature - source_version.gsub(/^(\d\.)(\d+)\..*$/) { $1 + ($2.to_i - 1).to_s } -end - -def prev_version - return prev_feature + '.0' if source_version.end_with? '.0' - source_version.gsub(/\d+$/) { |s| s.to_i - 1 } -end - -# SPECS =============================================================== - -task :test do - ENV['LANG'] = 'C' - ENV.delete 'LC_CTYPE' -end - -Rake::TestTask.new(:test) do |t| - t.test_files = FileList['test/*_test.rb'] - t.ruby_opts = ['-rubygems'] if defined? Gem - t.ruby_opts << '-I.' - t.warning = true -end - -Rake::TestTask.new(:"test:core") do |t| - core_tests = %w[base delegator encoding extensions filter - helpers mapped_error middleware radius rdoc - readme request response result route_added_hook - routing server settings sinatra static templates] - t.test_files = core_tests.map {|n| "test/#{n}_test.rb"} - t.ruby_opts = ["-rubygems"] if defined? Gem - t.ruby_opts << "-I." - t.warning = true -end - -# Rcov ================================================================ - -namespace :test do - desc 'Measures test coverage' - task :coverage do - rm_f "coverage" - sh "rcov -Ilib test/*_test.rb" - end -end - -# Website ============================================================= - -desc 'Generate RDoc under doc/api' -task 'doc' => ['doc:api'] -task('doc:api') { sh "yardoc -o doc/api" } -CLEAN.include 'doc/api' - -# README =============================================================== - -task :add_template, [:name] do |t, args| - Dir.glob('README.*') do |file| - code = File.read(file) - if code =~ /^===.*#{args.name.capitalize}/ - puts "Already covered in #{file}" - else - template = code[/===[^\n]*Liquid.*index\.liquid<\/tt>[^\n]*/m] - if !template - puts "Liquid not found in #{file}" - else - puts "Adding section to #{file}" - template = template.gsub(/Liquid/, args.name.capitalize).gsub(/liquid/, args.name.downcase) - code.gsub! /^(\s*===.*CoffeeScript)/, "\n" << template << "\n\\1" - File.open(file, "w") { |f| f << code } - end - end - end -end - -# Thanks in announcement =============================================== - -team = ["Ryan Tomayko", "Blake Mizerany", "Simon Rozet", "Konstantin Haase"] -desc "list of contributors" -task :thanks, [:release,:backports] do |t, a| - a.with_defaults :release => "#{prev_version}..HEAD", - :backports => "#{prev_feature}.0..#{prev_feature}.x" - included = `git log --format=format:"%aN\t%s" #{a.release}`.lines.map { |l| l.force_encoding('binary') } - excluded = `git log --format=format:"%aN\t%s" #{a.backports}`.lines.map { |l| l.force_encoding('binary') } - commits = (included - excluded).group_by { |c| c[/^[^\t]+/] } - authors = commits.keys.sort_by { |n| - commits[n].size } - team - puts authors[0..-2].join(', ') << " and " << authors.last, - "(based on commits included in #{a.release}, but not in #{a.backports})" -end - -desc "list of authors" -task :authors, [:commit_range, :format, :sep] do |t, a| - a.with_defaults :format => "%s (%d)", :sep => ", ", :commit_range => '--all' - authors = Hash.new(0) - blake = "Blake Mizerany" - overall = 0 - mapping = { - "blake.mizerany@gmail.com" => blake, "bmizerany" => blake, - "a_user@mac.com" => blake, "ichverstehe" => "Harry Vangberg", - "Wu Jiang (nouse)" => "Wu Jiang" } - `git shortlog -s #{a.commit_range}`.lines.map do |line| - line = line.force_encoding 'binary' if line.respond_to? :force_encoding - num, name = line.split("\t", 2).map(&:strip) - authors[mapping[name] || name] += num.to_i - overall += num.to_i - end - puts "#{overall} commits by #{authors.count} authors:" - puts authors.sort_by { |n,c| -c }.map { |e| a.format % e }.join(a.sep) -end - -desc "generates TOC" -task :toc, [:readme] do |t, a| - a.with_defaults :readme => 'README.md' - - def self.link(title) - title.downcase.gsub(/(?!-)\W /, '-').gsub(' ', '-').gsub(/(?!-)\W/, '') - end - - puts "* [Sinatra](#sinatra)" - title = Regexp.new('(?<=\* )(.*)') # so Ruby 1.8 doesn't complain - File.binread(a.readme).scan(/^##.*/) do |line| - puts line.gsub(/#(?=#)/, ' ').gsub('#', '*').gsub(title) { "[#{$1}](##{link($1)})" } - end -end - -# PACKAGING ============================================================ - -if defined?(Gem) - # Load the gemspec using the same limitations as github - def spec - require 'rubygems' unless defined? Gem::Specification - @spec ||= eval(File.read('sinatra.gemspec')) - end - - def package(ext='') - "pkg/sinatra-#{spec.version}" + ext - end - - desc 'Build packages' - task :package => %w[.gem .tar.gz].map {|e| package(e)} - - desc 'Build and install as local gem' - task :install => package('.gem') do - sh "gem install #{package('.gem')}" - end - - directory 'pkg/' - CLOBBER.include('pkg') - - file package('.gem') => %w[pkg/ sinatra.gemspec] + spec.files do |f| - sh "gem build sinatra.gemspec" - mv File.basename(f.name), f.name - end - - file package('.tar.gz') => %w[pkg/] + spec.files do |f| - sh <<-SH - git archive \ - --prefix=sinatra-#{source_version}/ \ - --format=tar \ - HEAD | gzip > #{f.name} - SH - end - - task 'release' => ['test', package('.gem')] do - if File.binread("CHANGES") =~ /= \d\.\d\.\d . not yet released$/i - fail 'please update changes first' unless %x{git symbolic-ref HEAD} == "refs/heads/prerelease\n" - end - - sh <<-SH - gem install #{package('.gem')} --local && - gem push #{package('.gem')} && - git commit --allow-empty -a -m '#{source_version} release' && - git tag -s v#{source_version} -m '#{source_version} release' && - git tag -s #{source_version} -m '#{source_version} release' && - git push && (git push sinatra || true) && - git push --tags && (git push sinatra --tags || true) - SH - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/chat.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/chat.rb deleted file mode 100755 index 8e47b7d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/chat.rb +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env ruby -I ../lib -I lib -# coding: utf-8 -require 'sinatra' -set :server, 'thin' -connections = [] - -get '/' do - halt erb(:login) unless params[:user] - erb :chat, :locals => { :user => params[:user].gsub(/\W/, '') } -end - -get '/stream', :provides => 'text/event-stream' do - stream :keep_open do |out| - connections << out - out.callback { connections.delete(out) } - end -end - -post '/' do - connections.each { |out| out << "data: #{params[:msg]}\n\n" } - 204 # response without entity body -end - -__END__ - -@@ layout - - - Super Simple Chat with Sinatra - - - - <%= yield %> - - -@@ login -
- - - -
- -@@ chat -

-
- -
- - - diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/simple.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/simple.rb deleted file mode 100755 index 2697f94..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/simple.rb +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env ruby -I ../lib -I lib -require 'sinatra' -get('/') { 'this is a simple app' } diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/stream.ru b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/stream.ru deleted file mode 100644 index 074c66b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/examples/stream.ru +++ /dev/null @@ -1,26 +0,0 @@ -# this example does *not* work properly with WEBrick -# -# run *one* of these: -# -# rackup -s mongrel stream.ru # gem install mongrel -# thin -R stream.ru start # gem install thin -# unicorn stream.ru # gem install unicorn -# puma stream.ru # gem install puma - -require 'sinatra/base' - -class Stream < Sinatra::Base - get '/' do - content_type :txt - - stream do |out| - out << "It's gonna be legen -\n" - sleep 0.5 - out << " (wait for it) \n" - sleep 1 - out << "- dary!\n" - end - end -end - -run Stream diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra.rb deleted file mode 100644 index ea4c68c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra.rb +++ /dev/null @@ -1,4 +0,0 @@ -require 'sinatra/base' -require 'sinatra/main' - -enable :inline_templates diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/base.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/base.rb deleted file mode 100644 index e21aa04..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/base.rb +++ /dev/null @@ -1,2044 +0,0 @@ -# external dependencies -require 'rack' -require 'tilt' -require 'rack/protection' - -# stdlib dependencies -require 'thread' -require 'time' -require 'uri' - -# other files we need -require 'sinatra/show_exceptions' -require 'sinatra/version' - -module Sinatra - # The request object. See Rack::Request for more info: - # http://rack.rubyforge.org/doc/classes/Rack/Request.html - class Request < Rack::Request - HEADER_PARAM = /\s*[\w.]+=(?:[\w.]+|"(?:[^"\\]|\\.)*")?\s*/ - HEADER_VALUE_WITH_PARAMS = /(?:(?:\w+|\*)\/(?:\w+(?:\.|\-|\+)?|\*)*)\s*(?:;#{HEADER_PARAM})*/ - - # Returns an array of acceptable media types for the response - def accept - @env['sinatra.accept'] ||= begin - if @env.include? 'HTTP_ACCEPT' and @env['HTTP_ACCEPT'].to_s != '' - @env['HTTP_ACCEPT'].to_s.scan(HEADER_VALUE_WITH_PARAMS). - map! { |e| AcceptEntry.new(e) }.sort - else - [AcceptEntry.new('*/*')] - end - end - end - - def accept?(type) - preferred_type(type).to_s.include?(type) - end - - def preferred_type(*types) - accepts = accept # just evaluate once - return accepts.first if types.empty? - types.flatten! - return types.first if accepts.empty? - accepts.detect do |pattern| - type = types.detect { |t| File.fnmatch(pattern, t) } - return type if type - end - end - - alias secure? ssl? - - def forwarded? - @env.include? "HTTP_X_FORWARDED_HOST" - end - - def safe? - get? or head? or options? or trace? - end - - def idempotent? - safe? or put? or delete? or link? or unlink? - end - - def link? - request_method == "LINK" - end - - def unlink? - request_method == "UNLINK" - end - - private - - class AcceptEntry - attr_accessor :params - - def initialize(entry) - params = entry.scan(HEADER_PARAM).map! do |s| - key, value = s.strip.split('=', 2) - value = value[1..-2].gsub(/\\(.)/, '\1') if value.start_with?('"') - [key, value] - end - - @entry = entry - @type = entry[/[^;]+/].delete(' ') - @params = Hash[params] - @q = @params.delete('q') { 1.0 }.to_f - end - - def <=>(other) - other.priority <=> self.priority - end - - def priority - # We sort in descending order; better matches should be higher. - [ @q, -@type.count('*'), @params.size ] - end - - def to_str - @type - end - - def to_s(full = false) - full ? entry : to_str - end - - def respond_to?(*args) - super or to_str.respond_to?(*args) - end - - def method_missing(*args, &block) - to_str.send(*args, &block) - end - end - end - - # The response object. See Rack::Response and Rack::Response::Helpers for - # more info: - # http://rack.rubyforge.org/doc/classes/Rack/Response.html - # http://rack.rubyforge.org/doc/classes/Rack/Response/Helpers.html - class Response < Rack::Response - DROP_BODY_RESPONSES = [204, 205, 304] - def initialize(*) - super - headers['Content-Type'] ||= 'text/html' - end - - def body=(value) - value = value.body while Rack::Response === value - @body = String === value ? [value.to_str] : value - end - - def each - block_given? ? super : enum_for(:each) - end - - def finish - result = body - - if drop_content_info? - headers.delete "Content-Length" - headers.delete "Content-Type" - end - - if drop_body? - close - result = [] - end - - if calculate_content_length? - # if some other code has already set Content-Length, don't muck with it - # currently, this would be the static file-handler - headers["Content-Length"] = body.inject(0) { |l, p| l + Rack::Utils.bytesize(p) }.to_s - end - - [status.to_i, headers, result] - end - - private - - def calculate_content_length? - headers["Content-Type"] and not headers["Content-Length"] and Array === body - end - - def drop_content_info? - status.to_i / 100 == 1 or drop_body? - end - - def drop_body? - DROP_BODY_RESPONSES.include?(status.to_i) - end - end - - # Some Rack handlers (Thin, Rainbows!) implement an extended body object protocol, however, - # some middleware (namely Rack::Lint) will break it by not mirroring the methods in question. - # This middleware will detect an extended body object and will make sure it reaches the - # handler directly. We do this here, so our middleware and middleware set up by the app will - # still be able to run. - class ExtendedRack < Struct.new(:app) - def call(env) - result, callback = app.call(env), env['async.callback'] - return result unless callback and async?(*result) - after_response { callback.call result } - setup_close(env, *result) - throw :async - end - - private - - def setup_close(env, status, headers, body) - return unless body.respond_to? :close and env.include? 'async.close' - env['async.close'].callback { body.close } - env['async.close'].errback { body.close } - end - - def after_response(&block) - raise NotImplementedError, "only supports EventMachine at the moment" unless defined? EventMachine - EventMachine.next_tick(&block) - end - - def async?(status, headers, body) - return true if status == -1 - body.respond_to? :callback and body.respond_to? :errback - end - end - - # Behaves exactly like Rack::CommonLogger with the notable exception that it does nothing, - # if another CommonLogger is already in the middleware chain. - class CommonLogger < Rack::CommonLogger - def call(env) - env['sinatra.commonlogger'] ? @app.call(env) : super - end - - superclass.class_eval do - alias call_without_check call unless method_defined? :call_without_check - def call(env) - env['sinatra.commonlogger'] = true - call_without_check(env) - end - end - end - - class NotFound < NameError #:nodoc: - def http_status; 404 end - end - - # Methods available to routes, before/after filters, and views. - module Helpers - # Set or retrieve the response status code. - def status(value = nil) - response.status = value if value - response.status - end - - # Set or retrieve the response body. When a block is given, - # evaluation is deferred until the body is read with #each. - def body(value = nil, &block) - if block_given? - def block.each; yield(call) end - response.body = block - elsif value - headers.delete 'Content-Length' unless request.head? || value.is_a?(Rack::File) || value.is_a?(Stream) - response.body = value - else - response.body - end - end - - # Halt processing and redirect to the URI provided. - def redirect(uri, *args) - if env['HTTP_VERSION'] == 'HTTP/1.1' and env["REQUEST_METHOD"] != 'GET' - status 303 - else - status 302 - end - - # According to RFC 2616 section 14.30, "the field value consists of a - # single absolute URI" - response['Location'] = uri(uri.to_s, settings.absolute_redirects?, settings.prefixed_redirects?) - halt(*args) - end - - # Generates the absolute URI for a given path in the app. - # Takes Rack routers and reverse proxies into account. - def uri(addr = nil, absolute = true, add_script_name = true) - return addr if addr =~ /\A[A-z][A-z0-9\+\.\-]*:/ - uri = [host = ""] - if absolute - host << "http#{'s' if request.secure?}://" - if request.forwarded? or request.port != (request.secure? ? 443 : 80) - host << request.host_with_port - else - host << request.host - end - end - uri << request.script_name.to_s if add_script_name - uri << (addr ? addr : request.path_info).to_s - File.join uri - end - - alias url uri - alias to uri - - # Halt processing and return the error status provided. - def error(code, body = nil) - code, body = 500, code.to_str if code.respond_to? :to_str - response.body = body unless body.nil? - halt code - end - - # Halt processing and return a 404 Not Found. - def not_found(body = nil) - error 404, body - end - - # Set multiple response headers with Hash. - def headers(hash = nil) - response.headers.merge! hash if hash - response.headers - end - - # Access the underlying Rack session. - def session - request.session - end - - # Access shared logger object. - def logger - request.logger - end - - # Look up a media type by file extension in Rack's mime registry. - def mime_type(type) - Base.mime_type(type) - end - - # Set the Content-Type of the response body given a media type or file - # extension. - def content_type(type = nil, params = {}) - return response['Content-Type'] unless type - default = params.delete :default - mime_type = mime_type(type) || default - fail "Unknown media type: %p" % type if mime_type.nil? - mime_type = mime_type.dup - unless params.include? :charset or settings.add_charset.all? { |p| not p === mime_type } - params[:charset] = params.delete('charset') || settings.default_encoding - end - params.delete :charset if mime_type.include? 'charset' - unless params.empty? - mime_type << (mime_type.include?(';') ? ', ' : ';') - mime_type << params.map do |key, val| - val = val.inspect if val =~ /[";,]/ - "#{key}=#{val}" - end.join(', ') - end - response['Content-Type'] = mime_type - end - - # Set the Content-Disposition to "attachment" with the specified filename, - # instructing the user agents to prompt to save. - def attachment(filename = nil, disposition = 'attachment') - response['Content-Disposition'] = disposition.to_s - if filename - params = '; filename="%s"' % File.basename(filename) - response['Content-Disposition'] << params - ext = File.extname(filename) - content_type(ext) unless response['Content-Type'] or ext.empty? - end - end - - # Use the contents of the file at +path+ as the response body. - def send_file(path, opts = {}) - if opts[:type] or not response['Content-Type'] - content_type opts[:type] || File.extname(path), :default => 'application/octet-stream' - end - - disposition = opts[:disposition] - filename = opts[:filename] - disposition = 'attachment' if disposition.nil? and filename - filename = path if filename.nil? - attachment(filename, disposition) if disposition - - last_modified opts[:last_modified] if opts[:last_modified] - - file = Rack::File.new nil - file.path = path - result = file.serving env - result[1].each { |k,v| headers[k] ||= v } - headers['Content-Length'] = result[1]['Content-Length'] - opts[:status] &&= Integer(opts[:status]) - halt opts[:status] || result[0], result[2] - rescue Errno::ENOENT - not_found - end - - # Class of the response body in case you use #stream. - # - # Three things really matter: The front and back block (back being the - # block generating content, front the one sending it to the client) and - # the scheduler, integrating with whatever concurrency feature the Rack - # handler is using. - # - # Scheduler has to respond to defer and schedule. - class Stream - def self.schedule(*) yield end - def self.defer(*) yield end - - def initialize(scheduler = self.class, keep_open = false, &back) - @back, @scheduler, @keep_open = back.to_proc, scheduler, keep_open - @callbacks, @closed = [], false - end - - def close - return if @closed - @closed = true - @scheduler.schedule { @callbacks.each { |c| c.call }} - end - - def each(&front) - @front = front - @scheduler.defer do - begin - @back.call(self) - rescue Exception => e - @scheduler.schedule { raise e } - end - close unless @keep_open - end - end - - def <<(data) - @scheduler.schedule { @front.call(data.to_s) } - self - end - - def callback(&block) - return yield if @closed - @callbacks << block - end - - alias errback callback - - def closed? - @closed - end - end - - # Allows to start sending data to the client even though later parts of - # the response body have not yet been generated. - # - # The close parameter specifies whether Stream#close should be called - # after the block has been executed. This is only relevant for evented - # servers like Thin or Rainbows. - def stream(keep_open = false) - scheduler = env['async.callback'] ? EventMachine : Stream - current = @params.dup - body Stream.new(scheduler, keep_open) { |out| with_params(current) { yield(out) } } - end - - # Specify response freshness policy for HTTP caches (Cache-Control header). - # Any number of non-value directives (:public, :private, :no_cache, - # :no_store, :must_revalidate, :proxy_revalidate) may be passed along with - # a Hash of value directives (:max_age, :min_stale, :s_max_age). - # - # cache_control :public, :must_revalidate, :max_age => 60 - # => Cache-Control: public, must-revalidate, max-age=60 - # - # See RFC 2616 / 14.9 for more on standard cache control directives: - # http://tools.ietf.org/html/rfc2616#section-14.9.1 - def cache_control(*values) - if values.last.kind_of?(Hash) - hash = values.pop - hash.reject! { |k,v| v == false } - hash.reject! { |k,v| values << k if v == true } - else - hash = {} - end - - values.map! { |value| value.to_s.tr('_','-') } - hash.each do |key, value| - key = key.to_s.tr('_', '-') - value = value.to_i if key == "max-age" - values << "#{key}=#{value}" - end - - response['Cache-Control'] = values.join(', ') if values.any? - end - - # Set the Expires header and Cache-Control/max-age directive. Amount - # can be an integer number of seconds in the future or a Time object - # indicating when the response should be considered "stale". The remaining - # "values" arguments are passed to the #cache_control helper: - # - # expires 500, :public, :must_revalidate - # => Cache-Control: public, must-revalidate, max-age=60 - # => Expires: Mon, 08 Jun 2009 08:50:17 GMT - # - def expires(amount, *values) - values << {} unless values.last.kind_of?(Hash) - - if amount.is_a? Integer - time = Time.now + amount.to_i - max_age = amount - else - time = time_for amount - max_age = time - Time.now - end - - values.last.merge!(:max_age => max_age) - cache_control(*values) - - response['Expires'] = time.httpdate - end - - # Set the last modified time of the resource (HTTP 'Last-Modified' header) - # and halt if conditional GET matches. The +time+ argument is a Time, - # DateTime, or other object that responds to +to_time+. - # - # When the current request includes an 'If-Modified-Since' header that is - # equal or later than the time specified, execution is immediately halted - # with a '304 Not Modified' response. - def last_modified(time) - return unless time - time = time_for time - response['Last-Modified'] = time.httpdate - return if env['HTTP_IF_NONE_MATCH'] - - if status == 200 and env['HTTP_IF_MODIFIED_SINCE'] - # compare based on seconds since epoch - since = Time.httpdate(env['HTTP_IF_MODIFIED_SINCE']).to_i - halt 304 if since >= time.to_i - end - - if (success? or status == 412) and env['HTTP_IF_UNMODIFIED_SINCE'] - # compare based on seconds since epoch - since = Time.httpdate(env['HTTP_IF_UNMODIFIED_SINCE']).to_i - halt 412 if since < time.to_i - end - rescue ArgumentError - end - - ETAG_KINDS = [:strong, :weak] - # Set the response entity tag (HTTP 'ETag' header) and halt if conditional - # GET matches. The +value+ argument is an identifier that uniquely - # identifies the current version of the resource. The +kind+ argument - # indicates whether the etag should be used as a :strong (default) or :weak - # cache validator. - # - # When the current request includes an 'If-None-Match' header with a - # matching etag, execution is immediately halted. If the request method is - # GET or HEAD, a '304 Not Modified' response is sent. - def etag(value, options = {}) - # Before touching this code, please double check RFC 2616 14.24 and 14.26. - options = {:kind => options} unless Hash === options - kind = options[:kind] || :strong - new_resource = options.fetch(:new_resource) { request.post? } - - unless ETAG_KINDS.include?(kind) - raise ArgumentError, ":strong or :weak expected" - end - - value = '"%s"' % value - value = "W/#{value}" if kind == :weak - response['ETag'] = value - - if success? or status == 304 - if etag_matches? env['HTTP_IF_NONE_MATCH'], new_resource - halt(request.safe? ? 304 : 412) - end - - if env['HTTP_IF_MATCH'] - halt 412 unless etag_matches? env['HTTP_IF_MATCH'], new_resource - end - end - end - - # Sugar for redirect (example: redirect back) - def back - request.referer - end - - # whether or not the status is set to 1xx - def informational? - status.between? 100, 199 - end - - # whether or not the status is set to 2xx - def success? - status.between? 200, 299 - end - - # whether or not the status is set to 3xx - def redirect? - status.between? 300, 399 - end - - # whether or not the status is set to 4xx - def client_error? - status.between? 400, 499 - end - - # whether or not the status is set to 5xx - def server_error? - status.between? 500, 599 - end - - # whether or not the status is set to 404 - def not_found? - status == 404 - end - - # Generates a Time object from the given value. - # Used by #expires and #last_modified. - def time_for(value) - if value.respond_to? :to_time - value.to_time - elsif value.is_a? Time - value - elsif value.respond_to? :new_offset - # DateTime#to_time does the same on 1.9 - d = value.new_offset 0 - t = Time.utc d.year, d.mon, d.mday, d.hour, d.min, d.sec + d.sec_fraction - t.getlocal - elsif value.respond_to? :mday - # Date#to_time does the same on 1.9 - Time.local(value.year, value.mon, value.mday) - elsif value.is_a? Numeric - Time.at value - else - Time.parse value.to_s - end - rescue ArgumentError => boom - raise boom - rescue Exception - raise ArgumentError, "unable to convert #{value.inspect} to a Time object" - end - - private - - # Helper method checking if a ETag value list includes the current ETag. - def etag_matches?(list, new_resource = request.post?) - return !new_resource if list == '*' - list.to_s.split(/\s*,\s*/).include? response['ETag'] - end - - def with_params(temp_params) - original, @params = @params, temp_params - yield - ensure - @params = original if original - end - end - - private - - # Template rendering methods. Each method takes the name of a template - # to render as a Symbol and returns a String with the rendered output, - # as well as an optional hash with additional options. - # - # `template` is either the name or path of the template as symbol - # (Use `:'subdir/myview'` for views in subdirectories), or a string - # that will be rendered. - # - # Possible options are: - # :content_type The content type to use, same arguments as content_type. - # :layout If set to something falsy, no layout is rendered, otherwise - # the specified layout is used (Ignored for `sass` and `less`) - # :layout_engine Engine to use for rendering the layout. - # :locals A hash with local variables that should be available - # in the template - # :scope If set, template is evaluate with the binding of the given - # object rather than the application instance. - # :views Views directory to use. - module Templates - module ContentTyped - attr_accessor :content_type - end - - def initialize - super - @default_layout = :layout - @preferred_extension = nil - end - - def erb(template, options = {}, locals = {}, &block) - render(:erb, template, options, locals, &block) - end - - def erubis(template, options = {}, locals = {}) - warn "Sinatra::Templates#erubis is deprecated and will be removed, use #erb instead.\n" \ - "If you have Erubis installed, it will be used automatically." - render :erubis, template, options, locals - end - - def haml(template, options = {}, locals = {}, &block) - render(:haml, template, options, locals, &block) - end - - def sass(template, options = {}, locals = {}) - options.merge! :layout => false, :default_content_type => :css - render :sass, template, options, locals - end - - def scss(template, options = {}, locals = {}) - options.merge! :layout => false, :default_content_type => :css - render :scss, template, options, locals - end - - def less(template, options = {}, locals = {}) - options.merge! :layout => false, :default_content_type => :css - render :less, template, options, locals - end - - def stylus(template, options={}, locals={}) - options.merge! :layout => false, :default_content_type => :css - render :styl, template, options, locals - end - - def builder(template = nil, options = {}, locals = {}, &block) - options[:default_content_type] = :xml - render_ruby(:builder, template, options, locals, &block) - end - - def liquid(template, options = {}, locals = {}, &block) - render(:liquid, template, options, locals, &block) - end - - def markdown(template, options = {}, locals = {}) - render :markdown, template, options, locals - end - - def textile(template, options = {}, locals = {}) - render :textile, template, options, locals - end - - def rdoc(template, options = {}, locals = {}) - render :rdoc, template, options, locals - end - - def asciidoc(template, options = {}, locals = {}) - render :asciidoc, template, options, locals - end - - def radius(template, options = {}, locals = {}) - render :radius, template, options, locals - end - - def markaby(template = nil, options = {}, locals = {}, &block) - render_ruby(:mab, template, options, locals, &block) - end - - def coffee(template, options = {}, locals = {}) - options.merge! :layout => false, :default_content_type => :js - render :coffee, template, options, locals - end - - def nokogiri(template = nil, options = {}, locals = {}, &block) - options[:default_content_type] = :xml - render_ruby(:nokogiri, template, options, locals, &block) - end - - def slim(template, options = {}, locals = {}, &block) - render(:slim, template, options, locals, &block) - end - - def creole(template, options = {}, locals = {}) - render :creole, template, options, locals - end - - def mediawiki(template, options = {}, locals = {}) - render :mediawiki, template, options, locals - end - - def wlang(template, options = {}, locals = {}, &block) - render(:wlang, template, options, locals, &block) - end - - def yajl(template, options = {}, locals = {}) - options[:default_content_type] = :json - render :yajl, template, options, locals - end - - def rabl(template, options = {}, locals = {}) - Rabl.register! - render :rabl, template, options, locals - end - - # Calls the given block for every possible template file in views, - # named name.ext, where ext is registered on engine. - def find_template(views, name, engine) - yield ::File.join(views, "#{name}.#{@preferred_extension}") - Tilt.mappings.each do |ext, engines| - next unless ext != @preferred_extension and engines.include? engine - yield ::File.join(views, "#{name}.#{ext}") - end - end - - private - - # logic shared between builder and nokogiri - def render_ruby(engine, template, options = {}, locals = {}, &block) - options, template = template, nil if template.is_a?(Hash) - template = Proc.new { block } if template.nil? - render engine, template, options, locals - end - - def render(engine, data, options = {}, locals = {}, &block) - # merge app-level options - engine_options = settings.respond_to?(engine) ? settings.send(engine) : {} - options.merge!(engine_options) { |key, v1, v2| v1 } - - # extract generic options - locals = options.delete(:locals) || locals || {} - views = options.delete(:views) || settings.views || "./views" - layout = options[:layout] - layout = false if layout.nil? && options.include?(:layout) - eat_errors = layout.nil? - layout = engine_options[:layout] if layout.nil? or (layout == true && engine_options[:layout] != false) - layout = @default_layout if layout.nil? or layout == true - layout_options = options.delete(:layout_options) || {} - content_type = options.delete(:content_type) || options.delete(:default_content_type) - layout_engine = options.delete(:layout_engine) || engine - scope = options.delete(:scope) || self - options.delete(:layout) - - # set some defaults - options[:outvar] ||= '@_out_buf' - options[:default_encoding] ||= settings.default_encoding - - # compile and render template - begin - layout_was = @default_layout - @default_layout = false - template = compile_template(engine, data, options, views) - output = template.render(scope, locals, &block) - ensure - @default_layout = layout_was - end - - # render layout - if layout - options = options.merge(:views => views, :layout => false, :eat_errors => eat_errors, :scope => scope). - merge!(layout_options) - catch(:layout_missing) { return render(layout_engine, layout, options, locals) { output } } - end - - output.extend(ContentTyped).content_type = content_type if content_type - output - end - - def compile_template(engine, data, options, views) - eat_errors = options.delete :eat_errors - template_cache.fetch engine, data, options, views do - template = Tilt[engine] - raise "Template engine not found: #{engine}" if template.nil? - - case data - when Symbol - body, path, line = settings.templates[data] - if body - body = body.call if body.respond_to?(:call) - template.new(path, line.to_i, options) { body } - else - found = false - @preferred_extension = engine.to_s - find_template(views, data, template) do |file| - path ||= file # keep the initial path rather than the last one - if found = File.exist?(file) - path = file - break - end - end - throw :layout_missing if eat_errors and not found - template.new(path, 1, options) - end - when Proc, String - body = data.is_a?(String) ? Proc.new { data } : data - path, line = settings.caller_locations.first - template.new(path, line.to_i, options, &body) - else - raise ArgumentError, "Sorry, don't know how to render #{data.inspect}." - end - end - end - end - - # Base class for all Sinatra applications and middleware. - class Base - include Rack::Utils - include Helpers - include Templates - - URI_INSTANCE = URI.const_defined?(:Parser) ? URI::Parser.new : URI - - attr_accessor :app, :env, :request, :response, :params - attr_reader :template_cache - - def initialize(app = nil) - super() - @app = app - @template_cache = Tilt::Cache.new - yield self if block_given? - end - - # Rack call interface. - def call(env) - dup.call!(env) - end - - def call!(env) # :nodoc: - @env = env - @request = Request.new(env) - @response = Response.new - @params = indifferent_params(@request.params) - template_cache.clear if settings.reload_templates - force_encoding(@params) - - @response['Content-Type'] = nil - invoke { dispatch! } - invoke { error_block!(response.status) } unless @env['sinatra.error'] - - unless @response['Content-Type'] - if Array === body and body[0].respond_to? :content_type - content_type body[0].content_type - else - content_type :html - end - end - - @response.finish - end - - # Access settings defined with Base.set. - def self.settings - self - end - - # Access settings defined with Base.set. - def settings - self.class.settings - end - - def options - warn "Sinatra::Base#options is deprecated and will be removed, " \ - "use #settings instead." - settings - end - - # Exit the current block, halts any further processing - # of the request, and returns the specified response. - def halt(*response) - response = response.first if response.length == 1 - throw :halt, response - end - - # Pass control to the next matching route. - # If there are no more matching routes, Sinatra will - # return a 404 response. - def pass(&block) - throw :pass, block - end - - # Forward the request to the downstream app -- middleware only. - def forward - fail "downstream app not set" unless @app.respond_to? :call - status, headers, body = @app.call env - @response.status = status - @response.body = body - @response.headers.merge! headers - nil - end - - private - - # Run filters defined on the class and all superclasses. - def filter!(type, base = settings) - filter! type, base.superclass if base.superclass.respond_to?(:filters) - base.filters[type].each { |args| process_route(*args) } - end - - # Run routes defined on the class and all superclasses. - def route!(base = settings, pass_block = nil) - if routes = base.routes[@request.request_method] - routes.each do |pattern, keys, conditions, block| - returned_pass_block = process_route(pattern, keys, conditions) do |*args| - env['sinatra.route'] = block.instance_variable_get(:@route_name) - route_eval { block[*args] } - end - - # don't wipe out pass_block in superclass - pass_block = returned_pass_block if returned_pass_block - end - end - - # Run routes defined in superclass. - if base.superclass.respond_to?(:routes) - return route!(base.superclass, pass_block) - end - - route_eval(&pass_block) if pass_block - route_missing - end - - # Run a route block and throw :halt with the result. - def route_eval - throw :halt, yield - end - - # If the current request matches pattern and conditions, fill params - # with keys and call the given block. - # Revert params afterwards. - # - # Returns pass block. - def process_route(pattern, keys, conditions, block = nil, values = []) - route = @request.path_info - route = '/' if route.empty? and not settings.empty_path_info? - return unless match = pattern.match(route) - values += match.captures.map! { |v| force_encoding URI_INSTANCE.unescape(v) if v } - - if values.any? - original, @params = params, params.merge('splat' => [], 'captures' => values) - keys.zip(values) { |k,v| Array === @params[k] ? @params[k] << v : @params[k] = v if v } - end - - catch(:pass) do - conditions.each { |c| throw :pass if c.bind(self).call == false } - block ? block[self, values] : yield(self, values) - end - ensure - @params = original if original - end - - # No matching route was found or all routes passed. The default - # implementation is to forward the request downstream when running - # as middleware (@app is non-nil); when no downstream app is set, raise - # a NotFound exception. Subclasses can override this method to perform - # custom route miss logic. - def route_missing - if @app - forward - else - raise NotFound - end - end - - # Attempt to serve static files from public directory. Throws :halt when - # a matching file is found, returns nil otherwise. - def static!(options = {}) - return if (public_dir = settings.public_folder).nil? - path = File.expand_path("#{public_dir}#{unescape(request.path_info)}" ) - return unless File.file?(path) - - env['sinatra.static_file'] = path - cache_control(*settings.static_cache_control) if settings.static_cache_control? - send_file path, options.merge(:disposition => nil) - end - - # Enable string or symbol key access to the nested params hash. - def indifferent_params(object) - case object - when Hash - new_hash = indifferent_hash - object.each { |key, value| new_hash[key] = indifferent_params(value) } - new_hash - when Array - object.map { |item| indifferent_params(item) } - else - object - end - end - - # Creates a Hash with indifferent access. - def indifferent_hash - Hash.new {|hash,key| hash[key.to_s] if Symbol === key } - end - - # Run the block with 'throw :halt' support and apply result to the response. - def invoke - res = catch(:halt) { yield } - res = [res] if Fixnum === res or String === res - if Array === res and Fixnum === res.first - res = res.dup - status(res.shift) - body(res.pop) - headers(*res) - elsif res.respond_to? :each - body res - end - nil # avoid double setting the same response tuple twice - end - - # Dispatch a request with error handling. - def dispatch! - invoke do - static! if settings.static? && (request.get? || request.head?) - filter! :before - route! - end - rescue ::Exception => boom - invoke { handle_exception!(boom) } - ensure - begin - filter! :after unless env['sinatra.static_file'] - rescue ::Exception => boom - invoke { handle_exception!(boom) } unless @env['sinatra.error'] - end - end - - # Error handling during requests. - def handle_exception!(boom) - @env['sinatra.error'] = boom - - if boom.respond_to? :http_status - status(boom.http_status) - elsif settings.use_code? and boom.respond_to? :code and boom.code.between? 400, 599 - status(boom.code) - else - status(500) - end - - status(500) unless status.between? 400, 599 - - if server_error? - dump_errors! boom if settings.dump_errors? - raise boom if settings.show_exceptions? and settings.show_exceptions != :after_handler - end - - if not_found? - headers['X-Cascade'] = 'pass' if settings.x_cascade? - body '

Not Found

' - end - - res = error_block!(boom.class, boom) || error_block!(status, boom) - return res if res or not server_error? - raise boom if settings.raise_errors? or settings.show_exceptions? - error_block! Exception, boom - end - - # Find an custom error block for the key(s) specified. - def error_block!(key, *block_params) - base = settings - while base.respond_to?(:errors) - next base = base.superclass unless args_array = base.errors[key] - args_array.reverse_each do |args| - first = args == args_array.first - args += [block_params] - resp = process_route(*args) - return resp unless resp.nil? && !first - end - end - return false unless key.respond_to? :superclass and key.superclass < Exception - error_block!(key.superclass, *block_params) - end - - def dump_errors!(boom) - msg = ["#{boom.class} - #{boom.message}:", *boom.backtrace].join("\n\t") - @env['rack.errors'].puts(msg) - end - - class << self - CALLERS_TO_IGNORE = [ # :nodoc: - /\/sinatra(\/(base|main|show_exceptions))?\.rb$/, # all sinatra code - /lib\/tilt.*\.rb$/, # all tilt code - /^\(.*\)$/, # generated code - /rubygems\/(custom|core_ext\/kernel)_require\.rb$/, # rubygems require hacks - /active_support/, # active_support require hacks - /bundler(\/runtime)?\.rb/, # bundler require hacks - /= 1.9.2 - /src\/kernel\/bootstrap\/[A-Z]/ # maglev kernel files - ] - - # contrary to what the comment said previously, rubinius never supported this - if defined?(RUBY_IGNORE_CALLERS) - warn "RUBY_IGNORE_CALLERS is deprecated and will no longer be supported by Sinatra 2.0" - CALLERS_TO_IGNORE.concat(RUBY_IGNORE_CALLERS) - end - - attr_reader :routes, :filters, :templates, :errors - - # Removes all routes, filters, middleware and extension hooks from the - # current class (not routes/filters/... defined by its superclass). - def reset! - @conditions = [] - @routes = {} - @filters = {:before => [], :after => []} - @errors = {} - @middleware = [] - @prototype = nil - @extensions = [] - - if superclass.respond_to?(:templates) - @templates = Hash.new { |hash,key| superclass.templates[key] } - else - @templates = {} - end - end - - # Extension modules registered on this class and all superclasses. - def extensions - if superclass.respond_to?(:extensions) - (@extensions + superclass.extensions).uniq - else - @extensions - end - end - - # Middleware used in this class and all superclasses. - def middleware - if superclass.respond_to?(:middleware) - superclass.middleware + @middleware - else - @middleware - end - end - - # Sets an option to the given value. If the value is a proc, - # the proc will be called every time the option is accessed. - def set(option, value = (not_set = true), ignore_setter = false, &block) - raise ArgumentError if block and !not_set - value, not_set = block, false if block - - if not_set - raise ArgumentError unless option.respond_to?(:each) - option.each { |k,v| set(k, v) } - return self - end - - if respond_to?("#{option}=") and not ignore_setter - return __send__("#{option}=", value) - end - - setter = proc { |val| set option, val, true } - getter = proc { value } - - case value - when Proc - getter = value - when Symbol, Fixnum, FalseClass, TrueClass, NilClass - getter = value.inspect - when Hash - setter = proc do |val| - val = value.merge val if Hash === val - set option, val, true - end - end - - define_singleton("#{option}=", setter) if setter - define_singleton(option, getter) if getter - define_singleton("#{option}?", "!!#{option}") unless method_defined? "#{option}?" - self - end - - # Same as calling `set :option, true` for each of the given options. - def enable(*opts) - opts.each { |key| set(key, true) } - end - - # Same as calling `set :option, false` for each of the given options. - def disable(*opts) - opts.each { |key| set(key, false) } - end - - # Define a custom error handler. Optionally takes either an Exception - # class, or an HTTP status code to specify which errors should be - # handled. - def error(*codes, &block) - args = compile! "ERROR", //, block - codes = codes.map { |c| Array(c) }.flatten - codes << Exception if codes.empty? - codes.each { |c| (@errors[c] ||= []) << args } - end - - # Sugar for `error(404) { ... }` - def not_found(&block) - error(404, &block) - error(Sinatra::NotFound, &block) - end - - # Define a named template. The block must return the template source. - def template(name, &block) - filename, line = caller_locations.first - templates[name] = [block, filename, line.to_i] - end - - # Define the layout template. The block must return the template source. - def layout(name = :layout, &block) - template name, &block - end - - # Load embedded templates from the file; uses the caller's __FILE__ - # when no file is specified. - def inline_templates=(file = nil) - file = (file.nil? || file == true) ? (caller_files.first || File.expand_path($0)) : file - - begin - io = ::IO.respond_to?(:binread) ? ::IO.binread(file) : ::IO.read(file) - app, data = io.gsub("\r\n", "\n").split(/^__END__$/, 2) - rescue Errno::ENOENT - app, data = nil - end - - if data - if app and app =~ /([^\n]*\n)?#[^\n]*coding: *(\S+)/m - encoding = $2 - else - encoding = settings.default_encoding - end - lines = app.count("\n") + 1 - template = nil - force_encoding data, encoding - data.each_line do |line| - lines += 1 - if line =~ /^@@\s*(.*\S)\s*$/ - template = force_encoding('', encoding) - templates[$1.to_sym] = [template, file, lines] - elsif template - template << line - end - end - end - end - - # Lookup or register a mime type in Rack's mime registry. - def mime_type(type, value = nil) - return type if type.nil? - return type.to_s if type.to_s.include?('/') - type = ".#{type}" unless type.to_s[0] == ?. - return Rack::Mime.mime_type(type, nil) unless value - Rack::Mime::MIME_TYPES[type] = value - end - - # provides all mime types matching type, including deprecated types: - # mime_types :html # => ['text/html'] - # mime_types :js # => ['application/javascript', 'text/javascript'] - def mime_types(type) - type = mime_type type - type =~ /^application\/(xml|javascript)$/ ? [type, "text/#$1"] : [type] - end - - # Define a before filter; runs before all requests within the same - # context as route handlers and may access/modify the request and - # response. - def before(path = nil, options = {}, &block) - add_filter(:before, path, options, &block) - end - - # Define an after filter; runs after all requests within the same - # context as route handlers and may access/modify the request and - # response. - def after(path = nil, options = {}, &block) - add_filter(:after, path, options, &block) - end - - # add a filter - def add_filter(type, path = nil, options = {}, &block) - path, options = //, path if path.respond_to?(:each_pair) - filters[type] << compile!(type, path || //, block, options) - end - - # Add a route condition. The route is considered non-matching when the - # block returns false. - def condition(name = "#{caller.first[/`.*'/]} condition", &block) - @conditions << generate_method(name, &block) - end - - def public=(value) - warn ":public is no longer used to avoid overloading Module#public, use :public_folder or :public_dir instead" - set(:public_folder, value) - end - - def public_dir=(value) - self.public_folder = value - end - - def public_dir - public_folder - end - - # Defining a `GET` handler also automatically defines - # a `HEAD` handler. - def get(path, opts = {}, &block) - conditions = @conditions.dup - route('GET', path, opts, &block) - - @conditions = conditions - route('HEAD', path, opts, &block) - end - - def put(path, opts = {}, &bk) route 'PUT', path, opts, &bk end - def post(path, opts = {}, &bk) route 'POST', path, opts, &bk end - def delete(path, opts = {}, &bk) route 'DELETE', path, opts, &bk end - def head(path, opts = {}, &bk) route 'HEAD', path, opts, &bk end - def options(path, opts = {}, &bk) route 'OPTIONS', path, opts, &bk end - def patch(path, opts = {}, &bk) route 'PATCH', path, opts, &bk end - def link(path, opts = {}, &bk) route 'LINK', path, opts, &bk end - def unlink(path, opts = {}, &bk) route 'UNLINK', path, opts, &bk end - - # Makes the methods defined in the block and in the Modules given - # in `extensions` available to the handlers and templates - def helpers(*extensions, &block) - class_eval(&block) if block_given? - include(*extensions) if extensions.any? - end - - # Register an extension. Alternatively take a block from which an - # extension will be created and registered on the fly. - def register(*extensions, &block) - extensions << Module.new(&block) if block_given? - @extensions += extensions - extensions.each do |extension| - extend extension - extension.registered(self) if extension.respond_to?(:registered) - end - end - - def development?; environment == :development end - def production?; environment == :production end - def test?; environment == :test end - - # Set configuration options for Sinatra and/or the app. - # Allows scoping of settings for certain environments. - def configure(*envs) - yield self if envs.empty? || envs.include?(environment.to_sym) - end - - # Use the specified Rack middleware - def use(middleware, *args, &block) - @prototype = nil - @middleware << [middleware, args, block] - end - - # Stop the self-hosted server if running. - def quit! - return unless running? - # Use Thin's hard #stop! if available, otherwise just #stop. - running_server.respond_to?(:stop!) ? running_server.stop! : running_server.stop - $stderr.puts "== Sinatra has ended his set (crowd applauds)" unless handler_name =~/cgi/i - set :running_server, nil - set :handler_name, nil - end - - alias_method :stop!, :quit! - - # Run the Sinatra app as a self-hosted server using - # Thin, Puma, Mongrel, or WEBrick (in that order). If given a block, will call - # with the constructed handler once we have taken the stage. - def run!(options = {}, &block) - return if running? - set options - handler = detect_rack_handler - handler_name = handler.name.gsub(/.*::/, '') - server_settings = settings.respond_to?(:server_settings) ? settings.server_settings : {} - server_settings.merge!(:Port => port, :Host => bind) - - begin - start_server(handler, server_settings, handler_name, &block) - rescue Errno::EADDRINUSE - $stderr.puts "== Someone is already performing on port #{port}!" - raise - ensure - quit! - end - end - - alias_method :start!, :run! - - # Check whether the self-hosted server is running or not. - def running? - running_server? - end - - # The prototype instance used to process requests. - def prototype - @prototype ||= new - end - - # Create a new instance without middleware in front of it. - alias new! new unless method_defined? :new! - - # Create a new instance of the class fronted by its middleware - # pipeline. The object is guaranteed to respond to #call but may not be - # an instance of the class new was called on. - def new(*args, &bk) - instance = new!(*args, &bk) - Wrapper.new(build(instance).to_app, instance) - end - - # Creates a Rack::Builder instance with all the middleware set up and - # the given +app+ as end point. - def build(app) - builder = Rack::Builder.new - setup_default_middleware builder - setup_middleware builder - builder.run app - builder - end - - def call(env) - synchronize { prototype.call(env) } - end - - # Like Kernel#caller but excluding certain magic entries and without - # line / method information; the resulting array contains filenames only. - def caller_files - cleaned_caller(1).flatten - end - - # Like caller_files, but containing Arrays rather than strings with the - # first element being the file, and the second being the line. - def caller_locations - cleaned_caller 2 - end - - private - - # Starts the server by running the Rack Handler. - def start_server(handler, server_settings, handler_name) - handler.run(self, server_settings) do |server| - unless handler_name =~ /cgi/i - $stderr.puts "== Sinatra/#{Sinatra::VERSION} has taken the stage " + - "on #{port} for #{environment} with backup from #{handler_name}" - end - - setup_traps - set :running_server, server - set :handler_name, handler_name - server.threaded = settings.threaded if server.respond_to? :threaded= - - yield server if block_given? - end - end - - def setup_traps - if traps? - at_exit { quit! } - - [:INT, :TERM].each do |signal| - old_handler = trap(signal) do - quit! - old_handler.call if old_handler.respond_to?(:call) - end - end - - set :traps, false - end - end - - # Dynamically defines a method on settings. - def define_singleton(name, content = Proc.new) - # replace with call to singleton_class once we're 1.9 only - (class << self; self; end).class_eval do - undef_method(name) if method_defined? name - String === content ? class_eval("def #{name}() #{content}; end") : define_method(name, &content) - end - end - - # Condition for matching host name. Parameter might be String or Regexp. - def host_name(pattern) - condition { pattern === request.host } - end - - # Condition for matching user agent. Parameter should be Regexp. - # Will set params[:agent]. - def user_agent(pattern) - condition do - if request.user_agent.to_s =~ pattern - @params[:agent] = $~[1..-1] - true - else - false - end - end - end - alias_method :agent, :user_agent - - # Condition for matching mimetypes. Accepts file extensions. - def provides(*types) - types.map! { |t| mime_types(t) } - types.flatten! - condition do - if type = response['Content-Type'] - types.include? type or types.include? type[/^[^;]+/] - elsif type = request.preferred_type(types) - params = (type.respond_to?(:params) ? type.params : {}) - content_type(type, params) - true - else - false - end - end - end - - def route(verb, path, options = {}, &block) - # Because of self.options.host - host_name(options.delete(:host)) if options.key?(:host) - enable :empty_path_info if path == "" and empty_path_info.nil? - signature = compile!(verb, path, block, options) - (@routes[verb] ||= []) << signature - invoke_hook(:route_added, verb, path, block) - signature - end - - def invoke_hook(name, *args) - extensions.each { |e| e.send(name, *args) if e.respond_to?(name) } - end - - def generate_method(method_name, &block) - method_name = method_name.to_sym - define_method(method_name, &block) - method = instance_method method_name - remove_method method_name - method - end - - def compile!(verb, path, block, options = {}) - options.each_pair { |option, args| send(option, *args) } - method_name = "#{verb} #{path}" - unbound_method = generate_method(method_name, &block) - pattern, keys = compile path - conditions, @conditions = @conditions, [] - - wrapper = block.arity != 0 ? - proc { |a,p| unbound_method.bind(a).call(*p) } : - proc { |a,p| unbound_method.bind(a).call } - wrapper.instance_variable_set(:@route_name, method_name) - - [ pattern, keys, conditions, wrapper ] - end - - def compile(path) - if path.respond_to? :to_str - keys = [] - - # We append a / at the end if there was one. - # Reason: Splitting does not split off an empty - # string at the end if the split separator - # is at the end. - # - postfix = '/' if path =~ /\/\z/ - - # Split the path into pieces in between forward slashes. - # - segments = path.split('/').map! do |segment| - ignore = [] - - # Special character handling. - # - pattern = segment.to_str.gsub(/[^\?\%\\\/\:\*\w]/) do |c| - ignore << escaped(c).join if c.match(/[\.@]/) - patt = encoded(c) - patt.gsub(/%[\da-fA-F]{2}/) do |match| - match.split(//).map! {|char| char =~ /[A-Z]/ ? "[#{char}#{char.tr('A-Z', 'a-z')}]" : char}.join - end - end - - ignore = ignore.uniq.join - - # Key handling. - # - pattern.gsub(/((:\w+)|\*)/) do |match| - if match == "*" - keys << 'splat' - "(.*?)" - else - keys << $2[1..-1] - ignore_pattern = safe_ignore(ignore) - - ignore_pattern - end - end - end - - # Special case handling. - # - if segment = segments.pop - if segment.match(/\[\^\\\./) - parts = segment.rpartition(/\[\^\\\./) - parts[1] = '[^' - segments << parts.join - else - segments << segment - end - end - [/\A#{segments.join('/')}#{postfix}\z/, keys] - elsif path.respond_to?(:keys) && path.respond_to?(:match) - [path, path.keys] - elsif path.respond_to?(:names) && path.respond_to?(:match) - [path, path.names] - elsif path.respond_to? :match - [path, []] - else - raise TypeError, path - end - end - - def encoded(char) - enc = URI_INSTANCE.escape(char) - enc = "(?:#{escaped(char, enc).join('|')})" if enc == char - enc = "(?:#{enc}|#{encoded('+')})" if char == " " - enc - end - - def escaped(char, enc = URI_INSTANCE.escape(char)) - [Regexp.escape(enc), URI_INSTANCE.escape(char, /./)] - end - - def safe_ignore(ignore) - unsafe_ignore = [] - ignore = ignore.gsub(/%[\da-fA-F]{2}/) do |hex| - unsafe_ignore << hex[1..2] - '' - end - unsafe_patterns = unsafe_ignore.map! do |unsafe| - chars = unsafe.split(//).map! do |char| - if char =~ /[A-Z]/ - char <<= char.tr('A-Z', 'a-z') - end - char - end - - "|(?:%[^#{chars[0]}].|%[#{chars[0]}][^#{chars[1]}])" - end - if unsafe_patterns.length > 0 - "((?:[^#{ignore}/?#%]#{unsafe_patterns.join()})+)" - else - "([^#{ignore}/?#]+)" - end - end - - def setup_default_middleware(builder) - builder.use ExtendedRack - builder.use ShowExceptions if show_exceptions? - builder.use Rack::MethodOverride if method_override? - builder.use Rack::Head - setup_logging builder - setup_sessions builder - setup_protection builder - end - - def setup_middleware(builder) - middleware.each { |c,a,b| builder.use(c, *a, &b) } - end - - def setup_logging(builder) - if logging? - setup_common_logger(builder) - setup_custom_logger(builder) - elsif logging == false - setup_null_logger(builder) - end - end - - def setup_null_logger(builder) - builder.use Rack::NullLogger - end - - def setup_common_logger(builder) - builder.use Sinatra::CommonLogger - end - - def setup_custom_logger(builder) - if logging.respond_to? :to_int - builder.use Rack::Logger, logging - else - builder.use Rack::Logger - end - end - - def setup_protection(builder) - return unless protection? - options = Hash === protection ? protection.dup : {} - protect_session = options.fetch(:session) { sessions? } - options[:except] = Array options[:except] - options[:except] += [:session_hijacking, :remote_token] unless protect_session - options[:reaction] ||= :drop_session - builder.use Rack::Protection, options - end - - def setup_sessions(builder) - return unless sessions? - options = {} - options[:secret] = session_secret if session_secret? - options.merge! sessions.to_hash if sessions.respond_to? :to_hash - builder.use Rack::Session::Cookie, options - end - - def detect_rack_handler - servers = Array(server) - servers.each do |server_name| - begin - return Rack::Handler.get(server_name.to_s) - rescue LoadError, NameError - end - end - fail "Server handler (#{servers.join(',')}) not found." - end - - def inherited(subclass) - subclass.reset! - subclass.set :app_file, caller_files.first unless subclass.app_file? - super - end - - @@mutex = Mutex.new - def synchronize(&block) - if lock? - @@mutex.synchronize(&block) - else - yield - end - end - - # used for deprecation warnings - def warn(message) - super message + "\n\tfrom #{cleaned_caller.first.join(':')}" - end - - # Like Kernel#caller but excluding certain magic entries - def cleaned_caller(keep = 3) - caller(1). - map! { |line| line.split(/:(?=\d|in )/, 3)[0,keep] }. - reject { |file, *_| CALLERS_TO_IGNORE.any? { |pattern| file =~ pattern } } - end - end - - # Fixes encoding issues by - # * defaulting to UTF-8 - # * casting params to Encoding.default_external - # - # The latter might not be necessary if Rack handles it one day. - # Keep an eye on Rack's LH #100. - def force_encoding(*args) settings.force_encoding(*args) end - if defined? Encoding - def self.force_encoding(data, encoding = default_encoding) - return if data == settings || data.is_a?(Tempfile) - if data.respond_to? :force_encoding - data.force_encoding(encoding).encode! - elsif data.respond_to? :each_value - data.each_value { |v| force_encoding(v, encoding) } - elsif data.respond_to? :each - data.each { |v| force_encoding(v, encoding) } - end - data - end - else - def self.force_encoding(data, *) data end - end - - reset! - - set :environment, (ENV['RACK_ENV'] || :development).to_sym - set :raise_errors, Proc.new { test? } - set :dump_errors, Proc.new { !test? } - set :show_exceptions, Proc.new { development? } - set :sessions, false - set :logging, false - set :protection, true - set :method_override, false - set :use_code, false - set :default_encoding, "utf-8" - set :x_cascade, true - set :add_charset, %w[javascript xml xhtml+xml].map { |t| "application/#{t}" } - settings.add_charset << /^text\// - - # explicitly generating a session secret eagerly to play nice with preforking - begin - require 'securerandom' - set :session_secret, SecureRandom.hex(64) - rescue LoadError, NotImplementedError - # SecureRandom raises a NotImplementedError if no random device is available - set :session_secret, "%064x" % Kernel.rand(2**256-1) - end - - class << self - alias_method :methodoverride?, :method_override? - alias_method :methodoverride=, :method_override= - end - - set :run, false # start server via at-exit hook? - set :running_server, nil - set :handler_name, nil - set :traps, true - set :server, %w[HTTP webrick] - set :bind, Proc.new { development? ? 'localhost' : '0.0.0.0' } - set :port, Integer(ENV['PORT'] && !ENV['PORT'].empty? ? ENV['PORT'] : 4567) - - ruby_engine = defined?(RUBY_ENGINE) && RUBY_ENGINE - - if ruby_engine == 'macruby' - server.unshift 'control_tower' - else - server.unshift 'reel' - server.unshift 'mongrel' if ruby_engine.nil? - server.unshift 'puma' if ruby_engine != 'rbx' - server.unshift 'thin' if ruby_engine != 'jruby' - server.unshift 'puma' if ruby_engine == 'rbx' - server.unshift 'trinidad' if ruby_engine == 'jruby' - end - - set :absolute_redirects, true - set :prefixed_redirects, false - set :empty_path_info, nil - - set :app_file, nil - set :root, Proc.new { app_file && File.expand_path(File.dirname(app_file)) } - set :views, Proc.new { root && File.join(root, 'views') } - set :reload_templates, Proc.new { development? } - set :lock, false - set :threaded, true - - set :public_folder, Proc.new { root && File.join(root, 'public') } - set :static, Proc.new { public_folder && File.exist?(public_folder) } - set :static_cache_control, false - - error ::Exception do - response.status = 500 - content_type 'text/html' - '

Internal Server Error

' - end - - configure :development do - get '/__sinatra__/:image.png' do - filename = File.dirname(__FILE__) + "/images/#{params[:image]}.png" - content_type :png - send_file filename - end - - error NotFound do - content_type 'text/html' - - if self.class == Sinatra::Application - code = <<-RUBY.gsub(/^ {12}/, '') - #{request.request_method.downcase} '#{request.path_info}' do - "Hello World" - end - RUBY - else - code = <<-RUBY.gsub(/^ {12}/, '') - class #{self.class} - #{request.request_method.downcase} '#{request.path_info}' do - "Hello World" - end - end - RUBY - - file = settings.app_file.to_s.sub(settings.root.to_s, '').sub(/^\//, '') - code = "# in #{file}\n#{code}" unless file.empty? - end - - (<<-HTML).gsub(/^ {10}/, '') - - - - - - -

Sinatra doesn’t know this ditty.

- -
- Try this: -
#{code}
-
- - - HTML - end - end - end - - # Execution context for classic style (top-level) applications. All - # DSL methods executed on main are delegated to this class. - # - # The Application class should not be subclassed, unless you want to - # inherit all settings, routes, handlers, and error pages from the - # top-level. Subclassing Sinatra::Base is highly recommended for - # modular applications. - class Application < Base - set :logging, Proc.new { ! test? } - set :method_override, true - set :run, Proc.new { ! test? } - set :session_secret, Proc.new { super() unless development? } - set :app_file, nil - - def self.register(*extensions, &block) #:nodoc: - added_methods = extensions.map {|m| m.public_instance_methods }.flatten - Delegator.delegate(*added_methods) - super(*extensions, &block) - end - end - - # Sinatra delegation mixin. Mixing this module into an object causes all - # methods to be delegated to the Sinatra::Application class. Used primarily - # at the top-level. - module Delegator #:nodoc: - def self.delegate(*methods) - methods.each do |method_name| - define_method(method_name) do |*args, &block| - return super(*args, &block) if respond_to? method_name - Delegator.target.send(method_name, *args, &block) - end - private method_name - end - end - - delegate :get, :patch, :put, :post, :delete, :head, :options, :link, :unlink, - :template, :layout, :before, :after, :error, :not_found, :configure, - :set, :mime_type, :enable, :disable, :use, :development?, :test?, - :production?, :helpers, :settings, :register - - class << self - attr_accessor :target - end - - self.target = Application - end - - class Wrapper - def initialize(stack, instance) - @stack, @instance = stack, instance - end - - def settings - @instance.settings - end - - def helpers - @instance - end - - def call(env) - @stack.call(env) - end - - def inspect - "#<#{@instance.class} app_file=#{settings.app_file.inspect}>" - end - end - - # Create a new Sinatra application. The block is evaluated in the new app's - # class scope. - def self.new(base = Base, &block) - base = Class.new(base) - base.class_eval(&block) if block_given? - base - end - - # Extend the top-level DSL with the modules provided. - def self.register(*extensions, &block) - Delegator.target.register(*extensions, &block) - end - - # Include the helper modules provided in Sinatra's request context. - def self.helpers(*extensions, &block) - Delegator.target.helpers(*extensions, &block) - end - - # Use the middleware for classic applications. - def self.use(*args, &block) - Delegator.target.use(*args, &block) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/images/404.png b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/images/404.png deleted file mode 100644 index f16a914..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/images/404.png and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/images/500.png b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/images/500.png deleted file mode 100644 index e08b17d..0000000 Binary files a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/images/500.png and /dev/null differ diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/main.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/main.rb deleted file mode 100644 index 76a5526..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/main.rb +++ /dev/null @@ -1,34 +0,0 @@ -require 'sinatra/base' - -module Sinatra - class Application < Base - - # we assume that the first file that requires 'sinatra' is the - # app_file. all other path related options are calculated based - # on this path by default. - set :app_file, caller_files.first || $0 - - set :run, Proc.new { File.expand_path($0) == File.expand_path(app_file) } - - if run? && ARGV.any? - require 'optparse' - OptionParser.new { |op| - op.on('-p port', 'set the port (default is 4567)') { |val| set :port, Integer(val) } - op.on('-o addr', "set the host (default is #{bind})") { |val| set :bind, val } - op.on('-e env', 'set the environment (default is development)') { |val| set :environment, val.to_sym } - op.on('-s server', 'specify rack server/handler (default is thin)') { |val| set :server, val } - op.on('-x', 'turn on the mutex lock (default is off)') { set :lock, true } - }.parse!(ARGV.dup) - end - end - - at_exit { Application.run! if $!.nil? && Application.run? } -end - -# include would include the module in Object -# extend only extends the `main` object -extend Sinatra::Delegator - -class Rack::Builder - include Sinatra::Delegator -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/show_exceptions.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/show_exceptions.rb deleted file mode 100644 index ec2fe07..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/show_exceptions.rb +++ /dev/null @@ -1,345 +0,0 @@ -require 'rack/showexceptions' - -module Sinatra - # Sinatra::ShowExceptions catches all exceptions raised from the app it - # wraps. It shows a useful backtrace with the sourcefile and clickable - # context, the whole Rack environment and the request data. - # - # Be careful when you use this on public-facing sites as it could reveal - # information helpful to attackers. - class ShowExceptions < Rack::ShowExceptions - @@eats_errors = Object.new - def @@eats_errors.flush(*) end - def @@eats_errors.puts(*) end - - def initialize(app) - @app = app - @template = ERB.new(TEMPLATE) - end - - def call(env) - @app.call(env) - rescue Exception => e - errors, env["rack.errors"] = env["rack.errors"], @@eats_errors - - if prefers_plain_text?(env) - content_type = "text/plain" - body = [dump_exception(e)] - else - content_type = "text/html" - body = pretty(env, e) - end - - env["rack.errors"] = errors - - [500, - {"Content-Type" => content_type, - "Content-Length" => Rack::Utils.bytesize(body.join).to_s}, - body] - end - - private - - def prefers_plain_text?(env) - !(Request.new(env).preferred_type("text/plain","text/html") == "text/html") && - [/curl/].index{|item| item =~ env["HTTP_USER_AGENT"]} - end - - def frame_class(frame) - if frame.filename =~ /lib\/sinatra.*\.rb/ - "framework" - elsif (defined?(Gem) && frame.filename.include?(Gem.dir)) || - frame.filename =~ /\/bin\/(\w+)$/ - "system" - else - "app" - end - end - -TEMPLATE = <<-HTML # :nodoc: - - - - - <%=h exception.class %> at <%=h path %> - - - - - - -
- - -
-

BACKTRACE

-

(expand)

- -
- -
    - - <% id = 1 %> - <% frames.each do |frame| %> - <% if frame.context_line && frame.context_line != "#" %> - -
  • - <%=h frame.filename %> in - <%=h frame.function %> -
  • - -
  • - <% if frame.pre_context %> -
      - <% frame.pre_context.each do |line| %> -
    1. <%=h line %>
    2. - <% end %> -
    - <% end %> - -
      -
    1. <%= - h frame.context_line %>
    2. -
    - - <% if frame.post_context %> -
      - <% frame.post_context.each do |line| %> -
    1. <%=h line %>
    2. - <% end %> -
    - <% end %> -
    -
  • - - <% end %> - - <% id += 1 %> - <% end %> - -
-
- -
-

GET

- <% if req.GET and not req.GET.empty? %> - - - - - - <% req.GET.sort_by { |k, v| k.to_s }.each { |key, val| %> - - - - - <% } %> -
VariableValue
<%=h key %>
<%=h val.inspect %>
- <% else %> -

No GET data.

- <% end %> -
-
- -
-

POST

- <% if req.POST and not req.POST.empty? %> - - - - - - <% req.POST.sort_by { |k, v| k.to_s }.each { |key, val| %> - - - - - <% } %> -
VariableValue
<%=h key %>
<%=h val.inspect %>
- <% else %> -

No POST data.

- <% end %> -
-
- -
- - <% unless req.cookies.empty? %> - - - - - - <% req.cookies.each { |key, val| %> - - - - - <% } %> -
VariableValue
<%=h key %>
<%=h val.inspect %>
- <% else %> -

No cookie data.

- <% end %> -
-
- -
-

Rack ENV

- - - - - - <% env.sort_by { |k, v| k.to_s }.each { |key, val| %> - - - - - <% } %> -
VariableValue
<%=h key %>
<%=h val %>
-
-
- -

You're seeing this error because you have -enabled the show_exceptions setting.

-
- - -HTML - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/version.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/version.rb deleted file mode 100644 index 5ef4b41..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/lib/sinatra/version.rb +++ /dev/null @@ -1,3 +0,0 @@ -module Sinatra - VERSION = '1.4.5' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/sinatra.gemspec b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/sinatra.gemspec deleted file mode 100644 index 16734a0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/sinatra.gemspec +++ /dev/null @@ -1,19 +0,0 @@ -$LOAD_PATH.unshift File.expand_path('../lib', __FILE__) -require 'sinatra/version' - -Gem::Specification.new 'sinatra', Sinatra::VERSION do |s| - s.description = "Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort." - s.summary = "Classy web-development dressed in a DSL" - s.authors = ["Blake Mizerany", "Ryan Tomayko", "Simon Rozet", "Konstantin Haase"] - s.email = "sinatrarb@googlegroups.com" - s.homepage = "http://www.sinatrarb.com/" - s.license = 'MIT' - s.files = `git ls-files`.split("\n") - %w[.gitignore .travis.yml] - s.test_files = s.files.select { |p| p =~ /^test\/.*_test.rb/ } - s.extra_rdoc_files = s.files.select { |p| p =~ /^README/ } << 'LICENSE' - s.rdoc_options = %w[--line-numbers --inline-source --title Sinatra --main README.rdoc --encoding=UTF-8] - - s.add_dependency 'rack', '~> 1.4' - s.add_dependency 'tilt', '~> 1.3', '>= 1.3.4' - s.add_dependency 'rack-protection', '~> 1.4' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/asciidoctor_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/asciidoctor_test.rb deleted file mode 100644 index 02e05ba..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/asciidoctor_test.rb +++ /dev/null @@ -1,72 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin - require 'asciidoctor' - - class AsciidoctorTest < Test::Unit::TestCase - def asciidoc_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline AsciiDoc strings' do - asciidoc_app { asciidoc '== Hiya' } - assert ok? - assert_match %r{Hiya}, body - end - - it 'uses the correct engine' do - engine = Tilt::AsciidoctorTemplate - assert_equal engine, Tilt[:ad] - assert_equal engine, Tilt[:adoc] - assert_equal engine, Tilt[:asciidoc] - end - - it 'renders .asciidoc files in views path' do - asciidoc_app { asciidoc :hello } - assert ok? - assert_match %r{Hello from AsciiDoc}, body - end - - it 'raises error if template not found' do - mock_app { get('/') { asciidoc :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it 'renders with inline layouts' do - mock_app do - layout { 'THIS. IS. #{yield.upcase}!' } - get('/') { asciidoc 'Sparta', :layout_engine => :str } - end - get '/' - assert ok? - assert_include body, 'THIS. IS.' - assert_include body, '

SPARTA

' - end - - it 'renders with file layouts' do - asciidoc_app do - asciidoc 'Hello World', :layout => :layout2, :layout_engine => :erb - end - assert ok? - assert_include body, 'ERB Layout!' - assert_include body, '

Hello World

' - end - - it 'can be used in a nested fashion for partials and whatnot' do - mock_app do - template(:inner) { 'hi' } - template(:outer) { '<%= asciidoc :inner %>' } - get('/') { erb :outer } - end - get '/' - assert ok? - assert_match %r{.*hi

.*
}m, body - end - end -rescue LoadError - warn "#{$!.to_s}: skipping asciidoc tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/base_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/base_test.rb deleted file mode 100644 index 8222c16..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/base_test.rb +++ /dev/null @@ -1,171 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class BaseTest < Test::Unit::TestCase - def test_default - assert true - end - - describe 'Sinatra::Base subclasses' do - class TestApp < Sinatra::Base - get('/') { 'Hello World' } - end - - it 'include Rack::Utils' do - assert TestApp.included_modules.include?(Rack::Utils) - end - - it 'processes requests with #call' do - assert TestApp.respond_to?(:call) - - request = Rack::MockRequest.new(TestApp) - response = request.get('/') - assert response.ok? - assert_equal 'Hello World', response.body - end - - class TestApp < Sinatra::Base - get '/state' do - @foo ||= "new" - body = "Foo: #{@foo}" - @foo = 'discard' - body - end - end - - it 'does not maintain state between requests' do - request = Rack::MockRequest.new(TestApp) - 2.times do - response = request.get('/state') - assert response.ok? - assert_equal 'Foo: new', response.body - end - end - - it "passes the subclass to configure blocks" do - ref = nil - TestApp.configure { |app| ref = app } - assert_equal TestApp, ref - end - - it "allows the configure block arg to be omitted and does not change context" do - context = nil - TestApp.configure { context = self } - assert_equal self, context - end - end - - describe "Sinatra::Base#new" do - it 'returns a wrapper' do - assert_equal Sinatra::Wrapper, Sinatra::Base.new.class - end - - it 'implements a nice inspect' do - assert_equal '#', Sinatra::Base.new.inspect - end - - it 'exposes settings' do - assert_equal Sinatra::Base.settings, Sinatra::Base.new.settings - end - - it 'exposes helpers' do - assert_equal 'image/jpeg', Sinatra::Base.new.helpers.mime_type(:jpg) - end - end - - describe "Sinatra::Base as Rack middleware" do - app = lambda { |env| - headers = {'X-Downstream' => 'true'} - headers['X-Route-Missing'] = env['sinatra.route-missing'] || '' - [210, headers, ['Hello from downstream']] } - - class TestMiddleware < Sinatra::Base - end - - it 'creates a middleware that responds to #call with .new' do - middleware = TestMiddleware.new(app) - assert middleware.respond_to?(:call) - end - - it 'exposes the downstream app' do - middleware = TestMiddleware.new!(app) - assert_same app, middleware.app - end - - class TestMiddleware < Sinatra::Base - def route_missing - env['sinatra.route-missing'] = '1' - super - end - - get('/') { 'Hello from middleware' } - end - - middleware = TestMiddleware.new(app) - request = Rack::MockRequest.new(middleware) - - it 'intercepts requests' do - response = request.get('/') - assert response.ok? - assert_equal 'Hello from middleware', response.body - end - - it 'automatically forwards requests downstream when no matching route found' do - response = request.get('/missing') - assert_equal 210, response.status - assert_equal 'Hello from downstream', response.body - end - - it 'calls #route_missing before forwarding downstream' do - response = request.get('/missing') - assert_equal '1', response['X-Route-Missing'] - end - - class TestMiddleware < Sinatra::Base - get('/low-level-forward') { app.call(env) } - end - - it 'can call the downstream app directly and return result' do - response = request.get('/low-level-forward') - assert_equal 210, response.status - assert_equal 'true', response['X-Downstream'] - assert_equal 'Hello from downstream', response.body - end - - class TestMiddleware < Sinatra::Base - get '/explicit-forward' do - response['X-Middleware'] = 'true' - res = forward - assert_nil res - assert_equal 210, response.status - assert_equal 'true', response['X-Downstream'] - assert_equal ['Hello from downstream'], response.body - 'Hello after explicit forward' - end - end - - it 'forwards the request downstream and integrates the response into the current context' do - response = request.get('/explicit-forward') - assert_equal 210, response.status - assert_equal 'true', response['X-Downstream'] - assert_equal 'Hello after explicit forward', response.body - assert_equal '28', response['Content-Length'] - end - - app_content_length = lambda {|env| - [200, {'Content-Length' => '16'}, 'From downstream!']} - - class TestMiddlewareContentLength < Sinatra::Base - get '/forward' do - 'From after explicit forward!' - end - end - - middleware_content_length = TestMiddlewareContentLength.new(app_content_length) - request_content_length = Rack::MockRequest.new(middleware_content_length) - - it "sets content length for last response" do - response = request_content_length.get('/forward') - assert_equal '28', response['Content-Length'] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/builder_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/builder_test.rb deleted file mode 100644 index 65744d1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/builder_test.rb +++ /dev/null @@ -1,91 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'builder' - -class BuilderTest < Test::Unit::TestCase - def builder_app(options = {}, &block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - set options - get('/', &block) - end - get '/' - end - - it 'renders inline Builder strings' do - builder_app { builder 'xml.instruct!' } - assert ok? - assert_equal %{\n}, body - end - - it 'defaults content type to xml' do - builder_app { builder 'xml.instruct!' } - assert ok? - assert_equal "application/xml;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type per route' do - builder_app do - content_type :html - builder 'xml.instruct!' - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type globally' do - builder_app(:builder => { :content_type => 'html' }) do - builder 'xml.instruct!' - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'renders inline blocks' do - builder_app do - @name = "Frank & Mary" - builder { |xml| xml.couple @name } - end - assert ok? - assert_equal "Frank & Mary\n", body - end - - it 'renders .builder files in views path' do - builder_app do - @name = "Blue" - builder :hello - end - assert ok? - assert_equal %(You're my boy, Blue!\n), body - end - - it "renders with inline layouts" do - mock_app do - layout { %(xml.layout { xml << yield }) } - get('/') { builder %(xml.em 'Hello World') } - end - get '/' - assert ok? - assert_equal "\nHello World\n\n", body - end - - it "renders with file layouts" do - builder_app do - builder %(xml.em 'Hello World'), :layout => :layout2 - end - assert ok? - assert_equal "\nHello World\n\n", body - end - - it "raises error if template not found" do - mock_app do - get('/') { builder :no_such_template } - end - assert_raise(Errno::ENOENT) { get('/') } - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping builder tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/coffee_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/coffee_test.rb deleted file mode 100644 index 98dea32..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/coffee_test.rb +++ /dev/null @@ -1,90 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'coffee-script' -require 'execjs' - -begin - ExecJS.compile '1' -rescue Exception - raise LoadError, 'unable to execute JavaScript' -end - -class CoffeeTest < Test::Unit::TestCase - def coffee_app(options = {}, &block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - set(options) - get('/', &block) - end - get '/' - end - - it 'renders inline Coffee strings' do - coffee_app { coffee "alert 'Aye!'\n" } - assert ok? - assert body.include?("alert('Aye!');") - end - - it 'defaults content type to javascript' do - coffee_app { coffee "alert 'Aye!'\n" } - assert ok? - assert_equal "application/javascript;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type per route' do - coffee_app do - content_type :html - coffee "alert 'Aye!'\n" - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type globally' do - coffee_app(:coffee => { :content_type => 'html' }) do - coffee "alert 'Aye!'\n" - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'renders .coffee files in views path' do - coffee_app { coffee :hello } - assert ok? - assert_include body, "alert(\"Aye!\");" - end - - it 'ignores the layout option' do - coffee_app { coffee :hello, :layout => :layout2 } - assert ok? - assert_include body, "alert(\"Aye!\");" - end - - it "raises error if template not found" do - mock_app { - get('/') { coffee :no_such_template } - } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "passes coffee options to the coffee engine" do - coffee_app { coffee "alert 'Aye!'\n", :no_wrap => true } - assert ok? - assert_body "alert('Aye!');" - end - - it "passes default coffee options to the coffee engine" do - mock_app do - set :coffee, :no_wrap => true # default coffee style is :nested - get('/') { coffee "alert 'Aye!'\n" } - end - get '/' - assert ok? - assert_body "alert('Aye!');" - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping coffee tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/compile_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/compile_test.rb deleted file mode 100644 index ece53c6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/compile_test.rb +++ /dev/null @@ -1,183 +0,0 @@ -# I like coding: UTF-8 -require File.expand_path('../helper', __FILE__) - -class CompileTest < Test::Unit::TestCase - - def self.converts pattern, expected_regexp - it "generates #{expected_regexp.source} from #{pattern}" do - compiled, _ = compiled pattern - assert_equal expected_regexp, compiled, "Pattern #{pattern} is not compiled into #{expected_regexp.source}. Was #{compiled.source}." - end - end - def self.parses pattern, example, expected_params - it "parses #{example} with #{pattern} into params #{expected_params}" do - compiled, keys = compiled pattern - match = compiled.match(example) - fail %Q{"#{example}" does not parse on pattern "#{pattern}" (compiled pattern is #{compiled.source}).} unless match - - # Aggregate e.g. multiple splat values into one array. - # - params = keys.zip(match.captures).reduce({}) do |hash, mapping| - key, value = mapping - hash[key] = if existing = hash[key] - existing.respond_to?(:to_ary) ? existing << value : [existing, value] - else - value - end - hash - end - - assert_equal expected_params, params, "Pattern #{pattern} does not match path #{example}." - end - end - def self.fails pattern, example - it "does not parse #{example} with #{pattern}" do - compiled, _ = compiled pattern - match = compiled.match(example) - fail %Q{"#{pattern}" does parse "#{example}" but it should fail} if match - end - end - def compiled pattern - app ||= mock_app {} - compiled, keys = app.send(:compile, pattern) - [compiled, keys] - end - - converts "/", %r{\A/\z} - parses "/", "/", {} - - converts "/foo", %r{\A/foo\z} - parses "/foo", "/foo", {} - - converts "/:foo", %r{\A/([^/?#]+)\z} - parses "/:foo", "/foo", "foo" => "foo" - parses "/:foo", "/foo.bar", "foo" => "foo.bar" - parses "/:foo", "/foo%2Fbar", "foo" => "foo%2Fbar" - parses "/:foo", "/%0Afoo", "foo" => "%0Afoo" - fails "/:foo", "/foo?" - fails "/:foo", "/foo/bar" - fails "/:foo", "/" - fails "/:foo", "/foo/" - - converts "/föö", %r{\A/f%[Cc]3%[Bb]6%[Cc]3%[Bb]6\z} - parses "/föö", "/f%C3%B6%C3%B6", {} - - converts "/:foo/:bar", %r{\A/([^/?#]+)/([^/?#]+)\z} - parses "/:foo/:bar", "/foo/bar", "foo" => "foo", "bar" => "bar" - - converts "/hello/:person", %r{\A/hello/([^/?#]+)\z} - parses "/hello/:person", "/hello/Frank", "person" => "Frank" - - converts "/?:foo?/?:bar?", %r{\A/?([^/?#]+)?/?([^/?#]+)?\z} - parses "/?:foo?/?:bar?", "/hello/world", "foo" => "hello", "bar" => "world" - parses "/?:foo?/?:bar?", "/hello", "foo" => "hello", "bar" => nil - parses "/?:foo?/?:bar?", "/", "foo" => nil, "bar" => nil - parses "/?:foo?/?:bar?", "", "foo" => nil, "bar" => nil - - converts "/*", %r{\A/(.*?)\z} - parses "/*", "/", "splat" => "" - parses "/*", "/foo", "splat" => "foo" - parses "/*", "/foo/bar", "splat" => "foo/bar" - - converts "/:foo/*", %r{\A/([^/?#]+)/(.*?)\z} - parses "/:foo/*", "/foo/bar/baz", "foo" => "foo", "splat" => "bar/baz" - - converts "/:foo/:bar", %r{\A/([^/?#]+)/([^/?#]+)\z} - parses "/:foo/:bar", "/user@example.com/name", "foo" => "user@example.com", "bar" => "name" - - converts "/test$/", %r{\A/test(?:\$|%24)/\z} - parses "/test$/", "/test$/", {} - - converts "/te+st/", %r{\A/te(?:\+|%2[Bb])st/\z} - parses "/te+st/", "/te+st/", {} - fails "/te+st/", "/test/" - fails "/te+st/", "/teeest/" - - converts "/test(bar)/", %r{\A/test(?:\(|%28)bar(?:\)|%29)/\z} - parses "/test(bar)/", "/test(bar)/", {} - - converts "/path with spaces", %r{\A/path(?:%20|(?:\+|%2[Bb]))with(?:%20|(?:\+|%2[Bb]))spaces\z} - parses "/path with spaces", "/path%20with%20spaces", {} - parses "/path with spaces", "/path%2Bwith%2Bspaces", {} - parses "/path with spaces", "/path+with+spaces", {} - - converts "/foo&bar", %r{\A/foo(?:&|%26)bar\z} - parses "/foo&bar", "/foo&bar", {} - - converts "/:foo/*", %r{\A/([^/?#]+)/(.*?)\z} - parses "/:foo/*", "/hello%20world/how%20are%20you", "foo" => "hello%20world", "splat" => "how%20are%20you" - - converts "/*/foo/*/*", %r{\A/(.*?)/foo/(.*?)/(.*?)\z} - parses "/*/foo/*/*", "/bar/foo/bling/baz/boom", "splat" => ["bar", "bling", "baz/boom"] - fails "/*/foo/*/*", "/bar/foo/baz" - - converts "/test.bar", %r{\A/test(?:\.|%2[Ee])bar\z} - parses "/test.bar", "/test.bar", {} - fails "/test.bar", "/test0bar" - - converts "/:file.:ext", %r{\A/((?:[^\./?#%]|(?:%[^2].|%[2][^Ee]))+)(?:\.|%2[Ee])((?:[^/?#%]|(?:%[^2].|%[2][^Ee]))+)\z} - parses "/:file.:ext", "/pony.jpg", "file" => "pony", "ext" => "jpg" - parses "/:file.:ext", "/pony%2Ejpg", "file" => "pony", "ext" => "jpg" - fails "/:file.:ext", "/.jpg" - - converts "/:name.?:format?", %r{\A/((?:[^\./?#%]|(?:%[^2].|%[2][^Ee]))+)(?:\.|%2[Ee])?((?:[^/?#%]|(?:%[^2].|%[2][^Ee]))+)?\z} - parses "/:name.?:format?", "/foo", "name" => "foo", "format" => nil - parses "/:name.?:format?", "/foo.bar", "name" => "foo", "format" => "bar" - parses "/:name.?:format?", "/foo%2Ebar", "name" => "foo", "format" => "bar" - parses "/:name?.?:format", "/.bar", "name" => nil, "format" => "bar" - parses "/:name?.?:format?", "/.bar", "name" => nil, "format" => "bar" - parses "/:name?.:format?", "/.bar", "name" => nil, "format" => "bar" - fails "/:name.:format", "/.bar" - fails "/:name.?:format?", "/.bar" - - converts "/:user@?:host?", %r{\A/((?:[^@/?#%]|(?:%[^4].|%[4][^0]))+)(?:@|%40)?((?:[^@/?#%]|(?:%[^4].|%[4][^0]))+)?\z} - parses "/:user@?:host?", "/foo@bar", "user" => "foo", "host" => "bar" - parses "/:user@?:host?", "/foo.foo@bar", "user" => "foo.foo", "host" => "bar" - parses "/:user@?:host?", "/foo@bar.bar", "user" => "foo", "host" => "bar.bar" - - # From https://gist.github.com/2154980#gistcomment-169469. - # - # converts "/:name(.:format)?", %r{\A/([^\.%2E/?#]+)(?:\(|%28)(?:\.|%2E)([^\.%2E/?#]+)(?:\)|%29)?\z} - # parses "/:name(.:format)?", "/foo", "name" => "foo", "format" => nil - # parses "/:name(.:format)?", "/foo.bar", "name" => "foo", "format" => "bar" - fails "/:name(.:format)?", "/foo." - - parses "/:id/test.bar", "/3/test.bar", {"id" => "3"} - parses "/:id/test.bar", "/2/test.bar", {"id" => "2"} - parses "/:id/test.bar", "/2E/test.bar", {"id" => "2E"} - parses "/:id/test.bar", "/2e/test.bar", {"id" => "2e"} - parses "/:id/test.bar", "/%2E/test.bar", {"id" => "%2E"} - - parses '/10/:id', '/10/test', "id" => "test" - parses '/10/:id', '/10/te.st', "id" => "te.st" - - parses '/10.1/:id', '/10.1/test', "id" => "test" - parses '/10.1/:id', '/10.1/te.st', "id" => "te.st" - parses '/:foo/:id', '/10.1/te.st', "foo" => "10.1", "id" => "te.st" - parses '/:foo/:id', '/10.1.2/te.st', "foo" => "10.1.2", "id" => "te.st" - parses '/:foo.:bar/:id', '/10.1/te.st', "foo" => "10", "bar" => "1", "id" => "te.st" - fails '/:foo.:bar/:id', '/10.1.2/te.st' # We don't do crazy. - - parses '/:a/:b.?:c?', '/a/b', "a" => "a", "b" => "b", "c" => nil - parses '/:a/:b.?:c?', '/a/b.c', "a" => "a", "b" => "b", "c" => "c" - parses '/:a/:b.?:c?', '/a.b/c', "a" => "a.b", "b" => "c", "c" => nil - parses '/:a/:b.?:c?', '/a.b/c.d', "a" => "a.b", "b" => "c", "c" => "d" - fails '/:a/:b.?:c?', '/a.b/c.d/e' - - parses "/:file.:ext", "/pony%2ejpg", "file" => "pony", "ext" => "jpg" - parses "/:file.:ext", "/pony%E6%AD%A3%2Ejpg", "file" => "pony%E6%AD%A3", "ext" => "jpg" - parses "/:file.:ext", "/pony%e6%ad%a3%2ejpg", "file" => "pony%e6%ad%a3", "ext" => "jpg" - parses "/:file.:ext", "/pony正%2Ejpg", "file" => "pony正", "ext" => "jpg" - parses "/:file.:ext", "/pony正%2ejpg", "file" => "pony正", "ext" => "jpg" - parses "/:file.:ext", "/pony正..jpg", "file" => "pony正", "ext" => ".jpg" - fails "/:file.:ext", "/pony正.%2ejpg" - - converts "/:name.:format", %r{\A/((?:[^\./?#%]|(?:%[^2].|%[2][^Ee]))+)(?:\.|%2[Ee])((?:[^/?#%]|(?:%[^2].|%[2][^Ee]))+)\z} - parses "/:name.:format", "/file.tar.gz", "name" => "file", "format" => "tar.gz" - parses "/:name.:format1.:format2", "/file.tar.gz", "name" => "file", "format1" => "tar", "format2" => "gz" - parses "/:name.:format1.:format2", "/file.temp.tar.gz", "name" => "file", "format1" => "temp", "format2" => "tar.gz" - - # From issue #688. - # - parses "/articles/10.1103/:doi", "/articles/10.1103/PhysRevLett.110.026401", "doi" => "PhysRevLett.110.026401" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/contest.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/contest.rb deleted file mode 100644 index 75447aa..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/contest.rb +++ /dev/null @@ -1,100 +0,0 @@ -# Copyright (c) 2009 Damian Janowski and Michel Martens for Citrusbyte -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -require "test/unit" - -# Test::Unit loads a default test if the suite is empty, whose purpose is to -# fail. Since having empty contexts is a common practice, we decided to -# overwrite TestSuite#empty? in order to allow them. Having a failure when no -# tests have been defined seems counter-intuitive. -class Test::Unit::TestSuite - def empty? - false - end -end - -# Contest adds +teardown+, +test+ and +context+ as class methods, and the -# instance methods +setup+ and +teardown+ now iterate on the corresponding -# blocks. Note that all setup and teardown blocks must be defined with the -# block syntax. Adding setup or teardown instance methods defeats the purpose -# of this library. -class Test::Unit::TestCase - def self.setup(&block) setup_blocks << block end - def self.teardown(&block) teardown_blocks << block end - def self.setup_blocks() @setup_blocks ||= [] end - def self.teardown_blocks() @teardown_blocks ||= [] end - - def setup_blocks(base = self.class) - setup_blocks base.superclass if base.superclass.respond_to? :setup_blocks - base.setup_blocks.each do |block| - instance_eval(&block) - end - end - - def teardown_blocks(base = self.class) - teardown_blocks base.superclass if base.superclass.respond_to? :teardown_blocks - base.teardown_blocks.each do |block| - instance_eval(&block) - end - end - - alias setup setup_blocks - alias teardown teardown_blocks - - def self.context(*name, &block) - subclass = Class.new(self) - remove_tests(subclass) - subclass.class_eval(&block) if block_given? - const_set(context_name(name.join(" ")), subclass) - end - - def self.test(name, &block) - define_method(test_name(name), &block) - end - - class << self - alias_method :should, :test - alias_method :describe, :context - end - -private - - def self.context_name(name) - # "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}".to_sym - name = "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}" - name.tr(" ", "_").to_sym - end - - def self.test_name(name) - name = "test_#{sanitize_name(name).gsub(/\s+/,'_')}_0" - name = name.succ while method_defined? name - name.to_sym - end - - def self.sanitize_name(name) - # name.gsub(/\W+/, ' ').strip - name.gsub(/\W+/, ' ') - end - - def self.remove_tests(subclass) - subclass.public_instance_methods.grep(/^test_/).each do |meth| - subclass.send(:undef_method, meth.to_sym) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/creole_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/creole_test.rb deleted file mode 100644 index 1a51e2b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/creole_test.rb +++ /dev/null @@ -1,65 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'creole' - -class CreoleTest < Test::Unit::TestCase - def creole_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline creole strings' do - creole_app { creole '= Hiya' } - assert ok? - assert_body "

Hiya

" - end - - it 'renders .creole files in views path' do - creole_app { creole :hello } - assert ok? - assert_body "

Hello From Creole

" - end - - it "raises error if template not found" do - mock_app { get('/') { creole :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "renders with inline layouts" do - mock_app do - layout { 'THIS. IS. #{yield.upcase}!' } - get('/') { creole 'Sparta', :layout_engine => :str } - end - get '/' - assert ok? - assert_like 'THIS. IS.

SPARTA

!', body - end - - it "renders with file layouts" do - creole_app do - creole 'Hello World', :layout => :layout2, :layout_engine => :erb - end - assert ok? - assert_body "ERB Layout!\n

Hello World

" - end - - it "can be used in a nested fashion for partials and whatnot" do - mock_app do - template(:inner) { "hi" } - template(:outer) { "<%= creole :inner %>" } - get('/') { erb :outer } - end - - get '/' - assert ok? - assert_like '

hi

', body - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping creole tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/delegator_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/delegator_test.rb deleted file mode 100644 index cdda7b8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/delegator_test.rb +++ /dev/null @@ -1,160 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class DelegatorTest < Test::Unit::TestCase - class Mirror - attr_reader :last_call - def method_missing(*a, &b) - @last_call = [*a.map(&:to_s)] - @last_call << b if b - end - end - - def self.delegates(name) - it "delegates #{name}" do - m = mirror { send name } - assert_equal [name.to_s], m.last_call - end - - it "delegates #{name} with arguments" do - m = mirror { send name, "foo", "bar" } - assert_equal [name.to_s, "foo", "bar"], m.last_call - end - - it "delegates #{name} with block" do - block = proc { } - m = mirror { send(name, &block) } - assert_equal [name.to_s, block], m.last_call - end - end - - setup do - @target_was = Sinatra::Delegator.target - end - - def teardown - Sinatra::Delegator.target = @target_was - end - - def delegation_app(&block) - mock_app { Sinatra::Delegator.target = self } - delegate(&block) - end - - def mirror(&block) - mirror = Mirror.new - Sinatra::Delegator.target = mirror - delegate(&block) - end - - def delegate(&block) - assert Sinatra::Delegator.target != Sinatra::Application - Object.new.extend(Sinatra::Delegator).instance_eval(&block) if block - Sinatra::Delegator.target - end - - def target - Sinatra::Delegator.target - end - - it 'defaults to Sinatra::Application as target' do - assert_equal Sinatra::Application, Sinatra::Delegator.target - end - - %w[get put post delete options patch link unlink].each do |verb| - it "delegates #{verb} correctly" do - delegation_app do - send(verb, '/hello') { 'Hello World' } - end - - request = Rack::MockRequest.new(@app) - response = request.request(verb.upcase, '/hello', {}) - assert response.ok? - assert_equal 'Hello World', response.body - end - end - - it "delegates head correctly" do - delegation_app do - head '/hello' do - response['X-Hello'] = 'World!' - 'remove me' - end - end - - request = Rack::MockRequest.new(@app) - response = request.request('HEAD', '/hello', {}) - assert response.ok? - assert_equal 'World!', response['X-Hello'] - assert_equal '', response.body - end - - it "registers extensions with the delegation target" do - app, mixin = mirror, Module.new - Sinatra.register mixin - assert_equal ["register", mixin.to_s], app.last_call - end - - it "registers helpers with the delegation target" do - app, mixin = mirror, Module.new - Sinatra.helpers mixin - assert_equal ["helpers", mixin.to_s], app.last_call - end - - it "registers middleware with the delegation target" do - app, mixin = mirror, Module.new - Sinatra.use mixin - assert_equal ["use", mixin.to_s], app.last_call - end - - it "should work with method_missing proxies for options" do - mixin = Module.new do - def respond_to?(method, *) - method.to_sym == :options or super - end - - def method_missing(method, *args, &block) - return super unless method.to_sym == :options - {:some => :option} - end - end - - value = nil - mirror do - extend mixin - value = options - end - - assert_equal({:some => :option}, value) - end - - it "delegates crazy method names" do - Sinatra::Delegator.delegate "foo:bar:" - method = mirror { send "foo:bar:" }.last_call.first - assert_equal "foo:bar:", method - end - - delegates 'get' - delegates 'patch' - delegates 'put' - delegates 'post' - delegates 'delete' - delegates 'head' - delegates 'options' - delegates 'template' - delegates 'layout' - delegates 'before' - delegates 'after' - delegates 'error' - delegates 'not_found' - delegates 'configure' - delegates 'set' - delegates 'mime_type' - delegates 'enable' - delegates 'disable' - delegates 'use' - delegates 'development?' - delegates 'test?' - delegates 'production?' - delegates 'helpers' - delegates 'settings' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/encoding_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/encoding_test.rb deleted file mode 100644 index a2e9f69..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/encoding_test.rb +++ /dev/null @@ -1,20 +0,0 @@ -# encoding: UTF-8 -require File.expand_path('../helper', __FILE__) -require 'erb' - -class BaseTest < Test::Unit::TestCase - setup do - @base = Sinatra.new(Sinatra::Base) - @base.set :views, File.dirname(__FILE__) + "/views" - end - - it 'allows unicode strings in ascii templates per default (1.9)' do - next unless defined? Encoding - @base.new!.erb(File.read(@base.views + "/ascii.erb").encode("ASCII"), {}, :value => "åkej") - end - - it 'allows ascii strings in unicode templates per default (1.9)' do - next unless defined? Encoding - @base.new!.erb(:utf8, {}, :value => "Some Lyrics".encode("ASCII")) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/erb_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/erb_test.rb deleted file mode 100644 index abf3bae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/erb_test.rb +++ /dev/null @@ -1,116 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class ERBTest < Test::Unit::TestCase - def engine - Tilt::ERBTemplate - end - - def setup - Tilt.prefer engine, :erb - super - end - - def erb_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'uses the correct engine' do - assert_equal engine, Tilt[:erb] - end - - it 'renders inline ERB strings' do - erb_app { erb '<%= 1 + 1 %>' } - assert ok? - assert_equal '2', body - end - - it 'renders .erb files in views path' do - erb_app { erb :hello } - assert ok? - assert_equal "Hello World\n", body - end - - it 'takes a :locals option' do - erb_app do - locals = {:foo => 'Bar'} - erb '<%= foo %>', :locals => locals - end - assert ok? - assert_equal 'Bar', body - end - - it "renders with inline layouts" do - mock_app do - layout { 'THIS. IS. <%= yield.upcase %>!' } - get('/') { erb 'Sparta' } - end - get '/' - assert ok? - assert_equal 'THIS. IS. SPARTA!', body - end - - it "renders with file layouts" do - erb_app { erb 'Hello World', :layout => :layout2 } - assert ok? - assert_body "ERB Layout!\nHello World" - end - - it "renders erb with blocks" do - mock_app do - def container - @_out_buf << "THIS." - yield - @_out_buf << "SPARTA!" - end - def is; "IS." end - get('/') { erb '<% container do %> <%= is %> <% end %>' } - end - get '/' - assert ok? - assert_equal 'THIS. IS. SPARTA!', body - end - - it "can be used in a nested fashion for partials and whatnot" do - mock_app do - template(:inner) { "<%= 'hi' %>" } - template(:outer) { "<%= erb :inner %>" } - get('/') { erb :outer } - end - - get '/' - assert ok? - assert_equal 'hi', body - end - - it "can render truly nested layouts by accepting a layout and a block with the contents" do - mock_app do - template(:main_outer_layout) { "

Title

\n<%= yield %>" } - template(:an_inner_layout) { "

Subtitle

\n<%= yield %>" } - template(:a_page) { "

Contents.

\n" } - get('/') do - erb :main_outer_layout, :layout => false do - erb :an_inner_layout do - erb :a_page - end - end - end - end - get '/' - assert ok? - assert_body "

Title

\n

Subtitle

\n

Contents.

\n" - end -end - - -begin - require 'erubis' - class ErubisTest < ERBTest - def engine; Tilt::ErubisTemplate end - end -rescue LoadError - warn "#{$!.to_s}: skipping erubis tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/extensions_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/extensions_test.rb deleted file mode 100644 index a423f8f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/extensions_test.rb +++ /dev/null @@ -1,98 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class ExtensionsTest < Test::Unit::TestCase - module FooExtensions - def foo - end - - private - def im_hiding_in_ur_foos - end - end - - module BarExtensions - def bar - end - end - - module BazExtensions - def baz - end - end - - module QuuxExtensions - def quux - end - end - - module PainExtensions - def foo=(name); end - def bar?(name); end - def fizz!(name); end - end - - it 'will add the methods to the DSL for the class in which you register them and its subclasses' do - Sinatra::Base.register FooExtensions - assert Sinatra::Base.respond_to?(:foo) - - Sinatra::Application.register BarExtensions - assert Sinatra::Application.respond_to?(:bar) - assert Sinatra::Application.respond_to?(:foo) - assert !Sinatra::Base.respond_to?(:bar) - end - - it 'allows extending by passing a block' do - Sinatra::Base.register { def im_in_ur_anonymous_module; end } - assert Sinatra::Base.respond_to?(:im_in_ur_anonymous_module) - end - - it 'will make sure any public methods added via Application#register are delegated to Sinatra::Delegator' do - Sinatra::Application.register FooExtensions - assert Sinatra::Delegator.private_instance_methods. - map { |m| m.to_sym }.include?(:foo) - assert !Sinatra::Delegator.private_instance_methods. - map { |m| m.to_sym }.include?(:im_hiding_in_ur_foos) - end - - it 'will handle special method names' do - Sinatra::Application.register PainExtensions - assert Sinatra::Delegator.private_instance_methods. - map { |m| m.to_sym }.include?(:foo=) - assert Sinatra::Delegator.private_instance_methods. - map { |m| m.to_sym }.include?(:bar?) - assert Sinatra::Delegator.private_instance_methods. - map { |m| m.to_sym }.include?(:fizz!) - end - - it 'will not delegate methods on Base#register' do - Sinatra::Base.register QuuxExtensions - assert !Sinatra::Delegator.private_instance_methods.include?("quux") - end - - it 'will extend the Sinatra::Application application by default' do - Sinatra.register BazExtensions - assert !Sinatra::Base.respond_to?(:baz) - assert Sinatra::Application.respond_to?(:baz) - end - - module BizzleExtension - def bizzle - bizzle_option - end - - def self.registered(base) - fail "base should be BizzleApp" unless base == BizzleApp - fail "base should have already extended BizzleExtension" unless base.respond_to?(:bizzle) - base.set :bizzle_option, 'bizzle!' - end - end - - class BizzleApp < Sinatra::Base - end - - it 'sends .registered to the extension module after extending the class' do - BizzleApp.register BizzleExtension - assert_equal 'bizzle!', BizzleApp.bizzle_option - assert_equal 'bizzle!', BizzleApp.bizzle - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/filter_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/filter_test.rb deleted file mode 100644 index 8f35b47..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/filter_test.rb +++ /dev/null @@ -1,487 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class BeforeFilterTest < Test::Unit::TestCase - it "executes filters in the order defined" do - count = 0 - mock_app do - get('/') { 'Hello World' } - before do - assert_equal 0, count - count = 1 - end - before do - assert_equal 1, count - count = 2 - end - end - - get '/' - assert ok? - assert_equal 2, count - assert_equal 'Hello World', body - end - - it "can modify the request" do - mock_app do - get('/foo') { 'foo' } - get('/bar') { 'bar' } - before { request.path_info = '/bar' } - end - - get '/foo' - assert ok? - assert_equal 'bar', body - end - - it "can modify instance variables available to routes" do - mock_app do - before { @foo = 'bar' } - get('/foo') { @foo } - end - - get '/foo' - assert ok? - assert_equal 'bar', body - end - - it "allows redirects" do - mock_app do - before { redirect '/bar' } - get('/foo') do - fail 'before block should have halted processing' - 'ORLY?!' - end - end - - get '/foo' - assert redirect? - assert_equal 'http://example.org/bar', response['Location'] - assert_equal '', body - end - - it "does not modify the response with its return value" do - mock_app do - before { 'Hello World!' } - get('/foo') do - assert_equal [], response.body - 'cool' - end - end - - get '/foo' - assert ok? - assert_equal 'cool', body - end - - it "does modify the response with halt" do - mock_app do - before { halt 302, 'Hi' } - get '/foo' do - "should not happen" - end - end - - get '/foo' - assert_equal 302, response.status - assert_equal 'Hi', body - end - - it "gives you access to params" do - mock_app do - before { @foo = params['foo'] } - get('/foo') { @foo } - end - - get '/foo?foo=cool' - assert ok? - assert_equal 'cool', body - end - - it "properly unescapes parameters" do - mock_app do - before { @foo = params['foo'] } - get('/foo') { @foo } - end - - get '/foo?foo=bar%3Abaz%2Fbend' - assert ok? - assert_equal 'bar:baz/bend', body - end - - it "runs filters defined in superclasses" do - base = Class.new(Sinatra::Base) - base.before { @foo = 'hello from superclass' } - - mock_app(base) { get('/foo') { @foo } } - - get '/foo' - assert_equal 'hello from superclass', body - end - - it 'does not run before filter when serving static files' do - ran_filter = false - mock_app do - before { ran_filter = true } - set :static, true - set :public_folder, File.dirname(__FILE__) - end - get "/#{File.basename(__FILE__)}" - assert ok? - assert_equal File.read(__FILE__), body - assert !ran_filter - end - - it 'takes an optional route pattern' do - ran_filter = false - mock_app do - before("/b*") { ran_filter = true } - get('/foo') { } - get('/bar') { } - end - get '/foo' - assert !ran_filter - get '/bar' - assert ran_filter - end - - it 'generates block arguments from route pattern' do - subpath = nil - mock_app do - before("/foo/:sub") { |s| subpath = s } - get('/foo/*') { } - end - get '/foo/bar' - assert_equal subpath, 'bar' - end - - it 'can catch exceptions in before filters and handle them properly' do - doodle = '' - mock_app do - before do - doodle += 'This begins' - raise StandardError, "before" - end - get "/" do - doodle = 'and runs' - end - error 500 do - "Error handled #{env['sinatra.error'].message}" - end - end - - doodle = '' - get '/' - assert_equal 'Error handled before', body - assert_equal 'This begins', doodle - end -end - -class AfterFilterTest < Test::Unit::TestCase - it "executes before and after filters in correct order" do - invoked = 0 - mock_app do - before { invoked = 2 } - get('/') { invoked += 2; 'hello' } - after { invoked *= 2 } - end - - get '/' - assert ok? - - assert_equal 8, invoked - end - - it "executes filters in the order defined" do - count = 0 - mock_app do - get('/') { 'Hello World' } - after do - assert_equal 0, count - count = 1 - end - after do - assert_equal 1, count - count = 2 - end - end - - get '/' - assert ok? - assert_equal 2, count - assert_equal 'Hello World', body - end - - it "allows redirects" do - mock_app do - get('/foo') { 'ORLY' } - after { redirect '/bar' } - end - - get '/foo' - assert redirect? - assert_equal 'http://example.org/bar', response['Location'] - assert_equal '', body - end - - it "does not modify the response with its return value" do - mock_app do - get('/foo') { 'cool' } - after { 'Hello World!' } - end - - get '/foo' - assert ok? - assert_equal 'cool', body - end - - it "does modify the response with halt" do - mock_app do - get '/foo' do - "should not be returned" - end - after { halt 302, 'Hi' } - end - - get '/foo' - assert_equal 302, response.status - assert_equal 'Hi', body - end - - it "runs filters defined in superclasses" do - count = 2 - base = Class.new(Sinatra::Base) - base.after { count *= 2 } - mock_app(base) do - get('/foo') do - count += 2 - "ok" - end - end - - get '/foo' - assert_equal 8, count - end - - it 'does not run after filter when serving static files' do - ran_filter = false - mock_app do - after { ran_filter = true } - set :static, true - set :public_folder, File.dirname(__FILE__) - end - get "/#{File.basename(__FILE__)}" - assert ok? - assert_equal File.read(__FILE__), body - assert !ran_filter - end - - it 'takes an optional route pattern' do - ran_filter = false - mock_app do - after("/b*") { ran_filter = true } - get('/foo') { } - get('/bar') { } - end - get '/foo' - assert !ran_filter - get '/bar' - assert ran_filter - end - - it 'changes to path_info from a pattern matching before filter are respected when routing' do - mock_app do - before('/foo') { request.path_info = '/bar' } - get('/bar') { 'blah' } - end - get '/foo' - assert ok? - assert_equal 'blah', body - end - - it 'generates block arguments from route pattern' do - subpath = nil - mock_app do - after("/foo/:sub") { |s| subpath = s } - get('/foo/*') { } - end - get '/foo/bar' - assert_equal subpath, 'bar' - end - - it 'is possible to access url params from the route param' do - ran = false - mock_app do - get('/foo/*') { } - before('/foo/:sub') do - assert_equal params[:sub], 'bar' - ran = true - end - end - get '/foo/bar' - assert ran - end - - it 'is possible to apply host_name conditions to before filters with no path' do - ran = false - mock_app do - before(:host_name => 'example.com') { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_HOST' => 'example.org' }) - assert !ran - get('/', {}, { 'HTTP_HOST' => 'example.com' }) - assert ran - end - - it 'is possible to apply host_name conditions to before filters with a path' do - ran = false - mock_app do - before('/foo', :host_name => 'example.com') { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_HOST' => 'example.com' }) - assert !ran - get('/foo', {}, { 'HTTP_HOST' => 'example.org' }) - assert !ran - get('/foo', {}, { 'HTTP_HOST' => 'example.com' }) - assert ran - end - - it 'is possible to apply host_name conditions to after filters with no path' do - ran = false - mock_app do - after(:host_name => 'example.com') { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_HOST' => 'example.org' }) - assert !ran - get('/', {}, { 'HTTP_HOST' => 'example.com' }) - assert ran - end - - it 'is possible to apply host_name conditions to after filters with a path' do - ran = false - mock_app do - after('/foo', :host_name => 'example.com') { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_HOST' => 'example.com' }) - assert !ran - get('/foo', {}, { 'HTTP_HOST' => 'example.org' }) - assert !ran - get('/foo', {}, { 'HTTP_HOST' => 'example.com' }) - assert ran - end - - it 'is possible to apply user_agent conditions to before filters with no path' do - ran = false - mock_app do - before(:user_agent => /foo/) { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_USER_AGENT' => 'bar' }) - assert !ran - get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) - assert ran - end - - it 'is possible to apply user_agent conditions to before filters with a path' do - ran = false - mock_app do - before('/foo', :user_agent => /foo/) { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) - assert !ran - get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' }) - assert !ran - get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' }) - assert ran - end - - it 'can add params' do - mock_app do - before { params['foo'] = 'bar' } - get('/') { params['foo'] } - end - - get '/' - assert_body 'bar' - end - - it 'can remove params' do - mock_app do - before { params.delete('foo') } - get('/') { params['foo'].to_s } - end - - get '/?foo=bar' - assert_body '' - end - - it 'is possible to apply user_agent conditions to after filters with no path' do - ran = false - mock_app do - after(:user_agent => /foo/) { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_USER_AGENT' => 'bar' }) - assert !ran - get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) - assert ran - end - - it 'is possible to apply user_agent conditions to after filters with a path' do - ran = false - mock_app do - after('/foo', :user_agent => /foo/) { ran = true } - get('/') { 'welcome' } - end - get('/', {}, { 'HTTP_USER_AGENT' => 'foo' }) - assert !ran - get('/foo', {}, { 'HTTP_USER_AGENT' => 'bar' }) - assert !ran - get('/foo', {}, { 'HTTP_USER_AGENT' => 'foo' }) - assert ran - end - - it 'only triggers provides condition if conforms with current Content-Type' do - mock_app do - before(:provides => :txt) { @type = 'txt' } - before(:provides => :html) { @type = 'html' } - get('/') { @type } - end - - get('/', {}, { 'HTTP_ACCEPT' => '*/*' }) - assert_body 'txt' - end - - it 'can catch exceptions in after filters and handle them properly' do - doodle = '' - mock_app do - after do - doodle += ' and after' - raise StandardError, "after" - end - get "/foo" do - doodle = 'Been now' - raise StandardError, "now" - end - get "/" do - doodle = 'Been now' - end - error 500 do - "Error handled #{env['sinatra.error'].message}" - end - end - - get '/foo' - assert_equal 'Error handled now', body - assert_equal 'Been now and after', doodle - - doodle = '' - get '/' - assert_equal 'Error handled after', body - assert_equal 'Been now and after', doodle - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/haml_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/haml_test.rb deleted file mode 100644 index dc62271..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/haml_test.rb +++ /dev/null @@ -1,109 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'haml' - -class HAMLTest < Test::Unit::TestCase - def haml_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline HAML strings' do - haml_app { haml '%h1 Hiya' } - assert ok? - assert_equal "

Hiya

\n", body - end - - it 'renders .haml files in views path' do - haml_app { haml :hello } - assert ok? - assert_equal "

Hello From Haml

\n", body - end - - it "renders with inline layouts" do - mock_app do - layout { %q(%h1= 'THIS. IS. ' + yield.upcase) } - get('/') { haml '%em Sparta' } - end - get '/' - assert ok? - assert_equal "

THIS. IS. SPARTA

\n", body - end - - it "renders with file layouts" do - haml_app { haml 'Hello World', :layout => :layout2 } - assert ok? - assert_equal "

HAML Layout!

\n

Hello World

\n", body - end - - it "raises error if template not found" do - mock_app { get('/') { haml :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "passes HAML options to the Haml engine" do - mock_app { - get('/') { haml "!!!\n%h1 Hello World", :format => :html5 } - } - get '/' - assert ok? - assert_equal "\n

Hello World

\n", body - end - - it "passes default HAML options to the Haml engine" do - mock_app do - set :haml, {:format => :html5} - get('/') { haml "!!!\n%h1 Hello World" } - end - get '/' - assert ok? - assert_equal "\n

Hello World

\n", body - end - - it "merges the default HAML options with the overrides and passes them to the Haml engine" do - mock_app do - set :haml, {:format => :html5, :attr_wrapper => '"'} # default HAML attr are - get('/') { haml "!!!\n%h1{:class => :header} Hello World" } - get('/html4') { - haml "!!!\n%h1{:class => 'header'} Hello World", :format => :html4 - } - end - get '/' - assert ok? - assert_equal "\n

Hello World

\n", body - get '/html4' - assert ok? - assert_match(/^ { :foo => 'bar' }} - assert_equal "bar\n", body - end - - it "can render truly nested layouts by accepting a layout and a block with the contents" do - mock_app do - template(:main_outer_layout) { "%h1 Title\n= yield" } - template(:an_inner_layout) { "%h2 Subtitle\n= yield" } - template(:a_page) { "%p Contents." } - get('/') do - haml :main_outer_layout, :layout => false do - haml :an_inner_layout do - haml :a_page - end - end - end - end - get '/' - assert ok? - assert_body "

Title

\n

Subtitle

\n

Contents.

\n" - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping haml tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/helper.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/helper.rb deleted file mode 100644 index 1a96710..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/helper.rb +++ /dev/null @@ -1,131 +0,0 @@ -ENV['RACK_ENV'] = 'test' -Encoding.default_external = "UTF-8" if defined? Encoding - -RUBY_ENGINE = 'ruby' unless defined? RUBY_ENGINE - -begin - require 'rack' -rescue LoadError - require 'rubygems' - require 'rack' -end - -testdir = File.dirname(__FILE__) -$LOAD_PATH.unshift testdir unless $LOAD_PATH.include?(testdir) - -libdir = File.dirname(File.dirname(__FILE__)) + '/lib' -$LOAD_PATH.unshift libdir unless $LOAD_PATH.include?(libdir) - -require 'contest' -require 'rack/test' -require 'sinatra/base' - -class Sinatra::Base - # Allow assertions in request context - include Test::Unit::Assertions -end - -class Rack::Builder - def include?(middleware) - @ins.any? { |m| p m ; middleware === m } - end -end - -Sinatra::Base.set :environment, :test - -class Test::Unit::TestCase - include Rack::Test::Methods - - class << self - alias_method :it, :test - alias_method :section, :context - end - - def self.example(desc = nil, &block) - @example_count = 0 unless instance_variable_defined? :@example_count - @example_count += 1 - it(desc || "Example #{@example_count}", &block) - end - - alias_method :response, :last_response - - setup do - Sinatra::Base.set :environment, :test - end - - # Sets up a Sinatra::Base subclass defined with the block - # given. Used in setup or individual spec methods to establish - # the application. - def mock_app(base=Sinatra::Base, &block) - @app = Sinatra.new(base, &block) - end - - def app - Rack::Lint.new(@app) - end - - def body - response.body.to_s - end - - def assert_body(value) - if value.respond_to? :to_str - assert_equal value.lstrip.gsub(/\s*\n\s*/, ""), body.lstrip.gsub(/\s*\n\s*/, "") - else - assert_match value, body - end - end - - def assert_status(expected) - assert_equal Integer(expected), Integer(status) - end - - def assert_like(a,b) - pattern = /id=['"][^"']*["']|\s+/ - assert_equal a.strip.gsub(pattern, ""), b.strip.gsub(pattern, "") - end - - def assert_include(str, substr) - assert str.include?(substr), "expected #{str.inspect} to include #{substr.inspect}" - end - - def options(uri, params = {}, env = {}, &block) - request(uri, env.merge(:method => "OPTIONS", :params => params), &block) - end - - def patch(uri, params = {}, env = {}, &block) - request(uri, env.merge(:method => "PATCH", :params => params), &block) - end - - def link(uri, params = {}, env = {}, &block) - request(uri, env.merge(:method => "LINK", :params => params), &block) - end - - def unlink(uri, params = {}, env = {}, &block) - request(uri, env.merge(:method => "UNLINK", :params => params), &block) - end - - # Delegate other missing methods to response. - def method_missing(name, *args, &block) - if response && response.respond_to?(name) - response.send(name, *args, &block) - else - super - end - rescue Rack::Test::Error - super - end - - # Also check response since we delegate there. - def respond_to?(symbol, include_private=false) - super || (response && response.respond_to?(symbol, include_private)) - end - - # Do not output warnings for the duration of the block. - def silence_warnings - $VERBOSE, v = nil, $VERBOSE - yield - ensure - $VERBOSE = v - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/helpers_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/helpers_test.rb deleted file mode 100644 index 0eb45e9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/helpers_test.rb +++ /dev/null @@ -1,1917 +0,0 @@ -require File.expand_path('../helper', __FILE__) -require 'date' -require 'json' - -class HelpersTest < Test::Unit::TestCase - def test_default - assert true - end - - def status_app(code, &block) - code += 2 if [204, 205, 304].include? code - block ||= proc { } - mock_app do - get('/') do - status code - instance_eval(&block).inspect - end - end - get '/' - end - - describe 'status' do - it 'sets the response status code' do - status_app 207 - assert_equal 207, response.status - end - end - - describe 'not_found?' do - it 'is true for status == 404' do - status_app(404) { not_found? } - assert_body 'true' - end - - it 'is false for status gt 404' do - status_app(405) { not_found? } - assert_body 'false' - end - - it 'is false for status lt 404' do - status_app(403) { not_found? } - assert_body 'false' - end - end - - describe 'informational?' do - it 'is true for 1xx status' do - status_app(100 + rand(100)) { informational? } - assert_body 'true' - end - - it 'is false for status > 199' do - status_app(200 + rand(400)) { informational? } - assert_body 'false' - end - end - - describe 'success?' do - it 'is true for 2xx status' do - status_app(200 + rand(100)) { success? } - assert_body 'true' - end - - it 'is false for status < 200' do - status_app(100 + rand(100)) { success? } - assert_body 'false' - end - - it 'is false for status > 299' do - status_app(300 + rand(300)) { success? } - assert_body 'false' - end - end - - describe 'redirect?' do - it 'is true for 3xx status' do - status_app(300 + rand(100)) { redirect? } - assert_body 'true' - end - - it 'is false for status < 300' do - status_app(200 + rand(100)) { redirect? } - assert_body 'false' - end - - it 'is false for status > 399' do - status_app(400 + rand(200)) { redirect? } - assert_body 'false' - end - end - - describe 'client_error?' do - it 'is true for 4xx status' do - status_app(400 + rand(100)) { client_error? } - assert_body 'true' - end - - it 'is false for status < 400' do - status_app(200 + rand(200)) { client_error? } - assert_body 'false' - end - - it 'is false for status > 499' do - status_app(500 + rand(100)) { client_error? } - assert_body 'false' - end - end - - describe 'server_error?' do - it 'is true for 5xx status' do - status_app(500 + rand(100)) { server_error? } - assert_body 'true' - end - - it 'is false for status < 500' do - status_app(200 + rand(300)) { server_error? } - assert_body 'false' - end - end - - describe 'body' do - it 'takes a block for deferred body generation' do - mock_app do - get('/') { body { 'Hello World' } } - end - - get '/' - assert_equal 'Hello World', body - end - - it 'takes a String, Array, or other object responding to #each' do - mock_app { get('/') { body 'Hello World' } } - - get '/' - assert_equal 'Hello World', body - end - - it 'can be used with other objects' do - mock_app do - get '/' do - body :hello => 'from json' - end - - after do - if Hash === response.body - body response.body[:hello] - end - end - end - - get '/' - assert_body 'from json' - end - - it 'can be set in after filter' do - mock_app do - get('/') { body 'route' } - after { body 'filter' } - end - - get '/' - assert_body 'filter' - end - end - - describe 'redirect' do - it 'uses a 302 when only a path is given' do - mock_app do - get('/') do - redirect '/foo' - fail 'redirect should halt' - end - end - - get '/' - assert_equal 302, status - assert_equal '', body - assert_equal 'http://example.org/foo', response['Location'] - end - - it 'uses the code given when specified' do - mock_app do - get('/') do - redirect '/foo', 301 - fail 'redirect should halt' - end - end - - get '/' - assert_equal 301, status - assert_equal '', body - assert_equal 'http://example.org/foo', response['Location'] - end - - it 'redirects back to request.referer when passed back' do - mock_app { get('/try_redirect') { redirect back } } - - request = Rack::MockRequest.new(@app) - response = request.get('/try_redirect', 'HTTP_REFERER' => '/foo') - assert_equal 302, response.status - assert_equal 'http://example.org/foo', response['Location'] - end - - it 'redirects using a non-standard HTTP port' do - mock_app { get('/') { redirect '/foo' } } - - request = Rack::MockRequest.new(@app) - response = request.get('/', 'SERVER_PORT' => '81') - assert_equal 'http://example.org:81/foo', response['Location'] - end - - it 'redirects using a non-standard HTTPS port' do - mock_app { get('/') { redirect '/foo' } } - - request = Rack::MockRequest.new(@app) - response = request.get('/', 'SERVER_PORT' => '444') - assert_equal 'http://example.org:444/foo', response['Location'] - end - - it 'uses 303 for post requests if request is HTTP 1.1' do - mock_app { post('/') { redirect '/'} } - post('/', {}, 'HTTP_VERSION' => 'HTTP/1.1') - assert_equal 303, status - assert_equal '', body - assert_equal 'http://example.org/', response['Location'] - end - - it 'uses 302 for post requests if request is HTTP 1.0' do - mock_app { post('/') { redirect '/'} } - post('/', {}, 'HTTP_VERSION' => 'HTTP/1.0') - assert_equal 302, status - assert_equal '', body - assert_equal 'http://example.org/', response['Location'] - end - - it 'works behind a reverse proxy' do - mock_app { get('/') { redirect '/foo' } } - - request = Rack::MockRequest.new(@app) - response = request.get('/', 'HTTP_X_FORWARDED_HOST' => 'example.com', 'SERVER_PORT' => '8080') - assert_equal 'http://example.com/foo', response['Location'] - end - - it 'accepts absolute URIs' do - mock_app do - get('/') do - redirect 'http://google.com' - fail 'redirect should halt' - end - end - - get '/' - assert_equal 302, status - assert_equal '', body - assert_equal 'http://google.com', response['Location'] - end - - it 'accepts absolute URIs with a different schema' do - mock_app do - get('/') do - redirect 'mailto:jsmith@example.com' - fail 'redirect should halt' - end - end - - get '/' - assert_equal 302, status - assert_equal '', body - assert_equal 'mailto:jsmith@example.com', response['Location'] - end - - it 'accepts a URI object instead of a String' do - mock_app do - get('/') { redirect URI.parse('http://sinatrarb.com') } - end - - get '/' - assert_equal 302, status - assert_equal '', body - assert_equal 'http://sinatrarb.com', response['Location'] - end - end - - describe 'error' do - it 'sets a status code and halts' do - mock_app do - get('/') do - error 501 - fail 'error should halt' - end - end - - get '/' - assert_equal 501, status - assert_equal '', body - end - - it 'takes an optional body' do - mock_app do - get('/') do - error 501, 'FAIL' - fail 'error should halt' - end - end - - get '/' - assert_equal 501, status - assert_equal 'FAIL', body - end - - it 'should not invoke error handler when setting status inside an error handler' do - mock_app do - disable :raise_errors - not_found do - body "not_found handler" - status 404 - end - - error do - body "error handler" - status 404 - end - - get '/' do - raise - end - end - - get '/' - assert_equal 404, status - assert_equal 'error handler', body - end - - it 'should not reset the content-type to html for error handlers' do - mock_app do - disable :raise_errors - before { content_type "application/json" } - not_found { JSON.dump("error" => "Not Found") } - end - - get '/' - assert_equal 404, status - assert_equal 'application/json', response.content_type - end - - it 'should not invoke error handler when halting with 500 inside an error handler' do - mock_app do - disable :raise_errors - not_found do - body "not_found handler" - halt 404 - end - - error do - body "error handler" - halt 404 - end - - get '/' do - raise - end - end - - get '/' - assert_equal 404, status - assert_equal 'error handler', body - end - - it 'should not invoke not_found handler when halting with 404 inside a not found handler' do - mock_app do - disable :raise_errors - - not_found do - body "not_found handler" - halt 500 - end - - error do - body "error handler" - halt 500 - end - end - - get '/' - assert_equal 500, status - assert_equal 'not_found handler', body - end - - it 'uses a 500 status code when first argument is a body' do - mock_app do - get('/') do - error 'FAIL' - fail 'error should halt' - end - end - - get '/' - assert_equal 500, status - assert_equal 'FAIL', body - end - end - - describe 'not_found' do - it 'halts with a 404 status' do - mock_app do - get('/') do - not_found - fail 'not_found should halt' - end - end - - get '/' - assert_equal 404, status - assert_equal '', body - end - - it 'does not set a X-Cascade header' do - mock_app do - get('/') do - not_found - fail 'not_found should halt' - end - end - - get '/' - assert_equal 404, status - assert_equal nil, response.headers['X-Cascade'] - end - end - - describe 'headers' do - it 'sets headers on the response object when given a Hash' do - mock_app do - get('/') do - headers 'X-Foo' => 'bar', 'X-Baz' => 'bling' - 'kthx' - end - end - - get '/' - assert ok? - assert_equal 'bar', response['X-Foo'] - assert_equal 'bling', response['X-Baz'] - assert_equal 'kthx', body - end - - it 'returns the response headers hash when no hash provided' do - mock_app do - get('/') do - headers['X-Foo'] = 'bar' - 'kthx' - end - end - - get '/' - assert ok? - assert_equal 'bar', response['X-Foo'] - end - end - - describe 'session' do - it 'uses the existing rack.session' do - mock_app do - get('/') do - session[:foo] - end - end - - get('/', {}, { 'rack.session' => { :foo => 'bar' } }) - assert_equal 'bar', body - end - - it 'creates a new session when none provided' do - mock_app do - enable :sessions - - get('/') do - assert session[:foo].nil? - session[:foo] = 'bar' - redirect '/hi' - end - - get('/hi') do - "hi #{session[:foo]}" - end - end - - get '/' - follow_redirect! - assert_equal 'hi bar', body - end - - it 'inserts session middleware' do - mock_app do - enable :sessions - - get('/') do - assert env['rack.session'] - assert env['rack.session.options'] - 'ok' - end - end - - get '/' - assert_body 'ok' - end - - it 'sets a default session secret' do - mock_app do - enable :sessions - - get('/') do - secret = env['rack.session.options'][:secret] - assert secret - assert_equal secret, settings.session_secret - 'ok' - end - end - - get '/' - assert_body 'ok' - end - - it 'allows disabling session secret' do - mock_app do - enable :sessions - disable :session_secret - - get('/') do - assert !env['rack.session.options'].include?(:session_secret) - 'ok' - end - end - - # Silence warnings since Rack::Session::Cookie complains about the non-present session secret - silence_warnings do - get '/' - end - assert_body 'ok' - end - - it 'accepts an options hash' do - mock_app do - set :sessions, :foo => :bar - - get('/') do - assert_equal env['rack.session.options'][:foo], :bar - 'ok' - end - end - - get '/' - assert_body 'ok' - end - end - - describe 'mime_type' do - include Sinatra::Helpers - - it "looks up mime types in Rack's MIME registry" do - Rack::Mime::MIME_TYPES['.foo'] = 'application/foo' - assert_equal 'application/foo', mime_type('foo') - assert_equal 'application/foo', mime_type('.foo') - assert_equal 'application/foo', mime_type(:foo) - end - - it 'returns nil when given nil' do - assert mime_type(nil).nil? - end - - it 'returns nil when media type not registered' do - assert mime_type(:bizzle).nil? - end - - it 'returns the argument when given a media type string' do - assert_equal 'text/plain', mime_type('text/plain') - end - - it 'turns AcceptEntry into String' do - type = mime_type(Sinatra::Request::AcceptEntry.new('text/plain')) - assert_equal String, type.class - assert_equal 'text/plain', type - end - end - - test 'Base.mime_type registers mime type' do - mock_app do - mime_type :foo, 'application/foo' - - get('/') do - "foo is #{mime_type(:foo)}" - end - end - - get '/' - assert_equal 'foo is application/foo', body - end - - describe 'content_type' do - it 'sets the Content-Type header' do - mock_app do - get('/') do - content_type 'text/plain' - 'Hello World' - end - end - - get '/' - assert_equal 'text/plain;charset=utf-8', response['Content-Type'] - assert_equal 'Hello World', body - end - - it 'takes media type parameters (like charset=)' do - mock_app do - get('/') do - content_type 'text/html', :charset => 'latin1' - "

Hello, World

" - end - end - - get '/' - assert ok? - assert_equal 'text/html;charset=latin1', response['Content-Type'] - assert_equal "

Hello, World

", body - end - - it "looks up symbols in Rack's mime types dictionary" do - Rack::Mime::MIME_TYPES['.foo'] = 'application/foo' - mock_app do - get('/foo.xml') do - content_type :foo - "I AM FOO" - end - end - - get '/foo.xml' - assert ok? - assert_equal 'application/foo', response['Content-Type'] - assert_equal 'I AM FOO', body - end - - it 'fails when no mime type is registered for the argument provided' do - mock_app do - get('/foo.xml') do - content_type :bizzle - "I AM FOO" - end - end - - assert_raise(RuntimeError) { get '/foo.xml' } - end - - it 'only sets default charset for specific mime types' do - tests_ran = false - mock_app do - mime_type :foo, 'text/foo' - mime_type :bar, 'application/bar' - mime_type :baz, 'application/baz' - add_charset << mime_type(:baz) - get('/') do - assert_equal content_type(:txt), 'text/plain;charset=utf-8' - assert_equal content_type(:css), 'text/css;charset=utf-8' - assert_equal content_type(:html), 'text/html;charset=utf-8' - assert_equal content_type(:foo), 'text/foo;charset=utf-8' - assert_equal content_type(:xml), 'application/xml;charset=utf-8' - assert_equal content_type(:xhtml), 'application/xhtml+xml;charset=utf-8' - assert_equal content_type(:js), 'application/javascript;charset=utf-8' - assert_equal content_type(:json), 'application/json' - assert_equal content_type(:bar), 'application/bar' - assert_equal content_type(:png), 'image/png' - assert_equal content_type(:baz), 'application/baz;charset=utf-8' - tests_ran = true - "done" - end - end - - get '/' - assert tests_ran - end - - it 'handles already present params' do - mock_app do - get('/') do - content_type 'foo/bar;level=1', :charset => 'utf-8' - 'ok' - end - end - - get '/' - assert_equal 'foo/bar;level=1, charset=utf-8', response['Content-Type'] - end - - it 'does not add charset if present' do - mock_app do - get('/') do - content_type 'text/plain;charset=utf-16' - 'ok' - end - end - - get '/' - assert_equal 'text/plain;charset=utf-16', response['Content-Type'] - end - - it 'properly encodes parameters with delimiter characters' do - mock_app do - before '/comma' do - content_type 'image/png', :comment => 'Hello, world!' - end - before '/semicolon' do - content_type 'image/png', :comment => 'semi;colon' - end - before '/quote' do - content_type 'image/png', :comment => '"Whatever."' - end - - get('*') { 'ok' } - end - - get '/comma' - assert_equal 'image/png;comment="Hello, world!"', response['Content-Type'] - get '/semicolon' - assert_equal 'image/png;comment="semi;colon"', response['Content-Type'] - get '/quote' - assert_equal 'image/png;comment="\"Whatever.\""', response['Content-Type'] - end - end - - describe 'attachment' do - def attachment_app(filename=nil) - mock_app do - get('/attachment') do - attachment filename - response.write("") - end - end - end - - it 'sets the Content-Type response header' do - attachment_app('test.xml') - get '/attachment' - assert_equal 'application/xml;charset=utf-8', response['Content-Type'] - assert_equal '', body - end - - it 'sets the Content-Type response header without extname' do - attachment_app('test') - get '/attachment' - assert_equal 'text/html;charset=utf-8', response['Content-Type'] - assert_equal '', body - end - - it 'sets the Content-Type response header with extname' do - mock_app do - get('/attachment') do - content_type :atom - attachment 'test.xml' - response.write("") - end - end - - get '/attachment' - assert_equal 'application/atom+xml', response['Content-Type'] - assert_equal '', body - end - - end - - describe 'send_file' do - setup do - @file = File.dirname(__FILE__) + '/file.txt' - File.open(@file, 'wb') { |io| io.write('Hello World') } - end - - def teardown - File.unlink @file - @file = nil - end - - def send_file_app(opts={}) - path = @file - mock_app { - get '/file.txt' do - send_file path, opts - end - } - end - - it "sends the contents of the file" do - send_file_app - get '/file.txt' - assert ok? - assert_equal 'Hello World', body - end - - it 'sets the Content-Type response header if a mime-type can be located' do - send_file_app - get '/file.txt' - assert_equal 'text/plain;charset=utf-8', response['Content-Type'] - end - - it 'sets the Content-Type response header if type option is set to a file extension' do - send_file_app :type => 'html' - get '/file.txt' - assert_equal 'text/html;charset=utf-8', response['Content-Type'] - end - - it 'sets the Content-Type response header if type option is set to a mime type' do - send_file_app :type => 'application/octet-stream' - get '/file.txt' - assert_equal 'application/octet-stream', response['Content-Type'] - end - - it 'sets the Content-Length response header' do - send_file_app - get '/file.txt' - assert_equal 'Hello World'.length.to_s, response['Content-Length'] - end - - it 'sets the Last-Modified response header' do - send_file_app - get '/file.txt' - assert_equal File.mtime(@file).httpdate, response['Last-Modified'] - end - - it 'allows passing in a different Last-Modified response header with :last_modified' do - time = Time.now - send_file_app :last_modified => time - get '/file.txt' - assert_equal time.httpdate, response['Last-Modified'] - end - - it "returns a 404 when not found" do - mock_app { - get('/') { send_file 'this-file-does-not-exist.txt' } - } - get '/' - assert not_found? - end - - it "does not set the Content-Disposition header by default" do - send_file_app - get '/file.txt' - assert_nil response['Content-Disposition'] - end - - it "sets the Content-Disposition header when :disposition set to 'attachment'" do - send_file_app :disposition => 'attachment' - get '/file.txt' - assert_equal 'attachment; filename="file.txt"', response['Content-Disposition'] - end - - it "does not set add a file name if filename is false" do - send_file_app :disposition => 'inline', :filename => false - get '/file.txt' - assert_equal 'inline', response['Content-Disposition'] - end - - it "sets the Content-Disposition header when :disposition set to 'inline'" do - send_file_app :disposition => 'inline' - get '/file.txt' - assert_equal 'inline; filename="file.txt"', response['Content-Disposition'] - end - - it "sets the Content-Disposition header when :filename provided" do - send_file_app :filename => 'foo.txt' - get '/file.txt' - assert_equal 'attachment; filename="foo.txt"', response['Content-Disposition'] - end - - it 'allows setting a custom status code' do - send_file_app :status => 201 - get '/file.txt' - assert_status 201 - end - - it "is able to send files with unknown mime type" do - @file = File.dirname(__FILE__) + '/file.foobar' - File.open(@file, 'wb') { |io| io.write('Hello World') } - send_file_app - get '/file.txt' - assert_equal 'application/octet-stream', response['Content-Type'] - end - - it "does not override Content-Type if already set and no explicit type is given" do - path = @file - mock_app do - get('/') do - content_type :png - send_file path - end - end - get '/' - assert_equal 'image/png', response['Content-Type'] - end - - it "does override Content-Type even if already set, if explicit type is given" do - path = @file - mock_app do - get('/') do - content_type :png - send_file path, :type => :gif - end - end - get '/' - assert_equal 'image/gif', response['Content-Type'] - end - - it 'can have :status option as a string' do - path = @file - mock_app do - post '/' do - send_file path, :status => '422' - end - end - post '/' - assert_equal response.status, 422 - end - end - - describe 'cache_control' do - setup do - mock_app do - get('/foo') do - cache_control :public, :no_cache, :max_age => 60.0 - 'Hello World' - end - - get('/bar') do - cache_control :public, :no_cache - 'Hello World' - end - end - end - - it 'sets the Cache-Control header' do - get '/foo' - assert_equal ['public', 'no-cache', 'max-age=60'], response['Cache-Control'].split(', ') - end - - it 'last argument does not have to be a hash' do - get '/bar' - assert_equal ['public', 'no-cache'], response['Cache-Control'].split(', ') - end - end - - describe 'expires' do - setup do - mock_app do - get('/foo') do - expires 60, :public, :no_cache - 'Hello World' - end - - get('/bar') { expires Time.now } - - get('/baz') { expires Time.at(0) } - - get('/blah') do - obj = Object.new - def obj.method_missing(*a, &b) 60.send(*a, &b) end - def obj.is_a?(thing) 60.is_a?(thing) end - expires obj, :public, :no_cache - 'Hello World' - end - - get('/boom') { expires '9999' } - end - end - - it 'sets the Cache-Control header' do - get '/foo' - assert_equal ['public', 'no-cache', 'max-age=60'], response['Cache-Control'].split(', ') - end - - it 'sets the Expires header' do - get '/foo' - assert_not_nil response['Expires'] - end - - it 'allows passing Time.now objects' do - get '/bar' - assert_not_nil response['Expires'] - end - - it 'allows passing Time.at objects' do - get '/baz' - assert_equal 'Thu, 01 Jan 1970 00:00:00 GMT', response['Expires'] - end - - it 'accepts values pretending to be a Numeric (like ActiveSupport::Duration)' do - get '/blah' - assert_equal ['public', 'no-cache', 'max-age=60'], response['Cache-Control'].split(', ') - end - - it 'fails when Time.parse raises an ArgumentError' do - assert_raise(ArgumentError) { get '/boom' } - end - end - - describe 'last_modified' do - it 'ignores nil' do - mock_app { get('/') { last_modified nil; 200; } } - - get '/' - assert ! response['Last-Modified'] - end - - it 'does not change a status other than 200' do - mock_app do - get('/') do - status 299 - last_modified Time.at(0) - 'ok' - end - end - - get('/', {}, 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT') - assert_status 299 - assert_body 'ok' - end - - [Time.now, DateTime.now, Date.today, Time.now.to_i, - Struct.new(:to_time).new(Time.now) ].each do |last_modified_time| - describe "with #{last_modified_time.class.name}" do - setup do - mock_app do - get('/') do - last_modified last_modified_time - 'Boo!' - end - end - wrapper = Object.new.extend Sinatra::Helpers - @last_modified_time = wrapper.time_for last_modified_time - end - - # fixes strange missing test error when running complete test suite. - it("does not complain about missing tests") { } - - context "when there's no If-Modified-Since header" do - it 'sets the Last-Modified header to a valid RFC 2616 date value' do - get '/' - assert_equal @last_modified_time.httpdate, response['Last-Modified'] - end - - it 'conditional GET misses and returns a body' do - get '/' - assert_equal 200, status - assert_equal 'Boo!', body - end - end - - context "when there's an invalid If-Modified-Since header" do - it 'sets the Last-Modified header to a valid RFC 2616 date value' do - get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'a really weird date' }) - assert_equal @last_modified_time.httpdate, response['Last-Modified'] - end - - it 'conditional GET misses and returns a body' do - get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'a really weird date' }) - assert_equal 200, status - assert_equal 'Boo!', body - end - end - - context "when the resource has been modified since the If-Modified-Since header date" do - it 'sets the Last-Modified header to a valid RFC 2616 date value' do - get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time - 1).httpdate }) - assert_equal @last_modified_time.httpdate, response['Last-Modified'] - end - - it 'conditional GET misses and returns a body' do - get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time - 1).httpdate }) - assert_equal 200, status - assert_equal 'Boo!', body - end - - it 'does not rely on string comparison' do - mock_app do - get('/compare') do - last_modified "Mon, 18 Oct 2010 20:57:11 GMT" - "foo" - end - end - - get('/compare', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2010 23:43:52 GMT' }) - assert_equal 200, status - assert_equal 'foo', body - get('/compare', {}, { 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT' }) - assert_equal 304, status - assert_equal '', body - end - end - - context "when the resource has been modified on the exact If-Modified-Since header date" do - it 'sets the Last-Modified header to a valid RFC 2616 date value' do - get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => @last_modified_time.httpdate }) - assert_equal @last_modified_time.httpdate, response['Last-Modified'] - end - - it 'conditional GET matches and halts' do - get( '/', {}, { 'HTTP_IF_MODIFIED_SINCE' => @last_modified_time.httpdate }) - assert_equal 304, status - assert_equal '', body - end - end - - context "when the resource hasn't been modified since the If-Modified-Since header date" do - it 'sets the Last-Modified header to a valid RFC 2616 date value' do - get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time + 1).httpdate }) - assert_equal @last_modified_time.httpdate, response['Last-Modified'] - end - - it 'conditional GET matches and halts' do - get('/', {}, { 'HTTP_IF_MODIFIED_SINCE' => (@last_modified_time + 1).httpdate }) - assert_equal 304, status - assert_equal '', body - end - end - - context "If-Unmodified-Since" do - it 'results in 200 if resource has not been modified' do - get('/', {}, { 'HTTP_IF_UNMODIFIED_SINCE' => 'Sun, 26 Sep 2030 23:43:52 GMT' }) - assert_equal 200, status - assert_equal 'Boo!', body - end - - it 'results in 412 if resource has been modified' do - get('/', {}, { 'HTTP_IF_UNMODIFIED_SINCE' => Time.at(0).httpdate }) - assert_equal 412, status - assert_equal '', body - end - end - end - end - end - - describe 'etag' do - context "safe requests" do - it 'returns 200 for normal requests' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get '/' - assert_status 200 - assert_body 'ok' - end - - context "If-None-Match" do - it 'returns 304 when If-None-Match is *' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 304 - assert_body '' - end - - it 'returns 200 when If-None-Match is * for new resources' do - mock_app do - get('/') do - etag 'foo', :new_resource => true - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 304 when If-None-Match is * for existing resources' do - mock_app do - get('/') do - etag 'foo', :new_resource => false - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 304 - assert_body '' - end - - it 'returns 304 when If-None-Match is the etag' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '"foo"') - assert_status 304 - assert_body '' - end - - it 'returns 304 when If-None-Match includes the etag' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar", "foo"') - assert_status 304 - assert_body '' - end - - it 'returns 200 when If-None-Match does not include the etag' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar"') - assert_status 200 - assert_body 'ok' - end - - it 'ignores If-Modified-Since if If-None-Match does not match' do - mock_app do - get('/') do - etag 'foo' - last_modified Time.at(0) - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar"') - assert_status 200 - assert_body 'ok' - end - - it 'does not change a status code other than 2xx or 304' do - mock_app do - get('/') do - status 499 - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '"foo"') - assert_status 499 - assert_body 'ok' - end - - it 'does change 2xx status codes' do - mock_app do - get('/') do - status 299 - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '"foo"') - assert_status 304 - assert_body '' - end - - it 'does not send a body on 304 status codes' do - mock_app do - get('/') do - status 304 - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_NONE_MATCH' => '"foo"') - assert_status 304 - assert_body '' - end - end - - context "If-Match" do - it 'returns 200 when If-Match is the etag' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_MATCH' => '"foo"') - assert_status 200 - assert_body 'ok' - end - - it 'returns 200 when If-Match includes the etag' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_MATCH' => '"foo", "bar"') - assert_status 200 - assert_body 'ok' - end - - it 'returns 200 when If-Match is *' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-Match is * for new resources' do - mock_app do - get('/') do - etag 'foo', :new_resource => true - 'ok' - end - end - - get('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 412 - assert_body '' - end - - it 'returns 200 when If-Match is * for existing resources' do - mock_app do - get('/') do - etag 'foo', :new_resource => false - 'ok' - end - end - - get('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-Match does not include the etag' do - mock_app do - get('/') do - etag 'foo' - 'ok' - end - end - - get('/', {}, 'HTTP_IF_MATCH' => '"bar"') - assert_status 412 - assert_body '' - end - end - end - - context "idempotent requests" do - it 'returns 200 for normal requests' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put '/' - assert_status 200 - assert_body 'ok' - end - - context "If-None-Match" do - it 'returns 412 when If-None-Match is *' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 412 - assert_body '' - end - - it 'returns 200 when If-None-Match is * for new resources' do - mock_app do - put('/') do - etag 'foo', :new_resource => true - 'ok' - end - end - - put('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-None-Match is * for existing resources' do - mock_app do - put('/') do - etag 'foo', :new_resource => false - 'ok' - end - end - - put('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 412 - assert_body '' - end - - it 'returns 412 when If-None-Match is the etag' do - mock_app do - put '/' do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_NONE_MATCH' => '"foo"') - assert_status 412 - assert_body '' - end - - it 'returns 412 when If-None-Match includes the etag' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar", "foo"') - assert_status 412 - assert_body '' - end - - it 'returns 200 when If-None-Match does not include the etag' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar"') - assert_status 200 - assert_body 'ok' - end - - it 'ignores If-Modified-Since if If-None-Match does not match' do - mock_app do - put('/') do - etag 'foo' - last_modified Time.at(0) - 'ok' - end - end - - put('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar"') - assert_status 200 - assert_body 'ok' - end - end - - context "If-Match" do - it 'returns 200 when If-Match is the etag' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_MATCH' => '"foo"') - assert_status 200 - assert_body 'ok' - end - - it 'returns 200 when If-Match includes the etag' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_MATCH' => '"foo", "bar"') - assert_status 200 - assert_body 'ok' - end - - it 'returns 200 when If-Match is *' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-Match is * for new resources' do - mock_app do - put('/') do - etag 'foo', :new_resource => true - 'ok' - end - end - - put('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 412 - assert_body '' - end - - it 'returns 200 when If-Match is * for existing resources' do - mock_app do - put('/') do - etag 'foo', :new_resource => false - 'ok' - end - end - - put('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-Match does not include the etag' do - mock_app do - put('/') do - etag 'foo' - 'ok' - end - end - - put('/', {}, 'HTTP_IF_MATCH' => '"bar"') - assert_status 412 - assert_body '' - end - end - end - - context "post requests" do - it 'returns 200 for normal requests' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/') - assert_status 200 - assert_body 'ok' - end - - context "If-None-Match" do - it 'returns 200 when If-None-Match is *' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 200 when If-None-Match is * for new resources' do - mock_app do - post('/') do - etag 'foo', :new_resource => true - 'ok' - end - end - - post('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-None-Match is * for existing resources' do - mock_app do - post('/') do - etag 'foo', :new_resource => false - 'ok' - end - end - - post('/', {}, 'HTTP_IF_NONE_MATCH' => '*') - assert_status 412 - assert_body '' - end - - it 'returns 412 when If-None-Match is the etag' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_NONE_MATCH' => '"foo"') - assert_status 412 - assert_body '' - end - - it 'returns 412 when If-None-Match includes the etag' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar", "foo"') - assert_status 412 - assert_body '' - end - - it 'returns 200 when If-None-Match does not include the etag' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar"') - assert_status 200 - assert_body 'ok' - end - - it 'ignores If-Modified-Since if If-None-Match does not match' do - mock_app do - post('/') do - etag 'foo' - last_modified Time.at(0) - 'ok' - end - end - - post('/', {}, 'HTTP_IF_NONE_MATCH' => '"bar"') - assert_status 200 - assert_body 'ok' - end - end - - context "If-Match" do - it 'returns 200 when If-Match is the etag' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_MATCH' => '"foo"') - assert_status 200 - assert_body 'ok' - end - - it 'returns 200 when If-Match includes the etag' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_MATCH' => '"foo", "bar"') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-Match is *' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 412 - assert_body '' - end - - it 'returns 412 when If-Match is * for new resources' do - mock_app do - post('/') do - etag 'foo', :new_resource => true - 'ok' - end - end - - post('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 412 - assert_body '' - end - - it 'returns 200 when If-Match is * for existing resources' do - mock_app do - post('/') do - etag 'foo', :new_resource => false - 'ok' - end - end - - post('/', {}, 'HTTP_IF_MATCH' => '*') - assert_status 200 - assert_body 'ok' - end - - it 'returns 412 when If-Match does not include the etag' do - mock_app do - post('/') do - etag 'foo' - 'ok' - end - end - - post('/', {}, 'HTTP_IF_MATCH' => '"bar"') - assert_status 412 - assert_body '' - end - end - end - - it 'uses a weak etag with the :weak option' do - mock_app do - get('/') do - etag 'FOO', :weak - "that's weak, dude." - end - end - get '/' - assert_equal 'W/"FOO"', response['ETag'] - end - - it 'raises an ArgumentError for an invalid strength' do - mock_app do - get('/') do - etag 'FOO', :w00t - "that's weak, dude." - end - end - assert_raise(ArgumentError) { get('/') } - end - end - - describe 'back' do - it "makes redirecting back pretty" do - mock_app { get('/foo') { redirect back } } - - get('/foo', {}, 'HTTP_REFERER' => 'http://github.com') - assert redirect? - assert_equal "http://github.com", response.location - end - end - - describe 'uri' do - it 'generates absolute urls' do - mock_app { get('/') { uri }} - get '/' - assert_equal 'http://example.org/', body - end - - it 'includes path_info' do - mock_app { get('/:name') { uri }} - get '/foo' - assert_equal 'http://example.org/foo', body - end - - it 'allows passing an alternative to path_info' do - mock_app { get('/:name') { uri '/bar' }} - get '/foo' - assert_equal 'http://example.org/bar', body - end - - it 'includes script_name' do - mock_app { get('/:name') { uri '/bar' }} - get '/foo', {}, { "SCRIPT_NAME" => '/foo' } - assert_equal 'http://example.org/foo/bar', body - end - - it 'handles absolute URIs' do - mock_app { get('/') { uri 'http://google.com' }} - get '/' - assert_equal 'http://google.com', body - end - - it 'handles different protocols' do - mock_app { get('/') { uri 'mailto:jsmith@example.com' }} - get '/' - assert_equal 'mailto:jsmith@example.com', body - end - - it 'is aliased to #url' do - mock_app { get('/') { url }} - get '/' - assert_equal 'http://example.org/', body - end - - it 'is aliased to #to' do - mock_app { get('/') { to }} - get '/' - assert_equal 'http://example.org/', body - end - end - - describe 'logger' do - it 'logging works when logging is enabled' do - mock_app do - enable :logging - get('/') do - logger.info "Program started" - logger.warn "Nothing to do!" - end - end - io = StringIO.new - get '/', {}, 'rack.errors' => io - assert io.string.include?("INFO -- : Program started") - assert io.string.include?("WARN -- : Nothing to do") - end - - it 'logging works when logging is disable, but no output is produced' do - mock_app do - disable :logging - get('/') do - logger.info "Program started" - logger.warn "Nothing to do!" - end - end - io = StringIO.new - get '/', {}, 'rack.errors' => io - assert !io.string.include?("INFO -- : Program started") - assert !io.string.include?("WARN -- : Nothing to do") - end - - it 'does not create a logger when logging is set to nil' do - mock_app do - set :logging, nil - get('/') { logger.inspect } - end - - get '/' - assert_body 'nil' - end - end - - module ::HelperOne; def one; '1'; end; end - module ::HelperTwo; def two; '2'; end; end - - describe 'Adding new helpers' do - it 'takes a list of modules to mix into the app' do - mock_app do - helpers ::HelperOne, ::HelperTwo - - get('/one') { one } - - get('/two') { two } - end - - get '/one' - assert_equal '1', body - - get '/two' - assert_equal '2', body - end - - it 'takes a block to mix into the app' do - mock_app do - helpers do - def foo - 'foo' - end - end - - get('/') { foo } - end - - get '/' - assert_equal 'foo', body - end - - it 'evaluates the block in class context so that methods can be aliased' do - mock_app do - helpers { alias_method :h, :escape_html } - - get('/') { h('42 < 43') } - end - - get '/' - assert ok? - assert_equal '42 < 43', body - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration/app.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration/app.rb deleted file mode 100644 index 3e87a00..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration/app.rb +++ /dev/null @@ -1,79 +0,0 @@ -$stderr.puts "loading" -require 'sinatra' - -configure do - set :foo, :bar -end - -get '/app_file' do - content_type :txt - settings.app_file -end - -get '/ping' do - 'pong' -end - -get '/stream' do - stream do |out| - sleep 0.1 - out << "a" - sleep 1.2 - out << "b" - end -end - -get '/mainonly' do - object = Object.new - begin - object.send(:get, '/foo') { } - 'false' - rescue NameError - 'true' - end -end - -set :out, nil -get '/async' do - stream(:keep_open) { |o| (settings.out = o) << "hi!" } -end - -get '/send' do - settings.out << params[:msg] if params[:msg] - settings.out.close if params[:close] - "ok" -end - -get '/send_file' do - file = File.expand_path '../../views/a/in_a.str', __FILE__ - send_file file -end - -get '/streaming' do - headers['Content-Length'] = '46' - stream do |out| - out << "It's gonna be legen -\n" - sleep 0.5 - out << " (wait for it) \n" - puts headers - sleep 1 - out << "- dary!\n" - end -end - -class Subclass < Sinatra::Base - set :out, nil - get '/subclass/async' do - stream(:keep_open) { |o| (settings.out = o) << "hi!" } - end - - get '/subclass/send' do - settings.out << params[:msg] if params[:msg] - settings.out.close if params[:close] - "ok" - end -end - -use Subclass - -$stderr.puts "starting" diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration_helper.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration_helper.rb deleted file mode 100644 index f747175..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration_helper.rb +++ /dev/null @@ -1,236 +0,0 @@ -require 'sinatra/base' -require 'rbconfig' -require 'open-uri' -require 'net/http' -require 'timeout' - -module IntegrationHelper - class BaseServer - extend Enumerable - attr_accessor :server, :port, :pipe - alias name server - - def self.all - @all ||= [] - end - - def self.each(&block) - all.each(&block) - end - - def self.run(server, port) - new(server, port).run - end - - def app_file - File.expand_path('../integration/app.rb', __FILE__) - end - - def environment - "development" - end - - def initialize(server, port) - @installed, @pipe, @server, @port = nil, nil, server, port - Server.all << self - end - - def run - return unless installed? - kill - @log = "" - @pipe = IO.popen(command) - @started = Time.now - warn "#{server} up and running on port #{port}" if ping - at_exit { kill } - end - - def ping(timeout = 30) - loop do - return if alive? - if Time.now - @started > timeout - $stderr.puts command, log - fail "timeout" - else - sleep 0.1 - end - end - end - - def alive? - 3.times { get('/ping') } - true - rescue Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError, SystemCallError, OpenURI::HTTPError, Timeout::Error - false - end - - def get_stream(url = "/stream", &block) - Net::HTTP.start '127.0.0.1', port do |http| - request = Net::HTTP::Get.new url - http.request request do |response| - response.read_body(&block) - end - end - end - - def get_response(url) - Net::HTTP.start '127.0.0.1', port do |http| - request = Net::HTTP::Get.new url - http.request request do |response| - response - end - end - end - - def get(url) - Timeout.timeout(1) { open("http://127.0.0.1:#{port}#{url}").read } - end - - def log - @log ||= "" - loop { @log << @pipe.read_nonblock(1) } - rescue Exception - @log - end - - def installed? - return @installed unless @installed.nil? - s = server == 'HTTP' ? 'net/http/server' : server - require s - @installed = true - rescue LoadError - warn "#{server} is not installed, skipping integration tests" - @installed = false - end - - def command - @command ||= begin - cmd = ["RACK_ENV=#{environment}", "exec"] - if RbConfig.respond_to? :ruby - cmd << RbConfig.ruby.inspect - else - file, dir = RbConfig::CONFIG.values_at('ruby_install_name', 'bindir') - cmd << File.expand_path(file, dir).inspect - end - cmd << "-w" unless thin? || net_http_server? - cmd << "-I" << File.expand_path('../../lib', __FILE__).inspect - cmd << app_file.inspect << '-s' << server << '-o' << '127.0.0.1' << '-p' << port - cmd << "-e" << environment.to_s << '2>&1' - cmd.join " " - end - end - - def kill - return unless pipe - Process.kill("KILL", pipe.pid) - rescue NotImplementedError - system "kill -9 #{pipe.pid}" - rescue Errno::ESRCH - end - - def webrick? - name.to_s == "webrick" - end - - def thin? - name.to_s == "thin" - end - - def puma? - name.to_s == "puma" - end - - def trinidad? - name.to_s == "trinidad" - end - - def net_http_server? - name.to_s == 'HTTP' - end - - def warnings - log.scan(%r[(?:\(eval|lib/sinatra).*warning:.*$]) - end - - def run_test(target, &block) - retries ||= 3 - target.server = self - run unless alive? - target.instance_eval(&block) - rescue Exception => error - retries -= 1 - kill - retries < 0 ? retry : raise(error) - end - end - - if RUBY_ENGINE == "jruby" - class JRubyServer < BaseServer - def start_vm - require 'java' - # Create a new container, set load paths and env - # SINGLETHREAD means create a new runtime - vm = org.jruby.embed.ScriptingContainer.new(org.jruby.embed.LocalContextScope::SINGLETHREAD) - vm.load_paths = [File.expand_path('../../lib', __FILE__)] - vm.environment = ENV.merge('RACK_ENV' => environment.to_s) - - # This ensures processing of RUBYOPT which activates Bundler - vm.provider.ruby_instance_config.process_arguments [] - vm.argv = ['-s', server.to_s, '-o', '127.0.0.1', '-p', port.to_s, '-e', environment.to_s] - - # Set stdout/stderr so we can retrieve log - @pipe = java.io.ByteArrayOutputStream.new - vm.output = java.io.PrintStream.new(@pipe) - vm.error = java.io.PrintStream.new(@pipe) - - Thread.new do - # Hack to ensure that Kernel#caller has the same info as - # when run from command-line, for Sinatra::Application.app_file. - # Also, line numbers are zero-based in JRuby's parser - vm.provider.runtime.current_context.set_file_and_line(app_file, 0) - # Run the app - vm.run_scriptlet org.jruby.embed.PathType::ABSOLUTE, app_file - # terminate launches at_exit hooks which start server - vm.terminate - end - end - - def run - return unless installed? - kill - @thread = start_vm - @started = Time.now - warn "#{server} up and running on port #{port}" if ping - at_exit { kill } - end - - def log - String.from_java_bytes @pipe.to_byte_array - end - - def kill - @thread.kill if @thread - @thread = nil - end - end - Server = JRubyServer - else - Server = BaseServer - end - - def it(message, &block) - Server.each do |server| - next unless server.installed? - super("with #{server.name}: #{message}") { server.run_test(self, &block) } - end - end - - def self.extend_object(obj) - super - - base_port = 5000 + Process.pid % 100 - Sinatra::Base.server.each_with_index do |server, index| - Server.run(server, base_port+index) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration_test.rb deleted file mode 100644 index b19d7ea..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/integration_test.rb +++ /dev/null @@ -1,104 +0,0 @@ -require File.expand_path('../helper', __FILE__) -require File.expand_path('../integration_helper', __FILE__) - -# These tests start a real server and talk to it over TCP. -# Every test runs with every detected server. -# -# See test/integration/app.rb for the code of the app we test against. -class IntegrationTest < Test::Unit::TestCase - extend IntegrationHelper - attr_accessor :server - - it('sets the app_file') { assert_equal server.app_file, server.get("/app_file") } - it('only extends main') { assert_equal "true", server.get("/mainonly") } - - it 'logs once in development mode' do - next if server.puma? or RUBY_ENGINE == 'jruby' - random = "%064x" % Kernel.rand(2**256-1) - server.get "/ping?x=#{random}" - count = server.log.scan("GET /ping?x=#{random}").count - if server.net_http_server? - assert_equal 0, count - elsif server.webrick? - assert(count > 0) - else - assert_equal(1, count) - end - end - - it 'streams' do - next if server.webrick? or server.trinidad? - times, chunks = [Time.now], [] - server.get_stream do |chunk| - next if chunk.empty? - chunks << chunk - times << Time.now - end - assert_equal ["a", "b"], chunks - assert times[1] - times[0] < 1 - assert times[2] - times[1] > 1 - end - - it 'streams async' do - next unless server.thin? - - Timeout.timeout(3) do - chunks = [] - server.get_stream '/async' do |chunk| - next if chunk.empty? - chunks << chunk - case chunk - when "hi!" then server.get "/send?msg=hello" - when "hello" then server.get "/send?close=1" - end - end - - assert_equal ['hi!', 'hello'], chunks - end - end - - it 'streams async from subclass' do - next unless server.thin? - - Timeout.timeout(3) do - chunks = [] - server.get_stream '/subclass/async' do |chunk| - next if chunk.empty? - chunks << chunk - case chunk - when "hi!" then server.get "/subclass/send?msg=hello" - when "hello" then server.get "/subclass/send?close=1" - end - end - - assert_equal ['hi!', 'hello'], chunks - end - end - - it 'starts the correct server' do - exp = %r{ - ==\sSinatra/#{Sinatra::VERSION}\s - has\staken\sthe\sstage\son\s\d+\sfor\sdevelopment\s - with\sbackup\sfrom\s#{server} - }ix - - # because Net HTTP Server logs to $stderr by default - assert_match exp, server.log unless server.net_http_server? - end - - it 'does not generate warnings' do - assert_raise(OpenURI::HTTPError) { server.get '/' } - server.get '/app_file' - assert_equal [], server.warnings - end - - it 'sets the Content-Length response header when sending files' do - response = server.get_response '/send_file' - assert response['Content-Length'] - end - - it "doesn't ignore Content-Length header when streaming" do - response = server.get_response '/streaming' - assert_equal '46', response['Content-Length'] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/less_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/less_test.rb deleted file mode 100644 index 505ef75..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/less_test.rb +++ /dev/null @@ -1,69 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'less' - -class LessTest < Test::Unit::TestCase - def less_app(options = {}, &block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - set options - get('/', &block) - end - get '/' - end - - it 'renders inline Less strings' do - less_app { - less "@white_color: #fff; #main { background-color: @white_color }" - } - assert ok? - assert_equal "#main{background-color:#ffffff;}", body.gsub(/\s/, "") - end - - it 'defaults content type to css' do - less_app { - less "@white_color: #fff; #main { background-color: @white_color }" - } - assert ok? - assert_equal "text/css;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type per route' do - less_app do - content_type :html - less "@white_color: #fff; #main { background-color: @white_color }" - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type globally' do - less_app(:less => { :content_type => 'html' }) do - less "@white_color: #fff; #main { background-color: @white_color }" - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'renders .less files in views path' do - less_app { less :hello } - assert ok? - assert_equal "#main{background-color:#ffffff;}", body.gsub(/\s/, "") - end - - it 'ignores the layout option' do - less_app { less :hello, :layout => :layout2 } - assert ok? - assert_equal "#main{background-color:#ffffff;}", body.gsub(/\s/, "") - end - - it "raises error if template not found" do - mock_app { get('/') { less :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping less tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/liquid_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/liquid_test.rb deleted file mode 100644 index 8a8f48e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/liquid_test.rb +++ /dev/null @@ -1,77 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'liquid' - -class LiquidTest < Test::Unit::TestCase - def liquid_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline liquid strings' do - liquid_app { liquid '

Hiya

' } - assert ok? - assert_equal "

Hiya

", body - end - - it 'renders .liquid files in views path' do - liquid_app { liquid :hello } - assert ok? - assert_equal "

Hello From Liquid

\n", body - end - - it "renders with inline layouts" do - mock_app do - layout { "

THIS. IS. {{ yield }}

" } - get('/') { liquid 'SPARTA' } - end - get '/' - assert ok? - assert_equal "

THIS. IS. SPARTA

", body - end - - it "renders with file layouts" do - liquid_app { liquid 'Hello World', :layout => :layout2 } - assert ok? - assert_equal "

Liquid Layout!

\n

Hello World

\n", body - end - - it "raises error if template not found" do - mock_app { get('/') { liquid :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "allows passing locals" do - liquid_app { - liquid '{{ value }}', :locals => { :value => 'foo' } - } - assert ok? - assert_equal 'foo', body - end - - it "can rendere truly nested layouts by accepting a layout and a block with the contents" do - mock_app do - template(:main_outer_layout) { "

Title

\n{{ yield }}" } - template(:an_inner_layout) { "

Subtitle

\n{{ yield }}" } - template(:a_page) { "

Contents.

\n" } - get('/') do - liquid :main_outer_layout, :layout => false do - liquid :an_inner_layout do - liquid :a_page - end - end - end - end - get '/' - assert ok? - assert_body "

Title

\n

Subtitle

\n

Contents.

\n" - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping liquid tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/mapped_error_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/mapped_error_test.rb deleted file mode 100644 index 001ccf3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/mapped_error_test.rb +++ /dev/null @@ -1,285 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class FooError < RuntimeError -end - -class FooNotFound < Sinatra::NotFound -end - -class FooSpecialError < RuntimeError - def http_status; 501 end -end - -class FooStatusOutOfRangeError < RuntimeError - def code; 4000 end -end - -class FooWithCode < RuntimeError - def code; 419 end -end - -class FirstError < RuntimeError; end -class SecondError < RuntimeError; end - -class MappedErrorTest < Test::Unit::TestCase - def test_default - assert true - end - - describe 'Exception Mappings' do - it 'invokes handlers registered with ::error when raised' do - mock_app do - set :raise_errors, false - error(FooError) { 'Foo!' } - get('/') { raise FooError } - end - get '/' - assert_equal 500, status - assert_equal 'Foo!', body - end - - it 'passes the exception object to the error handler' do - mock_app do - set :raise_errors, false - error(FooError) { |e| assert_equal(FooError, e.class) } - get('/') { raise FooError } - end - get('/') - end - - it 'uses the Exception handler if no matching handler found' do - mock_app do - set :raise_errors, false - error(Exception) { 'Exception!' } - get('/') { raise FooError } - end - - get '/' - assert_equal 500, status - assert_equal 'Exception!', body - end - - it 'walks down inheritance chain for errors' do - mock_app do - set :raise_errors, false - error(RuntimeError) { 'Exception!' } - get('/') { raise FooError } - end - - get '/' - assert_equal 500, status - assert_equal 'Exception!', body - end - - it 'favors subclass handler over superclass handler if available' do - mock_app do - set :raise_errors, false - error(Exception) { 'Exception!' } - error(FooError) { 'FooError!' } - error(RuntimeError) { 'Exception!' } - get('/') { raise FooError } - end - - get '/' - assert_equal 500, status - assert_equal 'FooError!', body - end - - it "sets env['sinatra.error'] to the rescued exception" do - mock_app do - set :raise_errors, false - error(FooError) do - assert env.include?('sinatra.error') - assert env['sinatra.error'].kind_of?(FooError) - 'looks good' - end - get('/') { raise FooError } - end - get '/' - assert_equal 'looks good', body - end - - it "raises errors from the app when raise_errors set and no handler defined" do - mock_app do - set :raise_errors, true - get('/') { raise FooError } - end - assert_raise(FooError) { get '/' } - end - - it "calls error handlers before raising errors even when raise_errors is set" do - mock_app do - set :raise_errors, true - error(FooError) { "she's there." } - get('/') { raise FooError } - end - assert_nothing_raised { get '/' } - assert_equal 500, status - end - - it "never raises Sinatra::NotFound beyond the application" do - mock_app(Sinatra::Application) do - get('/') { raise Sinatra::NotFound } - end - assert_nothing_raised { get '/' } - assert_equal 404, status - end - - it "cascades for subclasses of Sinatra::NotFound" do - mock_app do - set :raise_errors, true - error(FooNotFound) { "foo! not found." } - get('/') { raise FooNotFound } - end - assert_nothing_raised { get '/' } - assert_equal 404, status - assert_equal 'foo! not found.', body - end - - it 'has a not_found method for backwards compatibility' do - mock_app { not_found { "Lost, are we?" } } - - get '/test' - assert_equal 404, status - assert_equal "Lost, are we?", body - end - - it 'inherits error mappings from base class' do - base = Class.new(Sinatra::Base) - base.error(FooError) { 'base class' } - - mock_app(base) do - set :raise_errors, false - get('/') { raise FooError } - end - - get '/' - assert_equal 'base class', body - end - - it 'overrides error mappings in base class' do - base = Class.new(Sinatra::Base) - base.error(FooError) { 'base class' } - - mock_app(base) do - set :raise_errors, false - error(FooError) { 'subclass' } - get('/') { raise FooError } - end - - get '/' - assert_equal 'subclass', body - end - - it 'honors Exception#http_status if present' do - mock_app do - set :raise_errors, false - error(501) { 'Foo!' } - get('/') { raise FooSpecialError } - end - get '/' - assert_equal 501, status - assert_equal 'Foo!', body - end - - it 'does not use Exception#code by default' do - mock_app do - set :raise_errors, false - get('/') { raise FooWithCode } - end - get '/' - assert_equal 500, status - end - - it 'uses Exception#code if use_code is enabled' do - mock_app do - set :raise_errors, false - set :use_code, true - get('/') { raise FooWithCode } - end - get '/' - assert_equal 419, status - end - - it 'does not rely on Exception#code for invalid codes' do - mock_app do - set :raise_errors, false - set :use_code, true - get('/') { raise FooStatusOutOfRangeError } - end - get '/' - assert_equal 500, status - end - - it "allows a stack of exception_handlers" do - mock_app do - set :raise_errors, false - error(FirstError) { 'First!' } - error(SecondError) { 'Second!' } - get('/'){ raise SecondError } - end - get '/' - assert_equal 500, status - assert_equal 'Second!', body - end - - it "allows an exception handler to pass control to the next exception handler" do - mock_app do - set :raise_errors, false - error(500, FirstError) { 'First!' } - error(500, SecondError) { pass } - get('/') { raise 500 } - end - get '/' - assert_equal 500, status - assert_equal 'First!', body - end - - it "allows an exception handler to handle the exception" do - mock_app do - set :raise_errors, false - error(500, FirstError) { 'First!' } - error(500, SecondError) { 'Second!' } - get('/') { raise 500 } - end - get '/' - assert_equal 500, status - assert_equal 'Second!', body - end - end - - describe 'Custom Error Pages' do - it 'allows numeric status code mappings to be registered with ::error' do - mock_app do - set :raise_errors, false - error(500) { 'Foo!' } - get('/') { [500, {}, 'Internal Foo Error'] } - end - get '/' - assert_equal 500, status - assert_equal 'Foo!', body - end - - it 'allows ranges of status code mappings to be registered with :error' do - mock_app do - set :raise_errors, false - error(500..550) { "Error: #{response.status}" } - get('/') { [507, {}, 'A very special error'] } - end - get '/' - assert_equal 507, status - assert_equal 'Error: 507', body - end - - it 'allows passing more than one range' do - mock_app do - set :raise_errors, false - error(409..411, 503..509) { "Error: #{response.status}" } - get('/') { [507, {}, 'A very special error'] } - end - get '/' - assert_equal 507, status - assert_equal 'Error: 507', body - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/markaby_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/markaby_test.rb deleted file mode 100644 index 946f684..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/markaby_test.rb +++ /dev/null @@ -1,80 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'markaby' - -class MarkabyTest < Test::Unit::TestCase - def markaby_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline markaby strings' do - markaby_app { markaby 'h1 "Hiya"' } - assert ok? - assert_equal "

Hiya

", body - end - - it 'renders .markaby files in views path' do - markaby_app { markaby :hello } - assert ok? - assert_equal "

Hello From Markaby

", body - end - - it "renders with inline layouts" do - mock_app do - layout { 'h1 { text "THIS. IS. "; yield }' } - get('/') { markaby 'em "SPARTA"' } - end - get '/' - assert ok? - assert_equal "

THIS. IS. SPARTA

", body - end - - it "renders with file layouts" do - markaby_app { markaby 'text "Hello World"', :layout => :layout2 } - assert ok? - assert_equal "

Markaby Layout!

Hello World

", body - end - - it 'renders inline markaby blocks' do - markaby_app { markaby { h1 'Hiya' } } - assert ok? - assert_equal "

Hiya

", body - end - - it 'renders inline markaby blocks with inline layouts' do - markaby_app do - settings.layout { 'h1 { text "THIS. IS. "; yield }' } - markaby { em 'SPARTA' } - end - assert ok? - assert_equal "

THIS. IS. SPARTA

", body - end - - it 'renders inline markaby blocks with file layouts' do - markaby_app { markaby(:layout => :layout2) { text "Hello World" } } - assert ok? - assert_equal "

Markaby Layout!

Hello World

", body - end - - it "raises error if template not found" do - mock_app { get('/') { markaby :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "allows passing locals" do - markaby_app { - markaby 'text value', :locals => { :value => 'foo' } - } - assert ok? - assert_equal 'foo', body - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping markaby tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/markdown_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/markdown_test.rb deleted file mode 100644 index d74bc70..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/markdown_test.rb +++ /dev/null @@ -1,82 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -MarkdownTest = proc do - def markdown_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - def setup - Tilt.prefer engine, 'markdown', 'mkd', 'md' - super - end - - it 'uses the correct engine' do - assert_equal engine, Tilt[:md] - assert_equal engine, Tilt[:mkd] - assert_equal engine, Tilt[:markdown] - end - - it 'renders inline markdown strings' do - markdown_app { markdown '# Hiya' } - assert ok? - assert_like "

Hiya

\n", body - end - - it 'renders .markdown files in views path' do - markdown_app { markdown :hello } - assert ok? - assert_like "

Hello From Markdown

", body - end - - it "raises error if template not found" do - mock_app { get('/') { markdown :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "renders with inline layouts" do - mock_app do - layout { 'THIS. IS. #{yield.upcase}!' } - get('/') { markdown 'Sparta', :layout_engine => :str } - end - get '/' - assert ok? - assert_like 'THIS. IS.

SPARTA

!', body - end - - it "renders with file layouts" do - markdown_app { - markdown 'Hello World', :layout => :layout2, :layout_engine => :erb - } - assert ok? - assert_body "ERB Layout!\n

Hello World

" - end - - it "can be used in a nested fashion for partials and whatnot" do - mock_app do - template(:inner) { "hi" } - template(:outer) { "<%= markdown :inner %>" } - get('/') { erb :outer } - end - - get '/' - assert ok? - assert_like '

hi

', body - end -end - -# Will generate RDiscountTest, KramdownTest, etc. -Tilt.mappings['md'].each do |t| - begin - t.new { "" } - klass = Class.new(Test::Unit::TestCase) { define_method(:engine) { t }} - klass.class_eval(&MarkdownTest) - name = t.name[/[^:]+$/].sub(/Template$/, '') << "Test" - Object.const_set name, klass - rescue LoadError, NameError - warn "#{$!}: skipping markdown tests with #{t}" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/mediawiki_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/mediawiki_test.rb deleted file mode 100644 index 051f389..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/mediawiki_test.rb +++ /dev/null @@ -1,68 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin - require 'wikicloth' - - class MediaWikiTest < Test::Unit::TestCase - def mediawiki_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'supports both .mw and .mediawiki extensions' do - assert_equal Tilt[:mw], Tilt[:mediawiki] - end - - it 'renders inline mediawiki strings' do - mediawiki_app { mediawiki "''Hiya''" } - assert ok? - assert_include body, 'Hiya' - end - - it 'renders .mediawiki files in views path' do - mediawiki_app { mediawiki :hello } - assert ok? - assert_include body, "Hello from MediaWiki" - end - - it 'raises error if template not found' do - mock_app { get('/') { mediawiki :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it 'renders with inline layouts' do - mock_app do - layout { 'THIS. IS. #{yield.upcase}!' } - get('/') { mediawiki 'Sparta', :layout_engine => :str } - end - get '/' - assert ok? - assert_like 'THIS. IS.

SPARTA

!', body - end - - it 'renders with file layouts' do - mediawiki_app do - mediawiki 'Hello World', :layout => :layout2, :layout_engine => :erb - end - assert ok? - assert_body "ERB Layout!\n

Hello World

" - end - - it 'can be used in a nested fashion for partials and whatnot' do - mock_app do - template(:inner) { "hi" } - template(:outer) { "<%= mediawiki :inner %>" } - get('/') { erb :outer } - end - - get '/' - assert ok? - assert_like '

hi

', body - end - end -rescue LoadError - warn "#{$!.to_s}: skipping mediawiki tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/middleware_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/middleware_test.rb deleted file mode 100644 index ef06625..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/middleware_test.rb +++ /dev/null @@ -1,68 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class MiddlewareTest < Test::Unit::TestCase - setup do - @app = mock_app(Sinatra::Application) do - get('/*')do - response.headers['X-Tests'] = env['test.ran']. - map { |n| n.split('::').last }. - join(', ') - env['PATH_INFO'] - end - end - end - - class MockMiddleware < Struct.new(:app) - def call(env) - (env['test.ran'] ||= []) << self.class.to_s - app.call(env) - end - end - - class UpcaseMiddleware < MockMiddleware - def call(env) - env['PATH_INFO'] = env['PATH_INFO'].upcase - super - end - end - - it "is added with Sinatra::Application.use" do - @app.use UpcaseMiddleware - get '/hello-world' - assert ok? - assert_equal '/HELLO-WORLD', body - end - - class DowncaseMiddleware < MockMiddleware - def call(env) - env['PATH_INFO'] = env['PATH_INFO'].downcase - super - end - end - - it "runs in the order defined" do - @app.use UpcaseMiddleware - @app.use DowncaseMiddleware - get '/Foo' - assert_equal "/foo", body - assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests'] - end - - it "resets the prebuilt pipeline when new middleware is added" do - @app.use UpcaseMiddleware - get '/Foo' - assert_equal "/FOO", body - @app.use DowncaseMiddleware - get '/Foo' - assert_equal '/foo', body - assert_equal "UpcaseMiddleware, DowncaseMiddleware", response['X-Tests'] - end - - it "works when app is used as middleware" do - @app.use UpcaseMiddleware - @app = @app.new - get '/Foo' - assert_equal "/FOO", body - assert_equal "UpcaseMiddleware", response['X-Tests'] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/nokogiri_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/nokogiri_test.rb deleted file mode 100644 index 033c45c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/nokogiri_test.rb +++ /dev/null @@ -1,67 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'nokogiri' - -class NokogiriTest < Test::Unit::TestCase - def nokogiri_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline Nokogiri strings' do - nokogiri_app { nokogiri 'xml' } - assert ok? - assert_body %(\n) - end - - it 'renders inline blocks' do - nokogiri_app do - @name = "Frank & Mary" - nokogiri { |xml| xml.couple @name } - end - assert ok? - assert_body %(\nFrank & Mary\n) - end - - it 'renders .nokogiri files in views path' do - nokogiri_app do - @name = "Blue" - nokogiri :hello - end - assert ok? - assert_body "\nYou're my boy, Blue!\n" - end - - it "renders with inline layouts" do - next if Tilt::VERSION <= "1.1" - mock_app do - layout { %(xml.layout { xml << yield }) } - get('/') { nokogiri %(xml.em 'Hello World') } - end - get '/' - assert ok? - assert_body %(\n\n Hello World\n\n) - end - - it "renders with file layouts" do - next if Tilt::VERSION <= "1.1" - nokogiri_app { - nokogiri %(xml.em 'Hello World'), :layout => :layout2 - } - assert ok? - assert_body %(\n\n Hello World\n\n) - end - - it "raises error if template not found" do - mock_app { get('/') { nokogiri :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping nokogiri tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/public/favicon.ico b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/public/favicon.ico deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rabl_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rabl_test.rb deleted file mode 100644 index 98d087d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rabl_test.rb +++ /dev/null @@ -1,89 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'rabl' -require 'ostruct' -require 'json' -require 'active_support/core_ext/hash/conversions' - -class RablTest < Test::Unit::TestCase - def rabl_app(&block) - mock_app { - set :views, File.dirname(__FILE__) + '/views' - get '/', &block - } - get '/' - end - - it 'renders inline rabl strings' do - rabl_app do - @foo = OpenStruct.new(:baz => 'w00t') - rabl %q{ - object @foo - attributes :baz - } - end - assert ok? - assert_equal '{"openstruct":{"baz":"w00t"}}', body - end - it 'renders .rabl files in views path' do - rabl_app do - @foo = OpenStruct.new(:bar => 'baz') - rabl :hello - end - assert ok? - assert_equal '{"openstruct":{"bar":"baz"}}', body - end - - it "renders with file layouts" do - rabl_app { - @foo = OpenStruct.new(:bar => 'baz') - rabl :hello, :layout => :layout2 - } - assert ok? - assert_equal '{"qux":{"openstruct":{"bar":"baz"}}}', body - end - - it "raises error if template not found" do - mock_app { - get('/') { rabl :no_such_template } - } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "passes rabl options to the rabl engine" do - mock_app do - get('/') do - @foo = OpenStruct.new(:bar => 'baz') - rabl %q{ - object @foo - attributes :bar - }, :format => 'xml' - end - end - get '/' - assert ok? - assert_body 'baz' - end - - it "passes default rabl options to the rabl engine" do - mock_app do - set :rabl, :format => 'xml' - get('/') do - @foo = OpenStruct.new(:bar => 'baz') - rabl %q{ - object @foo - attributes :bar - } - end - end - get '/' - assert ok? - assert_body 'baz' - end - -end - -rescue LoadError - warn "#{$!.to_s}: skipping rabl tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rack_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rack_test.rb deleted file mode 100644 index 84734ea..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rack_test.rb +++ /dev/null @@ -1,45 +0,0 @@ -require File.expand_path('../helper', __FILE__) -require 'rack' - -class RackTest < Test::Unit::TestCase - setup do - @foo = Sinatra.new { get('/foo') { 'foo' }} - @bar = Sinatra.new { get('/bar') { 'bar' }} - end - - def build(*middleware) - endpoint = middleware.pop - @app = Rack::Builder.app do - middleware.each { |m| use m } - run endpoint - end - end - - def check(*middleware) - build(*middleware) - assert get('/foo').ok? - assert_body 'foo' - assert get('/bar').ok? - assert_body 'bar' - end - - it 'works as middleware in front of Rack::Lock, with lock enabled' do - @foo.enable :lock - check(@foo, Rack::Lock, @bar) - end - - it 'works as middleware behind Rack::Lock, with lock enabled' do - @foo.enable :lock - check(Rack::Lock, @foo, @bar) - end - - it 'works as middleware in front of Rack::Lock, with lock disabled' do - @foo.disable :lock - check(@foo, Rack::Lock, @bar) - end - - it 'works as middleware behind Rack::Lock, with lock disabled' do - @foo.disable :lock - check(Rack::Lock, @foo, @bar) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/radius_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/radius_test.rb deleted file mode 100644 index 90f8712..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/radius_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'radius' - -class RadiusTest < Test::Unit::TestCase - def radius_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline radius strings' do - radius_app { radius '

Hiya

' } - assert ok? - assert_equal "

Hiya

", body - end - - it 'renders .radius files in views path' do - radius_app { radius :hello } - assert ok? - assert_equal "

Hello From Radius

\n", body - end - - it "renders with inline layouts" do - mock_app do - layout { "

THIS. IS.

" } - get('/') { radius 'SPARTA' } - end - get '/' - assert ok? - assert_equal "

THIS. IS. SPARTA

", body - end - - it "renders with file layouts" do - radius_app { radius 'Hello World', :layout => :layout2 } - assert ok? - assert_equal "

Radius Layout!

\n

Hello World

\n", body - end - - it "raises error if template not found" do - mock_app { get('/') { radius :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "allows passing locals" do - radius_app { - radius '', :locals => { :value => 'foo' } - } - assert ok? - assert_equal 'foo', body - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping radius tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rdoc_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rdoc_test.rb deleted file mode 100644 index a93299d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/rdoc_test.rb +++ /dev/null @@ -1,66 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'rdoc' -require 'rdoc/markup/to_html' - -class RdocTest < Test::Unit::TestCase - def rdoc_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline rdoc strings' do - rdoc_app { rdoc '= Hiya' } - assert ok? - assert_body(/]*>Hiya(¶<\/a> ↑<\/a><\/span>)?<\/h1>/) - end - - it 'renders .rdoc files in views path' do - rdoc_app { rdoc :hello } - assert ok? - assert_body(/]*>Hello From RDoc(¶<\/a> ↑<\/a><\/span>)?<\/h1>/) - end - - it "raises error if template not found" do - mock_app { get('/') { rdoc :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "renders with inline layouts" do - mock_app do - layout { 'THIS. IS. #{yield.upcase}!' } - get('/') { rdoc 'Sparta', :layout_engine => :str } - end - get '/' - assert ok? - assert_like 'THIS. IS.

SPARTA

!', body - end - - it "renders with file layouts" do - rdoc_app { - rdoc 'Hello World', :layout => :layout2, :layout_engine => :erb - } - assert ok? - assert_body "ERB Layout!\n

Hello World

" - end - - it "can be used in a nested fashion for partials and whatnot" do - mock_app do - template(:inner) { "hi" } - template(:outer) { "<%= rdoc :inner %>" } - get('/') { erb :outer } - end - - get '/' - assert ok? - assert_like '

hi

', body - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping rdoc tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/readme_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/readme_test.rb deleted file mode 100644 index 3964deb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/readme_test.rb +++ /dev/null @@ -1,130 +0,0 @@ -# Tests to check if all the README examples work. -require File.expand_path('../helper', __FILE__) - -class ReadmeTest < Test::Unit::TestCase - example do - mock_app { get('/') { 'Hello world!' } } - get '/' - assert_body 'Hello world!' - end - - section "Routes" do - example do - mock_app do - get('/') { ".. show something .." } - - post('/') { ".. create something .." } - - put('/') { ".. replace something .." } - - patch('/') { ".. modify something .." } - - delete('/') { ".. annihilate something .." } - - options('/') { ".. appease something .." } - - link('/') { ".. affiliate something .." } - - unlink('/') { ".. separate something .." } - end - - get '/' - assert_body '.. show something ..' - - post '/' - assert_body '.. create something ..' - - put '/' - assert_body '.. replace something ..' - - patch '/' - assert_body '.. modify something ..' - - delete '/' - assert_body '.. annihilate something ..' - - options '/' - assert_body '.. appease something ..' - - link '/' - assert_body '.. affiliate something ..' - - unlink '/' - assert_body '.. separate something ..' - end - - example do - mock_app do - get('/hello/:name') do - # matches "GET /hello/foo" and "GET /hello/bar" - # params[:name] is 'foo' or 'bar' - "Hello #{params[:name]}!" - end - end - - get '/hello/foo' - assert_body 'Hello foo!' - - get '/hello/bar' - assert_body 'Hello bar!' - end - - example do - mock_app { get('/hello/:name') { |n| "Hello #{n}!" } } - - get '/hello/foo' - assert_body 'Hello foo!' - - get '/hello/bar' - assert_body 'Hello bar!' - end - - example do - mock_app do - get('/say/*/to/*') do - # matches /say/hello/to/world - params[:splat].inspect # => ["hello", "world"] - end - - get('/download/*.*') do - # matches /download/path/to/file.xml - params[:splat].inspect # => ["path/to/file", "xml"] - end - end - - get "/say/hello/to/world" - assert_body '["hello", "world"]' - - get "/download/path/to/file.xml" - assert_body '["path/to/file", "xml"]' - end - - example do - mock_app do - get(%r{/hello/([\w]+)}) { - "Hello, #{params[:captures].first}!" - } - end - - get '/hello/foo' - assert_body 'Hello, foo!' - - get '/hello/bar' - assert_body 'Hello, bar!' - end - - example do - mock_app do - get( %r{/hello/([\w]+)}) { |c| - "Hello, #{c}!" - } - end - - get '/hello/foo' - assert_body 'Hello, foo!' - - get '/hello/bar' - assert_body 'Hello, bar!' - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/request_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/request_test.rb deleted file mode 100644 index f0d923b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/request_test.rb +++ /dev/null @@ -1,97 +0,0 @@ -require File.expand_path('../helper', __FILE__) -require 'stringio' - -class RequestTest < Test::Unit::TestCase - it 'responds to #user_agent' do - request = Sinatra::Request.new({'HTTP_USER_AGENT' => 'Test'}) - assert request.respond_to?(:user_agent) - assert_equal 'Test', request.user_agent - end - - it 'parses POST params when Content-Type is form-dataish' do - request = Sinatra::Request.new( - 'REQUEST_METHOD' => 'PUT', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'rack.input' => StringIO.new('foo=bar') - ) - assert_equal 'bar', request.params['foo'] - end - - it 'is secure when the url scheme is https' do - request = Sinatra::Request.new('rack.url_scheme' => 'https') - assert request.secure? - end - - it 'is not secure when the url scheme is http' do - request = Sinatra::Request.new('rack.url_scheme' => 'http') - assert !request.secure? - end - - it 'respects X-Forwarded-Proto header for proxied SSL' do - request = Sinatra::Request.new('HTTP_X_FORWARDED_PROTO' => 'https') - assert request.secure? - end - - it 'is possible to marshal params' do - request = Sinatra::Request.new( - 'REQUEST_METHOD' => 'PUT', - 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', - 'rack.input' => StringIO.new('foo=bar') - ) - Sinatra::Base.new!.send(:indifferent_hash).replace(request.params) - dumped = Marshal.dump(request.params) - assert_equal 'bar', Marshal.load(dumped)['foo'] - end - - it "exposes the preferred type's parameters" do - request = Sinatra::Request.new( - 'HTTP_ACCEPT' => 'image/jpeg; compress=0.25' - ) - assert_equal({ 'compress' => '0.25' }, request.preferred_type.params) - end - - it "makes accept types behave like strings" do - request = Sinatra::Request.new('HTTP_ACCEPT' => 'image/jpeg; compress=0.25') - assert request.accept?('image/jpeg') - assert_equal 'image/jpeg', request.preferred_type.to_s - assert_equal 'image/jpeg', request.preferred_type.to_str - assert_equal 'image', request.preferred_type.split('/').first - - String.instance_methods.each do |method| - next unless "".respond_to? method - assert request.preferred_type.respond_to?(method), "responds to #{method}" - end - end - - it "accepts types when wildcards are requested" do - request = Sinatra::Request.new('HTTP_ACCEPT' => 'image/*') - assert request.accept?('image/jpeg') - end - - it "properly decodes MIME type parameters" do - request = Sinatra::Request.new( - 'HTTP_ACCEPT' => 'image/jpeg;unquoted=0.25;quoted="0.25";chartest="\";,\x"' - ) - expected = { 'unquoted' => '0.25', 'quoted' => '0.25', 'chartest' => '";,x' } - assert_equal(expected, request.preferred_type.params) - end - - it 'accepts */* when HTTP_ACCEPT is not present in the request' do - request = Sinatra::Request.new Hash.new - assert_equal 1, request.accept.size - assert request.accept?('text/html') - assert_equal '*/*', request.preferred_type.to_s - end - - it 'accepts */* when HTTP_ACCEPT is blank in the request' do - request = Sinatra::Request.new 'HTTP_ACCEPT' => '' - assert_equal 1, request.accept.size - assert request.accept?('text/html') - assert_equal '*/*', request.preferred_type.to_s - end - - it 'will not accept types not specified in HTTP_ACCEPT when HTTP_ACCEPT is provided' do - request = Sinatra::Request.new 'HTTP_ACCEPT' => 'application/json' - assert !request.accept?('text/html') - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/response_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/response_test.rb deleted file mode 100644 index f9feb02..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/response_test.rb +++ /dev/null @@ -1,63 +0,0 @@ -# encoding: utf-8 - -require File.expand_path('../helper', __FILE__) - -class ResponseTest < Test::Unit::TestCase - setup { @response = Sinatra::Response.new } - - def assert_same_body(a, b) - assert_equal a.to_enum(:each).to_a, b.to_enum(:each).to_a - end - - it "initializes with 200, text/html, and empty body" do - assert_equal 200, @response.status - assert_equal 'text/html', @response['Content-Type'] - assert_equal [], @response.body - end - - it 'uses case insensitive headers' do - @response['content-type'] = 'application/foo' - assert_equal 'application/foo', @response['Content-Type'] - assert_equal 'application/foo', @response['CONTENT-TYPE'] - end - - it 'writes to body' do - @response.body = 'Hello' - @response.write ' World' - assert_equal 'Hello World', @response.body.join - end - - [204, 304].each do |status_code| - it "removes the Content-Type header and body when response status is #{status_code}" do - @response.status = status_code - @response.body = ['Hello World'] - assert_equal [status_code, {}, []], @response.finish - end - end - - it 'Calculates the Content-Length using the bytesize of the body' do - @response.body = ['Hello', 'World!', '✈'] - _, headers, body = @response.finish - assert_equal '14', headers['Content-Length'] - assert_same_body @response.body, body - end - - it 'does not call #to_ary or #inject on the body' do - object = Object.new - def object.inject(*) fail 'called' end - def object.to_ary(*) fail 'called' end - def object.each(*) end - @response.body = object - assert @response.finish - end - - it 'does not nest a Sinatra::Response' do - @response.body = Sinatra::Response.new ["foo"] - assert_same_body @response.body, ["foo"] - end - - it 'does not nest a Rack::Response' do - @response.body = Rack::Response.new ["foo"] - assert_same_body @response.body, ["foo"] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/result_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/result_test.rb deleted file mode 100644 index 6c59f6b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/result_test.rb +++ /dev/null @@ -1,76 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class ResultTest < Test::Unit::TestCase - it "sets response.body when result is a String" do - mock_app { get('/') { 'Hello World' } } - - get '/' - assert ok? - assert_equal 'Hello World', body - end - - it "sets response.body when result is an Array of Strings" do - mock_app { get('/') { ['Hello', 'World'] } } - - get '/' - assert ok? - assert_equal 'HelloWorld', body - end - - it "sets response.body when result responds to #each" do - mock_app do - get('/') do - res = lambda { 'Hello World' } - def res.each ; yield call ; end - return res - end - end - - get '/' - assert ok? - assert_equal 'Hello World', body - end - - it "sets response.body to [] when result is nil" do - mock_app { get( '/') { nil } } - - get '/' - assert ok? - assert_equal '', body - end - - it "sets status, headers, and body when result is a Rack response tuple" do - mock_app { - get('/') { [203, {'Content-Type' => 'foo/bar'}, 'Hello World'] } - } - - get '/' - assert_equal 203, status - assert_equal 'foo/bar', response['Content-Type'] - assert_equal 'Hello World', body - end - - it "sets status and body when result is a two-tuple" do - mock_app { get('/') { [409, 'formula of'] } } - - get '/' - assert_equal 409, status - assert_equal 'formula of', body - end - - it "raises a ArgumentError when result is a non two or three tuple Array" do - mock_app { - get('/') { [409, 'formula of', 'something else', 'even more'] } - } - - assert_raise(ArgumentError) { get '/' } - end - - it "sets status when result is a Fixnum status code" do - mock_app { get('/') { 205 } } - - get '/' - assert_equal 205, status - assert_equal '', body - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/route_added_hook_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/route_added_hook_test.rb deleted file mode 100644 index d6ef341..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/route_added_hook_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -module RouteAddedTest - @routes, @procs = [], [] - def self.routes ; @routes ; end - def self.procs ; @procs ; end - def self.route_added(verb, path, proc) - @routes << [verb, path] - @procs << proc - end -end - -class RouteAddedHookTest < Test::Unit::TestCase - setup do - RouteAddedTest.routes.clear - RouteAddedTest.procs.clear - end - - it "should be notified of an added route" do - mock_app(Class.new(Sinatra::Base)) do - register RouteAddedTest - get('/') {} - end - - assert_equal [["GET", "/"], ["HEAD", "/"]], - RouteAddedTest.routes - end - - it "should include hooks from superclass" do - a = Class.new(Class.new(Sinatra::Base)) - b = Class.new(a) - - a.register RouteAddedTest - b.class_eval { post("/sub_app_route") {} } - - assert_equal [["POST", "/sub_app_route"]], - RouteAddedTest.routes - end - - it "should only run once per extension" do - mock_app(Class.new(Sinatra::Base)) do - register RouteAddedTest - register RouteAddedTest - get('/') {} - end - - assert_equal [["GET", "/"], ["HEAD", "/"]], - RouteAddedTest.routes - end - - it "should pass route blocks as an argument" do - mock_app(Class.new(Sinatra::Base)) do - register RouteAddedTest - get('/') {} - end - - assert_kind_of Proc, RouteAddedTest.procs.first - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/routing_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/routing_test.rb deleted file mode 100644 index 5584601..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/routing_test.rb +++ /dev/null @@ -1,1412 +0,0 @@ -# I like coding: UTF-8 -require File.expand_path('../helper', __FILE__) - -# Helper method for easy route pattern matching testing -def route_def(pattern) - mock_app { get(pattern) { } } -end - -class RegexpLookAlike - class MatchData - def captures - ["this", "is", "a", "test"] - end - end - - def match(string) - ::RegexpLookAlike::MatchData.new if string == "/this/is/a/test/" - end - - def keys - ["one", "two", "three", "four"] - end -end - -class RoutingTest < Test::Unit::TestCase - %w[get put post delete options patch link unlink].each do |verb| - it "defines #{verb.upcase} request handlers with #{verb}" do - mock_app { - send verb, '/hello' do - 'Hello World' - end - } - - request = Rack::MockRequest.new(@app) - response = request.request(verb.upcase, '/hello', {}) - assert response.ok? - assert_equal 'Hello World', response.body - end - end - - it "defines HEAD request handlers with HEAD" do - mock_app { - head '/hello' do - response['X-Hello'] = 'World!' - 'remove me' - end - } - - request = Rack::MockRequest.new(@app) - response = request.request('HEAD', '/hello', {}) - assert response.ok? - assert_equal 'World!', response['X-Hello'] - assert_equal '', response.body - end - - it "404s when no route satisfies the request" do - mock_app { - get('/foo') { } - } - get '/bar' - assert_equal 404, status - end - - it "404s and sets X-Cascade header when no route satisfies the request" do - mock_app { - get('/foo') { } - } - get '/bar' - assert_equal 404, status - assert_equal 'pass', response.headers['X-Cascade'] - end - - it "404s and does not set X-Cascade header when no route satisfies the request and x_cascade has been disabled" do - mock_app { - disable :x_cascade - get('/foo') { } - } - get '/bar' - assert_equal 404, status - assert_equal nil, response.headers['X-Cascade'] - end - - - it "allows using unicode" do - mock_app do - get('/föö') { } - end - get '/f%C3%B6%C3%B6' - assert_equal 200, status - end - - it "it handles encoded slashes correctly" do - mock_app { - set :protection, :except => :path_traversal - get("/:a") { |a| a } - } - get '/foo%2Fbar' - assert_equal 200, status - assert_body "foo/bar" - end - - it "overrides the content-type in error handlers" do - mock_app { - before { content_type 'text/plain' } - error Sinatra::NotFound do - content_type "text/html" - "

Not Found

" - end - } - - get '/foo' - assert_equal 404, status - assert_equal 'text/html;charset=utf-8', response["Content-Type"] - assert_equal "

Not Found

", response.body - end - - it "recalculates body length correctly for 404 response" do - mock_app { - get '/' do - @response["Content-Length"] = "30" - raise Sinatra::NotFound - end - } - - get "/" - assert_equal "18", response["Content-Length"] - assert_equal 404, status - end - - it 'matches empty PATH_INFO to "/" if no route is defined for ""' do - mock_app do - get '/' do - 'worked' - end - end - - get '/', {}, "PATH_INFO" => "" - assert ok? - assert_equal 'worked', body - end - - it 'matches empty PATH_INFO to "" if a route is defined for ""' do - mock_app do - disable :protection - - get '/' do - 'did not work' - end - - get '' do - 'worked' - end - end - - get '/', {}, "PATH_INFO" => "" - assert ok? - assert_equal 'worked', body - end - - it 'takes multiple definitions of a route' do - mock_app { - user_agent(/Foo/) - get '/foo' do - 'foo' - end - - get '/foo' do - 'not foo' - end - } - - get '/foo', {}, 'HTTP_USER_AGENT' => 'Foo' - assert ok? - assert_equal 'foo', body - - get '/foo' - assert ok? - assert_equal 'not foo', body - end - - it "exposes params with indifferent hash" do - mock_app { - get '/:foo' do - assert_equal 'bar', params['foo'] - assert_equal 'bar', params[:foo] - 'well, alright' - end - } - get '/bar' - assert_equal 'well, alright', body - end - - it "merges named params and query string params in params" do - mock_app { - get '/:foo' do - assert_equal 'bar', params['foo'] - assert_equal 'biz', params['baz'] - end - } - get '/bar?baz=biz' - assert ok? - end - - it "supports named params like /hello/:person" do - mock_app { - get '/hello/:person' do - "Hello #{params['person']}" - end - } - get '/hello/Frank' - assert_equal 'Hello Frank', body - end - - it "supports optional named params like /?:foo?/?:bar?" do - mock_app { - get '/?:foo?/?:bar?' do - "foo=#{params[:foo]};bar=#{params[:bar]}" - end - } - - get '/hello/world' - assert ok? - assert_equal "foo=hello;bar=world", body - - get '/hello' - assert ok? - assert_equal "foo=hello;bar=", body - - get '/' - assert ok? - assert_equal "foo=;bar=", body - end - - it "supports named captures like %r{/hello/(?[^/?#]+)} on Ruby >= 1.9" do - next if RUBY_VERSION < '1.9' - mock_app { - get Regexp.new('/hello/(?[^/?#]+)') do - "Hello #{params['person']}" - end - } - get '/hello/Frank' - assert_equal 'Hello Frank', body - end - - it "supports optional named captures like %r{/page(?.[^/?#]+)?} on Ruby >= 1.9" do - next if RUBY_VERSION < '1.9' - mock_app { - get Regexp.new('/page(?.[^/?#]+)?') do - "format=#{params[:format]}" - end - } - - get '/page.html' - assert ok? - assert_equal "format=.html", body - - get '/page.xml' - assert ok? - assert_equal "format=.xml", body - - get '/page' - assert ok? - assert_equal "format=", body - end - - it 'does not concatinate params with the same name' do - mock_app { get('/:foo') { params[:foo] } } - get '/a?foo=b' - assert_body 'a' - end - - it "supports single splat params like /*" do - mock_app { - get '/*' do - assert params['splat'].kind_of?(Array) - params['splat'].join "\n" - end - } - - get '/foo' - assert_equal "foo", body - - get '/foo/bar/baz' - assert_equal "foo/bar/baz", body - end - - it "supports mixing multiple splat params like /*/foo/*/*" do - mock_app { - get '/*/foo/*/*' do - assert params['splat'].kind_of?(Array) - params['splat'].join "\n" - end - } - - get '/bar/foo/bling/baz/boom' - assert_equal "bar\nbling\nbaz/boom", body - - get '/bar/foo/baz' - assert not_found? - end - - it "supports mixing named and splat params like /:foo/*" do - mock_app { - get '/:foo/*' do - assert_equal 'foo', params['foo'] - assert_equal ['bar/baz'], params['splat'] - end - } - - get '/foo/bar/baz' - assert ok? - end - - it "matches a dot ('.') as part of a named param" do - mock_app { - get '/:foo/:bar' do - params[:foo] - end - } - - get '/user@example.com/name' - assert_equal 200, response.status - assert_equal 'user@example.com', body - end - - it "matches a literal dot ('.') outside of named params" do - mock_app { - get '/:file.:ext' do - assert_equal 'pony', params[:file] - assert_equal 'jpg', params[:ext] - 'right on' - end - } - - get '/pony.jpg' - assert_equal 200, response.status - assert_equal 'right on', body - end - - it "literally matches dot in paths" do - route_def '/test.bar' - - get '/test.bar' - assert ok? - get 'test0bar' - assert not_found? - end - - it "literally matches dollar sign in paths" do - route_def '/test$/' - - get '/test$/' - assert ok? - end - - it "literally matches plus sign in paths" do - route_def '/te+st/' - - get '/te%2Bst/' - assert ok? - get '/teeeeeeest/' - assert not_found? - end - - it "does not convert plus sign into space as the value of a named param" do - mock_app do - get '/:test' do - params["test"] - end - end - get '/bob+ross' - assert ok? - assert_equal 'bob+ross', body - end - - it "literally matches parens in paths" do - route_def '/test(bar)/' - - get '/test(bar)/' - assert ok? - end - - it "supports basic nested params" do - mock_app { - get '/hi' do - params["person"]["name"] - end - } - - get "/hi?person[name]=John+Doe" - assert ok? - assert_equal "John Doe", body - end - - it "exposes nested params with indifferent hash" do - mock_app { - get '/testme' do - assert_equal 'baz', params['bar']['foo'] - assert_equal 'baz', params['bar'][:foo] - 'well, alright' - end - } - get '/testme?bar[foo]=baz' - assert_equal 'well, alright', body - end - - it "exposes params nested within arrays with indifferent hash" do - mock_app { - get '/testme' do - assert_equal 'baz', params['bar'][0]['foo'] - assert_equal 'baz', params['bar'][0][:foo] - 'well, alright' - end - } - get '/testme?bar[][foo]=baz' - assert_equal 'well, alright', body - end - - it "supports arrays within params" do - mock_app { - get '/foo' do - assert_equal ['A', 'B'], params['bar'] - 'looks good' - end - } - get '/foo?bar[]=A&bar[]=B' - assert ok? - assert_equal 'looks good', body - end - - it "supports deeply nested params" do - expected_params = { - "emacs" => { - "map" => { "goto-line" => "M-g g" }, - "version" => "22.3.1" - }, - "browser" => { - "firefox" => {"engine" => {"name"=>"spidermonkey", "version"=>"1.7.0"}}, - "chrome" => {"engine" => {"name"=>"V8", "version"=>"1.0"}} - }, - "paste" => {"name"=>"hello world", "syntax"=>"ruby"} - } - mock_app { - get '/foo' do - assert_equal expected_params, params - 'looks good' - end - } - get '/foo', expected_params - assert ok? - assert_equal 'looks good', body - end - - it "preserves non-nested params" do - mock_app { - get '/foo' do - assert_equal "2", params["article_id"] - assert_equal "awesome", params['comment']['body'] - assert_nil params['comment[body]'] - 'looks good' - end - } - - get '/foo?article_id=2&comment[body]=awesome' - assert ok? - assert_equal 'looks good', body - end - - it "matches paths that include spaces encoded with %20" do - mock_app { - get '/path with spaces' do - 'looks good' - end - } - - get '/path%20with%20spaces' - assert ok? - assert_equal 'looks good', body - end - - it "matches paths that include spaces encoded with +" do - mock_app { - get '/path with spaces' do - 'looks good' - end - } - - get '/path+with+spaces' - assert ok? - assert_equal 'looks good', body - end - - it "matches paths that include ampersands" do - mock_app { - get '/:name' do - 'looks good' - end - } - - get '/foo&bar' - assert ok? - assert_equal 'looks good', body - end - - it "URL decodes named parameters and splats" do - mock_app { - get '/:foo/*' do - assert_equal 'hello world', params['foo'] - assert_equal ['how are you'], params['splat'] - nil - end - } - - get '/hello%20world/how%20are%20you' - assert ok? - end - - it 'supports regular expressions' do - mock_app { - get(/^\/foo...\/bar$/) do - 'Hello World' - end - } - - get '/foooom/bar' - assert ok? - assert_equal 'Hello World', body - end - - it 'makes regular expression captures available in params[:captures]' do - mock_app { - get(/^\/fo(.*)\/ba(.*)/) do - assert_equal ['orooomma', 'f'], params[:captures] - 'right on' - end - } - - get '/foorooomma/baf' - assert ok? - assert_equal 'right on', body - end - - it 'supports regular expression look-alike routes' do - mock_app { - get(RegexpLookAlike.new) do - assert_equal 'this', params[:one] - assert_equal 'is', params[:two] - assert_equal 'a', params[:three] - assert_equal 'test', params[:four] - 'right on' - end - } - - get '/this/is/a/test/' - assert ok? - assert_equal 'right on', body - end - - it 'raises a TypeError when pattern is not a String or Regexp' do - assert_raise(TypeError) { - mock_app { get(42){} } - } - end - - it "returns response immediately on halt" do - mock_app { - get '/' do - halt 'Hello World' - 'Boo-hoo World' - end - } - - get '/' - assert ok? - assert_equal 'Hello World', body - end - - it "halts with a response tuple" do - mock_app { - get '/' do - halt 295, {'Content-Type' => 'text/plain'}, 'Hello World' - end - } - - get '/' - assert_equal 295, status - assert_equal 'text/plain', response['Content-Type'] - assert_equal 'Hello World', body - end - - it "halts with an array of strings" do - mock_app { - get '/' do - halt %w[Hello World How Are You] - end - } - - get '/' - assert_equal 'HelloWorldHowAreYou', body - end - - it 'sets response.status with halt' do - status_was = nil - mock_app do - after { status_was = status } - get('/') { halt 500, 'error' } - end - get '/' - assert_status 500 - assert_equal 500, status_was - end - - it "transitions to the next matching route on pass" do - mock_app { - get '/:foo' do - pass - 'Hello Foo' - end - - get '/*' do - assert !params.include?('foo') - 'Hello World' - end - } - - get '/bar' - assert ok? - assert_equal 'Hello World', body - end - - it "transitions to 404 when passed and no subsequent route matches" do - mock_app { - get '/:foo' do - pass - 'Hello Foo' - end - } - - get '/bar' - assert not_found? - end - - it "transitions to 404 and sets X-Cascade header when passed and no subsequent route matches" do - mock_app { - get '/:foo' do - pass - 'Hello Foo' - end - - get '/bar' do - 'Hello Bar' - end - } - - get '/foo' - assert not_found? - assert_equal 'pass', response.headers['X-Cascade'] - end - - it "uses optional block passed to pass as route block if no other route is found" do - mock_app { - get "/" do - pass do - "this" - end - "not this" - end - } - - get "/" - assert ok? - assert "this", body - end - - it "uses optional block passed to pass as route block if no other route is found and superclass has non-matching routes" do - base = Class.new(Sinatra::Base) - base.get('/foo') { 'foo in baseclass' } - - mock_app(base) { - get "/" do - pass do - "this" - end - "not this" - end - } - - get "/" - assert_equal 200, status - assert "this", body - end - - it "passes when matching condition returns false" do - mock_app { - condition { params[:foo] == 'bar' } - get '/:foo' do - 'Hello World' - end - } - - get '/bar' - assert ok? - assert_equal 'Hello World', body - - get '/foo' - assert not_found? - end - - it "does not pass when matching condition returns nil" do - mock_app { - condition { nil } - get '/:foo' do - 'Hello World' - end - } - - get '/bar' - assert ok? - assert_equal 'Hello World', body - end - - it "passes to next route when condition calls pass explicitly" do - mock_app { - condition { pass unless params[:foo] == 'bar' } - get '/:foo' do - 'Hello World' - end - } - - get '/bar' - assert ok? - assert_equal 'Hello World', body - - get '/foo' - assert not_found? - end - - it "passes to the next route when host_name does not match" do - mock_app { - host_name 'example.com' - get '/foo' do - 'Hello World' - end - } - get '/foo' - assert not_found? - - get '/foo', {}, { 'HTTP_HOST' => 'example.com' } - assert_equal 200, status - assert_equal 'Hello World', body - end - - it "passes to the next route when user_agent does not match" do - mock_app { - user_agent(/Foo/) - get '/foo' do - 'Hello World' - end - } - get '/foo' - assert not_found? - - get '/foo', {}, { 'HTTP_USER_AGENT' => 'Foo Bar' } - assert_equal 200, status - assert_equal 'Hello World', body - end - - it "treats missing user agent like an empty string" do - mock_app do - user_agent(/.*/) - get '/' do - "Hello World" - end - end - get '/' - assert_equal 200, status - assert_equal 'Hello World', body - end - - it "makes captures in user agent pattern available in params[:agent]" do - mock_app { - user_agent(/Foo (.*)/) - get '/foo' do - 'Hello ' + params[:agent].first - end - } - get '/foo', {}, { 'HTTP_USER_AGENT' => 'Foo Bar' } - assert_equal 200, status - assert_equal 'Hello Bar', body - end - - it 'matches mime_types with dots, hyphens and plus signs' do - mime_types = %w( - application/atom+xml - application/ecmascript - application/EDI-X12 - application/EDIFACT - application/json - application/javascript - application/octet-stream - application/ogg - application/pdf - application/postscript - application/rdf+xml - application/rss+xml - application/soap+xml - application/font-woff - application/xhtml+xml - application/xml - application/xml-dtd - application/xop+xml - application/zip - application/gzip - audio/basic - audio/L24 - audio/mp4 - audio/mpeg - audio/ogg - audio/vorbis - audio/vnd.rn-realaudio - audio/vnd.wave - audio/webm - image/gif - image/jpeg - image/pjpeg - image/png - image/svg+xml - image/tiff - image/vnd.microsoft.icon - message/http - message/imdn+xml - message/partial - message/rfc822 - model/example - model/iges - model/mesh - model/vrml - model/x3d+binary - model/x3d+vrml - model/x3d+xml - multipart/mixed - multipart/alternative - multipart/related - multipart/form-data - multipart/signed - multipart/encrypted - text/cmd - text/css - text/csv - text/html - text/javascript - application/javascript - text/plain - text/vcard - text/xml - video/mpeg - video/mp4 - video/ogg - video/quicktime - video/webm - video/x-matroska - video/x-ms-wmv - video/x-flv - application/vnd.oasis.opendocument.text - application/vnd.oasis.opendocument.spreadsheet - application/vnd.oasis.opendocument.presentation - application/vnd.oasis.opendocument.graphics - application/vnd.ms-excel - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet - application/vnd.ms-powerpoint - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.mozilla.xul+xml - application/vnd.google-earth.kml+xml - application/x-deb - application/x-dvi - application/x-font-ttf - application/x-javascript - application/x-latex - application/x-mpegURL - application/x-rar-compressed - application/x-shockwave-flash - application/x-stuffit - application/x-tar - application/x-www-form-urlencoded - application/x-xpinstall - audio/x-aac - audio/x-caf - image/x-xcf - text/x-gwt-rpc - text/x-jquery-tmpl - application/x-pkcs12 - application/x-pkcs12 - application/x-pkcs7-certificates - application/x-pkcs7-certificates - application/x-pkcs7-certreqresp - application/x-pkcs7-mime - application/x-pkcs7-mime - application/x-pkcs7-signature - ) - - mime_types.each { |mime_type| assert mime_type.match(Sinatra::Request::HEADER_VALUE_WITH_PARAMS) } - end - - it "filters by accept header" do - mock_app { - get '/', :provides => :xml do - env['HTTP_ACCEPT'] - end - get '/foo', :provides => :html do - env['HTTP_ACCEPT'] - end - get '/stream', :provides => 'text/event-stream' do - env['HTTP_ACCEPT'] - end - } - - get '/', {}, { 'HTTP_ACCEPT' => 'application/xml' } - assert ok? - assert_equal 'application/xml', body - assert_equal 'application/xml;charset=utf-8', response.headers['Content-Type'] - - get '/', {}, {} - assert ok? - assert_equal '', body - assert_equal 'application/xml;charset=utf-8', response.headers['Content-Type'] - - get '/', {}, { 'HTTP_ACCEPT' => '*/*' } - assert ok? - assert_equal '*/*', body - assert_equal 'application/xml;charset=utf-8', response.headers['Content-Type'] - - get '/', {}, { 'HTTP_ACCEPT' => 'text/html;q=0.9' } - assert !ok? - - get '/foo', {}, { 'HTTP_ACCEPT' => 'text/html;q=0.9' } - assert ok? - assert_equal 'text/html;q=0.9', body - - get '/foo', {}, { 'HTTP_ACCEPT' => '' } - assert ok? - assert_equal '', body - - get '/foo', {}, { 'HTTP_ACCEPT' => '*/*' } - assert ok? - assert_equal '*/*', body - - get '/foo', {}, { 'HTTP_ACCEPT' => 'application/xml' } - assert !ok? - - get '/stream', {}, { 'HTTP_ACCEPT' => 'text/event-stream' } - assert ok? - assert_equal 'text/event-stream', body - - get '/stream', {}, { 'HTTP_ACCEPT' => '' } - assert ok? - assert_equal '', body - - get '/stream', {}, { 'HTTP_ACCEPT' => '*/*' } - assert ok? - assert_equal '*/*', body - - get '/stream', {}, { 'HTTP_ACCEPT' => 'application/xml' } - assert !ok? - end - - it "filters by current Content-Type" do - mock_app do - before('/txt') { content_type :txt } - get('*', :provides => :txt) { 'txt' } - - before('/html') { content_type :html } - get('*', :provides => :html) { 'html' } - end - - get '/', {}, { 'HTTP_ACCEPT' => '*/*' } - assert ok? - assert_equal 'text/plain;charset=utf-8', response.headers['Content-Type'] - assert_body 'txt' - - get '/txt', {}, { 'HTTP_ACCEPT' => 'text/plain' } - assert ok? - assert_equal 'text/plain;charset=utf-8', response.headers['Content-Type'] - assert_body 'txt' - - get '/', {}, { 'HTTP_ACCEPT' => 'text/html' } - assert ok? - assert_equal 'text/html;charset=utf-8', response.headers['Content-Type'] - assert_body 'html' - end - - it "allows multiple mime types for accept header" do - types = ['image/jpeg', 'image/pjpeg'] - - mock_app { - get '/', :provides => types do - env['HTTP_ACCEPT'] - end - } - - types.each do |type| - get '/', {}, { 'HTTP_ACCEPT' => type } - assert ok? - assert_equal type, body - assert_equal type, response.headers['Content-Type'] - end - end - - it 'respects user agent preferences for the content type' do - mock_app { get('/', :provides => [:png, :html]) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5,text/html;q=0.8' } - assert_body 'text/html;charset=utf-8' - get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.8,text/html;q=0.5' } - assert_body 'image/png' - end - - it 'accepts generic types' do - mock_app do - get('/', :provides => :xml) { content_type } - get('/') { 'no match' } - end - get '/', {}, { 'HTTP_ACCEPT' => 'foo/*' } - assert_body 'no match' - get '/', {}, { 'HTTP_ACCEPT' => 'application/*' } - assert_body 'application/xml;charset=utf-8' - get '/', {}, { 'HTTP_ACCEPT' => '*/*' } - assert_body 'application/xml;charset=utf-8' - end - - it 'prefers concrete over partly generic types' do - mock_app { get('/', :provides => [:png, :html]) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => 'image/*, text/html' } - assert_body 'text/html;charset=utf-8' - get '/', {}, { 'HTTP_ACCEPT' => 'image/png, text/*' } - assert_body 'image/png' - end - - it 'prefers concrete over fully generic types' do - mock_app { get('/', :provides => [:png, :html]) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => '*/*, text/html' } - assert_body 'text/html;charset=utf-8' - get '/', {}, { 'HTTP_ACCEPT' => 'image/png, */*' } - assert_body 'image/png' - end - - it 'prefers partly generic over fully generic types' do - mock_app { get('/', :provides => [:png, :html]) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => '*/*, text/*' } - assert_body 'text/html;charset=utf-8' - get '/', {}, { 'HTTP_ACCEPT' => 'image/*, */*' } - assert_body 'image/png' - end - - it 'respects quality with generic types' do - mock_app { get('/', :provides => [:png, :html]) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => 'image/*;q=1, text/html;q=0' } - assert_body 'image/png' - get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5, text/*;q=0.7' } - assert_body 'text/html;charset=utf-8' - end - - it 'supplies a default quality of 1.0' do - mock_app { get('/', :provides => [:png, :html]) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5, text/*' } - assert_body 'text/html;charset=utf-8' - end - - it 'orders types with equal quality by parameter count' do - mock_app do - get('/', :provides => [:png, :jpg]) { content_type } - end - - lo_png = 'image/png;q=0.5' - hi_png = 'image/png;q=0.5;profile=FOGRA40;gamma=0.8' - jpeg = 'image/jpeg;q=0.5;compress=0.25' - - get '/', {}, { 'HTTP_ACCEPT' => "#{lo_png}, #{jpeg}" } - assert_body 'image/jpeg' - get '/', {}, { 'HTTP_ACCEPT' => "#{hi_png}, #{jpeg}" } - assert_body 'image/png' - end - - it 'ignores the quality parameter when ordering by parameter count' do - mock_app do - get('/', :provides => [:png, :jpg]) { content_type } - end - - lo_png = 'image/png' - hi_png = 'image/png;profile=FOGRA40;gamma=0.8' - jpeg = 'image/jpeg;q=1.0;compress=0.25' - - get '/', {}, { 'HTTP_ACCEPT' => "#{jpeg}, #{lo_png}" } - assert_body 'image/jpeg' - get '/', {}, { 'HTTP_ACCEPT' => "#{jpeg}, #{hi_png}" } - assert_body 'image/png' - end - - it 'properly handles quoted strings in parameters' do - mock_app do - get('/', :provides => [:png, :jpg]) { content_type } - end - - get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5;profile=",image/jpeg,"' } - assert_body 'image/png' - get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5,image/jpeg;q=0;x=";q=1.0"' } - assert_body 'image/png' - get '/', {}, { 'HTTP_ACCEPT' => 'image/png;q=0.5,image/jpeg;q=0;x="\";q=1.0"' } - assert_body 'image/png' - end - - it 'accepts both text/javascript and application/javascript for js' do - mock_app { get('/', :provides => :js) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => 'application/javascript' } - assert_body 'application/javascript;charset=utf-8' - get '/', {}, { 'HTTP_ACCEPT' => 'text/javascript' } - assert_body 'text/javascript;charset=utf-8' - end - - it 'accepts both text/xml and application/xml for xml' do - mock_app { get('/', :provides => :xml) { content_type }} - get '/', {}, { 'HTTP_ACCEPT' => 'application/xml' } - assert_body 'application/xml;charset=utf-8' - get '/', {}, { 'HTTP_ACCEPT' => 'text/xml' } - assert_body 'text/xml;charset=utf-8' - end - - it 'passes a single url param as block parameters when one param is specified' do - mock_app { - get '/:foo' do |foo| - assert_equal 'bar', foo - end - } - - get '/bar' - assert ok? - end - - it 'passes multiple params as block parameters when many are specified' do - mock_app { - get '/:foo/:bar/:baz' do |foo, bar, baz| - assert_equal 'abc', foo - assert_equal 'def', bar - assert_equal 'ghi', baz - end - } - - get '/abc/def/ghi' - assert ok? - end - - it 'passes regular expression captures as block parameters' do - mock_app { - get(/^\/fo(.*)\/ba(.*)/) do |foo, bar| - assert_equal 'orooomma', foo - assert_equal 'f', bar - 'looks good' - end - } - - get '/foorooomma/baf' - assert ok? - assert_equal 'looks good', body - end - - it "supports mixing multiple splat params like /*/foo/*/* as block parameters" do - mock_app { - get '/*/foo/*/*' do |foo, bar, baz| - assert_equal 'bar', foo - assert_equal 'bling', bar - assert_equal 'baz/boom', baz - 'looks good' - end - } - - get '/bar/foo/bling/baz/boom' - assert ok? - assert_equal 'looks good', body - end - - it 'raises an ArgumentError with block arity > 1 and too many values' do - mock_app do - get '/:foo/:bar/:baz' do |foo, bar| - 'quux' - end - end - - assert_raise(ArgumentError) { get '/a/b/c' } - end - - it 'raises an ArgumentError with block param arity > 1 and too few values' do - mock_app { - get '/:foo/:bar' do |foo, bar, baz| - 'quux' - end - } - - assert_raise(ArgumentError) { get '/a/b' } - end - - it 'succeeds if no block parameters are specified' do - mock_app { - get '/:foo/:bar' do - 'quux' - end - } - - get '/a/b' - assert ok? - assert_equal 'quux', body - end - - it 'passes all params with block param arity -1 (splat args)' do - mock_app { - get '/:foo/:bar' do |*args| - args.join - end - } - - get '/a/b' - assert ok? - assert_equal 'ab', body - end - - it 'allows custom route-conditions to be set via route options' do - protector = Module.new { - def protect(*args) - condition { - unless authorize(params["user"], params["password"]) - halt 403, "go away" - end - } - end - } - - mock_app { - register protector - - helpers do - def authorize(username, password) - username == "foo" && password == "bar" - end - end - - get "/", :protect => true do - "hey" - end - } - - get "/" - assert forbidden? - assert_equal "go away", body - - get "/", :user => "foo", :password => "bar" - assert ok? - assert_equal "hey", body - end - - # NOTE Block params behaves differently under 1.8 and 1.9. Under 1.8, block - # param arity is lax: declaring a mismatched number of block params results - # in a warning. Under 1.9, block param arity is strict: mismatched block - # arity raises an ArgumentError. - - if RUBY_VERSION >= '1.9' - - it 'raises an ArgumentError with block param arity 1 and no values' do - mock_app { - get '/foo' do |foo| - 'quux' - end - } - - assert_raise(ArgumentError) { get '/foo' } - end - - it 'raises an ArgumentError with block param arity 1 and too many values' do - mock_app { - get '/:foo/:bar/:baz' do |foo| - 'quux' - end - } - - assert_raise(ArgumentError) { get '/a/b/c' } - end - - else - - it 'does not raise an ArgumentError with block param arity 1 and no values' do - mock_app { - get '/foo' do |foo| - 'quux' - end - } - - silence_warnings { get '/foo' } - assert ok? - assert_equal 'quux', body - end - - it 'does not raise an ArgumentError with block param arity 1 and too many values' do - mock_app { - get '/:foo/:bar/:baz' do |foo| - 'quux' - end - } - - silence_warnings { get '/a/b/c' } - assert ok? - assert_equal 'quux', body - end - - end - - it "matches routes defined in superclasses" do - base = Class.new(Sinatra::Base) - base.get('/foo') { 'foo in baseclass' } - - mock_app(base) { - get('/bar') { 'bar in subclass' } - } - - get '/foo' - assert ok? - assert_equal 'foo in baseclass', body - - get '/bar' - assert ok? - assert_equal 'bar in subclass', body - end - - it "matches routes in subclasses before superclasses" do - base = Class.new(Sinatra::Base) - base.get('/foo') { 'foo in baseclass' } - base.get('/bar') { 'bar in baseclass' } - - mock_app(base) { - get('/foo') { 'foo in subclass' } - } - - get '/foo' - assert ok? - assert_equal 'foo in subclass', body - - get '/bar' - assert ok? - assert_equal 'bar in baseclass', body - end - - it "adds hostname condition when it is in options" do - mock_app { - get '/foo', :host => 'host' do - 'foo' - end - } - - get '/foo' - assert not_found? - end - - it 'allows using call to fire another request internally' do - mock_app do - get '/foo' do - status, headers, body = call env.merge("PATH_INFO" => '/bar') - [status, headers, body.each.map(&:upcase)] - end - - get '/bar' do - "bar" - end - end - - get '/foo' - assert ok? - assert_body "BAR" - end - - it 'plays well with other routing middleware' do - middleware = Sinatra.new - inner_app = Sinatra.new { get('/foo') { 'hello' } } - builder = Rack::Builder.new do - use middleware - map('/test') { run inner_app } - end - - @app = builder.to_app - get '/test/foo' - assert ok? - assert_body 'hello' - end - - it 'returns the route signature' do - signature = list = nil - - mock_app do - signature = post('/') { } - list = routes['POST'] - end - - assert_equal Array, signature.class - assert_equal 4, signature.length - assert list.include?(signature) - end - - it "sets env['sinatra.route'] to the matched route" do - mock_app do - after do - assert_equal 'GET /users/:id/status', env['sinatra.route'] - end - get('/users/:id/status') { 'ok' } - end - get '/users/1/status' - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/sass_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/sass_test.rb deleted file mode 100644 index fec4e2f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/sass_test.rb +++ /dev/null @@ -1,115 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'sass' - -class SassTest < Test::Unit::TestCase - def sass_app(options = {}, &block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - set options - get('/', &block) - end - get '/' - end - - it 'renders inline Sass strings' do - sass_app { sass "#sass\n :background-color white\n" } - assert ok? - assert_equal "#sass {\n background-color: white; }\n", body - end - - it 'defaults content type to css' do - sass_app { sass "#sass\n :background-color white\n" } - assert ok? - assert_equal "text/css;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type per route' do - sass_app do - content_type :html - sass "#sass\n :background-color white\n" - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type globally' do - sass_app(:sass => { :content_type => 'html' }) { - sass "#sass\n :background-color white\n" - } - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'renders .sass files in views path' do - sass_app { sass :hello } - assert ok? - assert_equal "#sass {\n background-color: white; }\n", body - end - - it 'ignores the layout option' do - sass_app { sass :hello, :layout => :layout2 } - assert ok? - assert_equal "#sass {\n background-color: white; }\n", body - end - - it "raises error if template not found" do - mock_app { get('/') { sass :no_such_template } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "passes SASS options to the Sass engine" do - sass_app do - sass( - "#sass\n :background-color white\n :color black\n", - :style => :compact - ) - end - assert ok? - assert_equal("#sass { background-color: white; color: black; }\n", body) - end - - it "passes default SASS options to the Sass engine" do - mock_app do - set :sass, {:style => :compact} # default Sass style is :nested - get('/') { sass("#sass\n :background-color white\n :color black\n") } - end - get '/' - assert ok? - assert_equal "#sass { background-color: white; color: black; }\n", body - end - - it "merges the default SASS options with the overrides" do - mock_app do - # default Sass attribute_syntax is :normal (with : in front) - set :sass, {:style => :compact, :attribute_syntax => :alternate } - get('/') { sass("#sass\n background-color: white\n color: black\n") } - get('/raised') do - # retains global attribute_syntax settings - sass( - "#sass\n :background-color white\n :color black\n", - :style => :expanded - ) - end - get('/expanded_normal') do - sass( - "#sass\n :background-color white\n :color black\n", - :style => :expanded, :attribute_syntax => :normal - ) - end - end - get '/' - assert ok? - assert_equal "#sass { background-color: white; color: black; }\n", body - assert_raise(Sass::SyntaxError) { get('/raised') } - get '/expanded_normal' - assert ok? - assert_equal "#sass {\n background-color: white;\n color: black;\n}\n", - body - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping sass tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/scss_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/scss_test.rb deleted file mode 100644 index 3d43e88..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/scss_test.rb +++ /dev/null @@ -1,88 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'sass' - -class ScssTest < Test::Unit::TestCase - def scss_app(options = {}, &block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - set options - get('/', &block) - end - get '/' - end - - it 'renders inline Scss strings' do - scss_app { scss "#scss {\n background-color: white; }\n" } - assert ok? - assert_equal "#scss {\n background-color: white; }\n", body - end - - it 'defaults content type to css' do - scss_app { scss "#scss {\n background-color: white; }\n" } - assert ok? - assert_equal "text/css;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type per route' do - scss_app do - content_type :html - scss "#scss {\n background-color: white; }\n" - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type globally' do - scss_app(:scss => { :content_type => 'html' }) { - scss "#scss {\n background-color: white; }\n" - } - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'renders .scss files in views path' do - scss_app { scss :hello } - assert ok? - assert_equal "#scss {\n background-color: white; }\n", body - end - - it 'ignores the layout option' do - scss_app { scss :hello, :layout => :layout2 } - assert ok? - assert_equal "#scss {\n background-color: white; }\n", body - end - - it "raises error if template not found" do - mock_app { get('/') { scss(:no_such_template) } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "passes scss options to the scss engine" do - scss_app do - scss( - "#scss {\n background-color: white;\n color: black\n}", - :style => :compact - ) - end - assert ok? - assert_equal "#scss { background-color: white; color: black; }\n", body - end - - it "passes default scss options to the scss engine" do - mock_app do - set :scss, {:style => :compact} # default scss style is :nested - get('/') { - scss("#scss {\n background-color: white;\n color: black;\n}") - } - end - get '/' - assert ok? - assert_equal "#scss { background-color: white; color: black; }\n", body - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping scss tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/server_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/server_test.rb deleted file mode 100644 index 7a0633c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/server_test.rb +++ /dev/null @@ -1,48 +0,0 @@ -require File.expand_path('../helper', __FILE__) -require 'stringio' - -module Rack::Handler - class Mock - extend Test::Unit::Assertions - - def self.run(app, options={}) - assert(app < Sinatra::Base) - assert_equal 9001, options[:Port] - assert_equal 'foo.local', options[:Host] - yield new - end - - def stop - end - end - - register 'mock', 'Rack::Handler::Mock' -end - -class ServerTest < Test::Unit::TestCase - setup do - mock_app do - set :server, 'mock' - set :bind, 'foo.local' - set :port, 9001 - end - $stderr = StringIO.new - end - - def teardown - $stderr = STDERR - end - - it "locates the appropriate Rack handler and calls ::run" do - @app.run! - end - - it "sets options on the app before running" do - @app.run! :sessions => true - assert @app.sessions? - end - - it "falls back on the next server handler when not found" do - @app.run! :server => %w[foo bar mock] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/settings_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/settings_test.rb deleted file mode 100644 index 127c97c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/settings_test.rb +++ /dev/null @@ -1,582 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class SettingsTest < Test::Unit::TestCase - setup do - @base = Sinatra.new(Sinatra::Base) - @base.set :environment => :foo, :app_file => nil - - @application = Sinatra.new(Sinatra::Application) - @application.set :environment => :foo, :app_file => nil - end - - it 'sets settings to literal values' do - @base.set(:foo, 'bar') - assert @base.respond_to?(:foo) - assert_equal 'bar', @base.foo - end - - it 'sets settings to Procs' do - @base.set(:foo, Proc.new { 'baz' }) - assert @base.respond_to?(:foo) - assert_equal 'baz', @base.foo - end - - it 'sets settings using a block' do - @base.set(:foo){ 'baz' } - assert @base.respond_to?(:foo) - assert_equal 'baz', @base.foo - end - - it 'raises an error with a value and a block' do - assert_raise ArgumentError do - @base.set(:fiz, 'boom!'){ 'baz' } - end - assert !@base.respond_to?(:fiz) - end - - it 'raises an error without value and block' do - assert_raise(ArgumentError) { @base.set(:fiz) } - assert !@base.respond_to?(:fiz) - end - - it 'allows setting a value to the app class' do - @base.set :base, @base - assert @base.respond_to?(:base) - assert_equal @base, @base.base - end - - it 'raises an error with the app class as value and a block' do - assert_raise ArgumentError do - @base.set(:fiz, @base) { 'baz' } - end - assert !@base.respond_to?(:fiz) - end - - it "sets multiple settings with a Hash" do - @base.set :foo => 1234, - :bar => 'Hello World', - :baz => Proc.new { 'bizzle' } - assert_equal 1234, @base.foo - assert_equal 'Hello World', @base.bar - assert_equal 'bizzle', @base.baz - end - - it 'sets multiple settings using #each' do - @base.set [["foo", "bar"]] - assert_equal "bar", @base.foo - end - - it 'inherits settings methods when subclassed' do - @base.set :foo, 'bar' - @base.set :biz, Proc.new { 'baz' } - - sub = Class.new(@base) - assert sub.respond_to?(:foo) - assert_equal 'bar', sub.foo - assert sub.respond_to?(:biz) - assert_equal 'baz', sub.biz - end - - it 'overrides settings in subclass' do - @base.set :foo, 'bar' - @base.set :biz, Proc.new { 'baz' } - sub = Class.new(@base) - sub.set :foo, 'bling' - assert_equal 'bling', sub.foo - assert_equal 'bar', @base.foo - end - - it 'creates setter methods when first defined' do - @base.set :foo, 'bar' - assert @base.respond_to?('foo=') - @base.foo = 'biz' - assert_equal 'biz', @base.foo - end - - it 'creates predicate methods when first defined' do - @base.set :foo, 'hello world' - assert @base.respond_to?(:foo?) - assert @base.foo? - @base.set :foo, nil - assert !@base.foo? - end - - it 'uses existing setter methods if detected' do - class << @base - def foo - @foo - end - def foo=(value) - @foo = 'oops' - end - end - - @base.set :foo, 'bam' - assert_equal 'oops', @base.foo - end - - it 'merges values of multiple set calls if those are hashes' do - @base.set :foo, :a => 1 - sub = Class.new(@base) - sub.set :foo, :b => 2 - assert_equal({:a => 1, :b => 2}, sub.foo) - end - - it 'merging does not affect the superclass' do - @base.set :foo, :a => 1 - sub = Class.new(@base) - sub.set :foo, :b => 2 - assert_equal({:a => 1}, @base.foo) - end - - it 'is possible to change a value from a hash to something else' do - @base.set :foo, :a => 1 - @base.set :foo, :bar - assert_equal(:bar, @base.foo) - end - - it 'merges values with values of the superclass if those are hashes' do - @base.set :foo, :a => 1 - @base.set :foo, :b => 2 - assert_equal({:a => 1, :b => 2}, @base.foo) - end - - it "sets multiple settings to true with #enable" do - @base.enable :sessions, :foo, :bar - assert @base.sessions - assert @base.foo - assert @base.bar - end - - it "sets multiple settings to false with #disable" do - @base.disable :sessions, :foo, :bar - assert !@base.sessions - assert !@base.foo - assert !@base.bar - end - - it 'is accessible from instances via #settings' do - assert_equal :foo, @base.new!.settings.environment - end - - it 'is accessible from class via #settings' do - assert_equal :foo, @base.settings.environment - end - - describe 'methodoverride' do - it 'is disabled on Base' do - assert ! @base.method_override? - end - - it 'is enabled on Application' do - assert @application.method_override? - end - - it 'enables MethodOverride middleware' do - @base.set :method_override, true - @base.put('/') { 'okay' } - @app = @base - post '/', {'_method'=>'PUT'}, {} - assert_equal 200, status - assert_equal 'okay', body - end - - it 'is backward compatible with methodoverride' do - assert ! @base.methodoverride? - @base.enable :methodoverride - assert @base.methodoverride? - end - end - - describe 'run' do - it 'is disabled on Base' do - assert ! @base.run? - end - - it 'is enabled on Application except in test environment' do - assert @application.run? - - @application.set :environment, :test - assert ! @application.run? - end - end - - describe 'raise_errors' do - it 'is enabled on Base only in test' do - assert ! @base.raise_errors? - - @base.set(:environment, :test) - assert @base.raise_errors? - end - - it 'is enabled on Application only in test' do - assert ! @application.raise_errors? - - @application.set(:environment, :test) - assert @application.raise_errors? - end - end - - describe 'show_exceptions' do - it 'is disabled on Base except under development' do - assert ! @base.show_exceptions? - @base.environment = :development - assert @base.show_exceptions? - end - - it 'is disabled on Application except in development' do - assert ! @application.show_exceptions? - - @application.set(:environment, :development) - assert @application.show_exceptions? - end - - it 'returns a friendly 500' do - klass = Sinatra.new(Sinatra::Application) - mock_app(klass) { - enable :show_exceptions - - get '/' do - raise StandardError - end - } - - get '/' - assert_equal 500, status - assert body.include?("StandardError") - assert body.include?("show_exceptions setting") - end - - it 'does not override app-specified error handling when set to :after_handler' do - ran = false - mock_app do - set :show_exceptions, :after_handler - error(RuntimeError) { ran = true } - get('/') { raise RuntimeError } - end - - get '/' - assert_equal 500, status - assert ran - end - - it 'does catch any other exceptions when set to :after_handler' do - ran = false - mock_app do - set :show_exceptions, :after_handler - error(RuntimeError) { ran = true } - get('/') { raise ArgumentError } - end - - get '/' - assert_equal 500, status - assert !ran - end - end - - describe 'dump_errors' do - it 'is disabled on Base in test' do - @base.environment = :test - assert ! @base.dump_errors? - @base.environment = :development - assert @base.dump_errors? - @base.environment = :production - assert @base.dump_errors? - end - - it 'dumps exception with backtrace to rack.errors' do - klass = Sinatra.new(Sinatra::Application) - - mock_app(klass) { - enable :dump_errors - disable :raise_errors - - error do - error = @env['rack.errors'].instance_variable_get(:@error) - error.rewind - - error.read - end - - get '/' do - raise - end - } - - get '/' - assert body.include?("RuntimeError") && body.include?("settings_test.rb") - end - - it 'does not dump 404 errors' do - klass = Sinatra.new(Sinatra::Application) - - mock_app(klass) { - enable :dump_errors - disable :raise_errors - - error do - error = @env['rack.errors'].instance_variable_get(:@error) - error.rewind - - error.read - end - - get '/' do - raise Sinatra::NotFound - end - } - - get '/' - assert !body.include?("NotFound") && !body.include?("settings_test.rb") - end - end - - describe 'sessions' do - it 'is disabled on Base' do - assert ! @base.sessions? - end - - it 'is disabled on Application' do - assert ! @application.sessions? - end - end - - describe 'logging' do - it 'is disabled on Base' do - assert ! @base.logging? - end - - it 'is enabled on Application except in test environment' do - assert @application.logging? - - @application.set :environment, :test - assert ! @application.logging - end - end - - describe 'static' do - it 'is disabled on Base by default' do - assert ! @base.static? - end - - it 'is enabled on Base when public_folder is set and exists' do - @base.set :environment, :development - @base.set :public_folder, File.dirname(__FILE__) - assert @base.static? - end - - it 'is enabled on Base when root is set and root/public_folder exists' do - @base.set :environment, :development - @base.set :root, File.dirname(__FILE__) - assert @base.static? - end - - it 'is disabled on Application by default' do - assert ! @application.static? - end - - it 'is enabled on Application when public_folder is set and exists' do - @application.set :environment, :development - @application.set :public_folder, File.dirname(__FILE__) - assert @application.static? - end - - it 'is enabled on Application when root is set and root/public_folder exists' do - @application.set :environment, :development - @application.set :root, File.dirname(__FILE__) - assert @application.static? - end - - it 'is possible to use Module#public' do - @base.send(:define_method, :foo) { } - @base.send(:private, :foo) - assert !@base.public_method_defined?(:foo) - @base.send(:public, :foo) - assert @base.public_method_defined?(:foo) - end - - it 'is possible to use the keyword public in a sinatra app' do - app = Sinatra.new do - private - def priv; end - public - def pub; end - end - assert !app.public_method_defined?(:priv) - assert app.public_method_defined?(:pub) - end - end - - describe 'bind' do - it 'defaults to 0.0.0.0' do - assert_equal '0.0.0.0', @base.bind - assert_equal '0.0.0.0', @application.bind - end - end - - describe 'port' do - it 'defaults to 4567' do - assert_equal 4567, @base.port - assert_equal 4567, @application.port - end - end - - describe 'server' do - it 'includes webrick' do - assert @base.server.include?('webrick') - assert @application.server.include?('webrick') - end - - it 'includes puma' do - assert @base.server.include?('puma') - assert @application.server.include?('puma') - end - - it 'includes thin' do - next if RUBY_ENGINE == 'jruby' - assert @base.server.include?('thin') - assert @application.server.include?('thin') - end - end - - describe 'app_file' do - it 'is nil for base classes' do - assert_nil Sinatra::Base.app_file - assert_nil Sinatra::Application.app_file - end - - it 'defaults to the file subclassing' do - assert_equal File.expand_path(__FILE__), Sinatra.new.app_file - end - end - - describe 'root' do - it 'is nil if app_file is not set' do - assert @base.root.nil? - assert @application.root.nil? - end - - it 'is equal to the expanded basename of app_file' do - @base.app_file = __FILE__ - assert_equal File.expand_path(File.dirname(__FILE__)), @base.root - - @application.app_file = __FILE__ - assert_equal File.expand_path(File.dirname(__FILE__)), @application.root - end - end - - describe 'views' do - it 'is nil if root is not set' do - assert @base.views.nil? - assert @application.views.nil? - end - - it 'is set to root joined with views/' do - @base.root = File.dirname(__FILE__) - assert_equal File.dirname(__FILE__) + "/views", @base.views - - @application.root = File.dirname(__FILE__) - assert_equal File.dirname(__FILE__) + "/views", @application.views - end - end - - describe 'public_folder' do - it 'is nil if root is not set' do - assert @base.public_folder.nil? - assert @application.public_folder.nil? - end - - it 'is set to root joined with public/' do - @base.root = File.dirname(__FILE__) - assert_equal File.dirname(__FILE__) + "/public", @base.public_folder - - @application.root = File.dirname(__FILE__) - assert_equal File.dirname(__FILE__) + "/public", @application.public_folder - end - end - - describe 'public_dir' do - it 'is an alias for public_folder' do - @base.public_dir = File.dirname(__FILE__) - assert_equal File.dirname(__FILE__), @base.public_dir - assert_equal @base.public_folder, @base.public_dir - - @application.public_dir = File.dirname(__FILE__) - assert_equal File.dirname(__FILE__), @application.public_dir - assert_equal @application.public_folder, @application.public_dir - end - end - - describe 'lock' do - it 'is disabled by default' do - assert ! @base.lock? - assert ! @application.lock? - end - end - - describe 'protection' do - class MiddlewareTracker < Rack::Builder - def self.track - Rack.send :remove_const, :Builder - Rack.const_set :Builder, MiddlewareTracker - MiddlewareTracker.used.clear - yield - ensure - Rack.send :remove_const, :Builder - Rack.const_set :Builder, MiddlewareTracker.superclass - end - - def self.used - @used ||= [] - end - - def use(middleware, *) - MiddlewareTracker.used << middleware - super - end - end - - it 'sets up Rack::Protection' do - MiddlewareTracker.track do - Sinatra::Base.new - assert_include MiddlewareTracker.used, Rack::Protection - end - end - - it 'sets up Rack::Protection::PathTraversal' do - MiddlewareTracker.track do - Sinatra::Base.new - assert_include MiddlewareTracker.used, Rack::Protection::PathTraversal - end - end - - it 'does not set up Rack::Protection::PathTraversal when disabling it' do - MiddlewareTracker.track do - Sinatra.new { set :protection, :except => :path_traversal }.new - assert_include MiddlewareTracker.used, Rack::Protection - assert !MiddlewareTracker.used.include?(Rack::Protection::PathTraversal) - end - end - - it 'sets up RemoteToken if sessions are enabled' do - MiddlewareTracker.track do - Sinatra.new { enable :sessions }.new - assert_include MiddlewareTracker.used, Rack::Protection::RemoteToken - end - end - - it 'does not set up RemoteToken if sessions are disabled' do - MiddlewareTracker.track do - Sinatra.new.new - assert !MiddlewareTracker.used.include?(Rack::Protection::RemoteToken) - end - end - - it 'sets up RemoteToken if it is configured to' do - MiddlewareTracker.track do - Sinatra.new { set :protection, :session => true }.new - assert_include MiddlewareTracker.used, Rack::Protection::RemoteToken - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/sinatra_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/sinatra_test.rb deleted file mode 100644 index 9a76c97..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/sinatra_test.rb +++ /dev/null @@ -1,12 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class SinatraTest < Test::Unit::TestCase - it 'creates a new Sinatra::Base subclass on new' do - app = Sinatra.new { get('/') { 'Hello World' } } - assert_same Sinatra::Base, app.superclass - end - - it "responds to #template_cache" do - assert_kind_of Tilt::Cache, Sinatra::Base.new!.template_cache - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/slim_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/slim_test.rb deleted file mode 100644 index d5a9fb8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/slim_test.rb +++ /dev/null @@ -1,102 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'slim' - -class SlimTest < Test::Unit::TestCase - def slim_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline slim strings' do - slim_app { slim "h1 Hiya\n" } - assert ok? - assert_equal "

Hiya

", body - end - - it 'renders .slim files in views path' do - slim_app { slim :hello } - assert ok? - assert_equal "

Hello From Slim

", body - end - - it "renders with inline layouts" do - mock_app do - layout { %(h1\n | THIS. IS. \n == yield.upcase ) } - get('/') { slim 'em Sparta' } - end - get '/' - assert ok? - assert_equal "

THIS. IS. SPARTA

", body - end - - it "renders with file layouts" do - slim_app { slim('| Hello World', :layout => :layout2) } - assert ok? - assert_equal "

Slim Layout!

Hello World

", body - end - - it "raises error if template not found" do - mock_app { get('/') { slim(:no_such_template) } } - assert_raise(Errno::ENOENT) { get('/') } - end - - HTML4_DOCTYPE = "" - - it "passes slim options to the slim engine" do - mock_app { get('/') { slim("x foo='bar'", :attr_quote => "'") }} - get '/' - assert ok? - assert_body "" - end - - it "passes default slim options to the slim engine" do - mock_app do - set :slim, :attr_quote => "'" - get('/') { slim("x foo='bar'") } - end - get '/' - assert ok? - assert_body "" - end - - it "merges the default slim options with the overrides and passes them to the slim engine" do - mock_app do - set :slim, :attr_quote => "'" - get('/') { slim("x foo='bar'") } - get('/other') { slim("x foo='bar'", :attr_quote => '"') } - end - get '/' - assert ok? - assert_body "" - get '/other' - assert ok? - assert_body '' - end - - it "can render truly nested layouts by accepting a layout and a block with the contents" do - mock_app do - template(:main_outer_layout) { "h1 Title\n== yield" } - template(:an_inner_layout) { "h2 Subtitle\n== yield" } - template(:a_page) { "p Contents." } - get('/') do - slim :main_outer_layout, :layout => false do - slim :an_inner_layout do - slim :a_page - end - end - end - end - get '/' - assert ok? - assert_body "

Title

\n

Subtitle

\n

Contents.

\n" - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping slim tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/static_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/static_test.rb deleted file mode 100644 index fb640b4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/static_test.rb +++ /dev/null @@ -1,236 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class StaticTest < Test::Unit::TestCase - setup do - mock_app do - set :static, true - set :public_folder, File.dirname(__FILE__) - end - end - - it 'serves GET requests for files in the public directory' do - get "/#{File.basename(__FILE__)}" - assert ok? - assert_equal File.read(__FILE__), body - assert_equal File.size(__FILE__).to_s, response['Content-Length'] - assert response.headers.include?('Last-Modified') - end - - it 'produces a body that can be iterated over multiple times' do - env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") - _, _, body = @app.call(env) - buf1, buf2 = [], [] - body.each { |part| buf1 << part } - body.each { |part| buf2 << part } - assert_equal buf1.join, buf2.join - assert_equal File.read(__FILE__), buf1.join - end - - it 'sets the sinatra.static_file env variable if served' do - env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") - @app.call(env) - assert_equal File.expand_path(__FILE__), env['sinatra.static_file'] - end - - it 'serves HEAD requests for files in the public directory' do - head "/#{File.basename(__FILE__)}" - assert ok? - assert_equal '', body - assert response.headers.include?('Last-Modified') - assert_equal File.size(__FILE__).to_s, response['Content-Length'] - end - - %w[POST PUT DELETE].each do |verb| - it "does not serve #{verb} requests" do - send verb.downcase, "/#{File.basename(__FILE__)}" - assert_equal 404, status - end - end - - it 'serves files in preference to custom routes' do - @app.get("/#{File.basename(__FILE__)}") { 'Hello World' } - get "/#{File.basename(__FILE__)}" - assert ok? - assert body != 'Hello World' - end - - it 'does not serve directories' do - get "/" - assert not_found? - end - - it 'passes to the next handler when the static option is disabled' do - @app.set :static, false - get "/#{File.basename(__FILE__)}" - assert not_found? - end - - it 'passes to the next handler when the public option is nil' do - @app.set :public_folder, nil - get "/#{File.basename(__FILE__)}" - assert not_found? - end - - it '404s when a file is not found' do - get "/foobarbaz.txt" - assert not_found? - end - - it 'serves files when .. path traverses within public directory' do - get "/data/../#{File.basename(__FILE__)}" - assert ok? - assert_equal File.read(__FILE__), body - end - - it '404s when .. path traverses outside of public directory' do - mock_app do - set :static, true - set :public_folder, File.dirname(__FILE__) + '/data' - end - get "/../#{File.basename(__FILE__)}" - assert not_found? - end - - def assert_valid_range(http_range, range, path, file) - request = Rack::MockRequest.new(@app) - response = request.get("/#{File.basename(path)}", 'HTTP_RANGE' => http_range) - - should_be = file[range] - expected_range = "bytes #{range.begin}-#{range.end}/#{file.length}" - - assert_equal( - 206,response.status, - "Should be HTTP/1.1 206 Partial content" - ) - assert_equal( - should_be.length, - response.body.length, - "Unexpected response length for #{http_range}" - ) - assert_equal( - should_be, - response.body, - "Unexpected response data for #{http_range}" - ) - assert_equal( - should_be.length.to_s, - response['Content-Length'], - "Incorrect Content-Length for #{http_range}" - ) - assert_equal( - expected_range, - response['Content-Range'], - "Incorrect Content-Range for #{http_range}" - ) - end - - it 'handles valid byte ranges correctly' do - # Use the biggest file in this dir so we can test ranges > 8k bytes. (StaticFile sends in 8k chunks.) - path = File.dirname(__FILE__) + '/helpers_test.rb' # currently 16k bytes - file = File.read(path) - length = file.length - assert length > 9000, "The test file #{path} is too short (#{length} bytes) to run these tests" - - [0..0, 42..88, 1234..1234, 100..9000, 0..(length-1), (length-1)..(length-1)].each do |range| - assert_valid_range("bytes=#{range.begin}-#{range.end}", range, path, file) - end - - [0, 100, length-100, length-1].each do |start| - assert_valid_range("bytes=#{start}-", (start..length-1), path, file) - end - - [1, 100, length-100, length-1, length].each do |range_length| - assert_valid_range("bytes=-#{range_length}", (length-range_length..length-1), path, file) - end - - # Some valid ranges that exceed the length of the file: - assert_valid_range("bytes=100-999999", (100..length-1), path, file) - assert_valid_range("bytes=100-#{length}", (100..length-1), path, file) - assert_valid_range("bytes=-#{length}", (0..length-1), path, file) - assert_valid_range("bytes=-#{length+1}", (0..length-1), path, file) - assert_valid_range("bytes=-999999", (0..length-1), path, file) - end - - it 'correctly ignores syntactically invalid range requests' do - # ...and also ignores multi-range requests, which aren't supported yet - ["bytes=45-40", "bytes=IV-LXVI", "octets=10-20", "bytes=-", "bytes=1-2,3-4"].each do |http_range| - request = Rack::MockRequest.new(@app) - response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range) - - assert_equal( - 200, - response.status, - "Invalid range '#{http_range}' should be ignored" - ) - assert_equal( - nil, - response['Content-Range'], - "Invalid range '#{http_range}' should be ignored" - ) - end - end - - it 'returns error 416 for unsatisfiable range requests' do - # An unsatisfiable request is one that specifies a start that's at or past the end of the file. - length = File.read(__FILE__).length - ["bytes=888888-", "bytes=888888-999999", "bytes=#{length}-#{length}"].each do |http_range| - request = Rack::MockRequest.new(@app) - response = request.get("/#{File.basename(__FILE__)}", 'HTTP_RANGE' => http_range) - - assert_equal( - 416, - response.status, - "Unsatisfiable range '#{http_range}' should return 416" - ) - assert_equal( - "bytes */#{length}", - response['Content-Range'], - "416 response should include actual length" - ) - end - end - - it 'does not include static cache control headers by default' do - env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") - _, headers, _ = @app.call(env) - assert !headers.has_key?('Cache-Control') - end - - it 'sets cache control headers on static files if set' do - @app.set :static_cache_control, :public - env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") - status, headers, body = @app.call(env) - assert headers.has_key?('Cache-Control') - assert_equal headers['Cache-Control'], 'public' - - @app.set( - :static_cache_control, - [:public, :must_revalidate, {:max_age => 300}] - ) - env = Rack::MockRequest.env_for("/#{File.basename(__FILE__)}") - status, headers, body = @app.call(env) - assert headers.has_key?('Cache-Control') - assert_equal( - headers['Cache-Control'], - 'public, must-revalidate, max-age=300' - ) - end - - it 'renders static assets with custom status via options' do - mock_app do - set :static, true - set :public_folder, File.dirname(__FILE__) - - post '/*' do - static!(:status => params[:status]) - end - end - - post "/#{File.basename(__FILE__)}?status=422" - assert_equal response.status, 422 - assert_equal File.read(__FILE__), body - assert_equal File.size(__FILE__).to_s, response['Content-Length'] - assert response.headers.include?('Last-Modified') - end - -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/streaming_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/streaming_test.rb deleted file mode 100644 index d307d3b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/streaming_test.rb +++ /dev/null @@ -1,149 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -class StreamingTest < Test::Unit::TestCase - Stream = Sinatra::Helpers::Stream - - it 'returns the concatenated body' do - mock_app do - get('/') do - stream do |out| - out << "Hello" << " " - out << "World!" - end - end - end - - get('/') - assert_body "Hello World!" - end - - it 'always yields strings' do - stream = Stream.new { |out| out << :foo } - stream.each { |str| assert_equal 'foo', str } - end - - it 'postpones body generation' do - step = 0 - - stream = Stream.new do |out| - 10.times do - out << step - step += 1 - end - end - - stream.each do |s| - assert_equal s, step.to_s - step += 1 - end - end - - it 'calls the callback after it is done' do - step = 0 - final = 0 - stream = Stream.new { |_| 10.times { step += 1 }} - stream.callback { final = step } - stream.each {|_|} - assert_equal 10, final - end - - it 'does not trigger the callback if close is set to :keep_open' do - step = 0 - final = 0 - stream = Stream.new(Stream, :keep_open) { |_| 10.times { step += 1 } } - stream.callback { final = step } - stream.each {|_|} - assert_equal 0, final - end - - it 'allows adding more than one callback' do - a = b = false - stream = Stream.new { } - stream.callback { a = true } - stream.callback { b = true } - stream.each {|_| } - assert a, 'should trigger first callback' - assert b, 'should trigger second callback' - end - - class MockScheduler - def initialize(*) @schedule, @defer = [], [] end - def schedule(&block) @schedule << block end - def defer(&block) @defer << block end - def schedule!(*) @schedule.pop.call until @schedule.empty? end - def defer!(*) @defer.pop.call until @defer.empty? end - end - - it 'allows dropping in another scheduler' do - scheduler = MockScheduler.new - processing = sending = done = false - - stream = Stream.new(scheduler) do |out| - processing = true - out << :foo - end - - stream.each { sending = true} - stream.callback { done = true } - - scheduler.schedule! - assert !processing - assert !sending - assert !done - - scheduler.defer! - assert processing - assert !sending - assert !done - - scheduler.schedule! - assert sending - assert done - end - - it 'schedules exceptions to be raised on the main thread/event loop/...' do - scheduler = MockScheduler.new - Stream.new(scheduler) { fail 'should be caught' }.each { } - scheduler.defer! - assert_raise(RuntimeError) { scheduler.schedule! } - end - - it 'does not trigger an infinite loop if you call close in a callback' do - stream = Stream.new { |out| out.callback { out.close }} - stream.each { |_| } - end - - it 'gives access to route specific params' do - mock_app do - get('/:name') do - stream { |o| o << params[:name] } - end - end - get '/foo' - assert_body 'foo' - end - - it 'sets up async.close if available' do - ran = false - mock_app do - get('/') do - close = Object.new - def close.callback; yield end - def close.errback; end - env['async.close'] = close - stream(:keep_open) do |out| - out.callback { ran = true } - end - end - end - get '/' - assert ran - end - - it 'has a public interface to inspect its open/closed state' do - stream = Stream.new(Stream) { |out| out << :foo } - assert !stream.closed? - stream.close - assert stream.closed? - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/stylus_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/stylus_test.rb deleted file mode 100644 index acde663..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/stylus_test.rb +++ /dev/null @@ -1,90 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin - require 'stylus' - require 'stylus/tilt' - - begin - Stylus.compile '1' - rescue RuntimeError - raise LoadError, 'unable to find Stylus compiler' - end - - class StylusTest < Test::Unit::TestCase - def stylus_app(options = {}, &block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - set(options) - get('/', &block) - end - get '/' - end - - it 'renders inline Stylus strings' do - stylus_app { stylus "a\n margin auto\n" } - assert ok? - assert body.include?("a {\n margin: auto;\n}\n") - end - - it 'defaults content type to css' do - stylus_app { stylus :hello } - assert ok? - assert_equal "text/css;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type per route' do - stylus_app do - content_type :html - stylus :hello - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'defaults allows setting content type globally' do - stylus_app(:styl => { :content_type => 'html' }) do - stylus :hello - end - assert ok? - assert_equal "text/html;charset=utf-8", response['Content-Type'] - end - - it 'renders .styl files in views path' do - stylus_app { stylus :hello } - assert ok? - assert_include body, "a {\n margin: auto;\n}\n" - end - - it 'ignores the layout option' do - stylus_app { stylus :hello, :layout => :layout2 } - assert ok? - assert_include body, "a {\n margin: auto;\n}\n" - end - - it "raises error if template not found" do - mock_app { - get('/') { stylus :no_such_template } - } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "passes stylus options to the stylus engine" do - stylus_app { stylus :hello, :no_wrap => true } - assert ok? - assert_body "a {\n margin: auto;\n}\n" - end - - it "passes default stylus options to the stylus engine" do - mock_app do - set :stylus, :no_wrap => true # default stylus style is :nested - get('/') { stylus :hello } - end - get '/' - assert ok? - assert_body "a {\n margin: auto;\n}\n" - end - end - -rescue LoadError - warn "#{$!.to_s}: skipping stylus tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/templates_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/templates_test.rb deleted file mode 100644 index 9266c6d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/templates_test.rb +++ /dev/null @@ -1,382 +0,0 @@ -# encoding: UTF-8 -require File.expand_path('../helper', __FILE__) -File.delete(File.dirname(__FILE__) + '/views/layout.test') rescue nil - -class TestTemplate < Tilt::Template - def prepare - end - - def evaluate(scope, locals={}, &block) - inner = block ? block.call : '' - data + inner - end - - Tilt.register 'test', self -end - -class TemplatesTest < Test::Unit::TestCase - def render_app(base=Sinatra::Base, options = {}, &block) - base, options = Sinatra::Base, base if base.is_a? Hash - mock_app(base) do - set :views, File.dirname(__FILE__) + '/views' - set options - get('/', &block) - template(:layout3) { "Layout 3!\n" } - end - get '/' - end - - def with_default_layout - layout = File.dirname(__FILE__) + '/views/layout.test' - File.open(layout, 'wb') { |io| io.write "Layout!\n" } - yield - ensure - File.unlink(layout) rescue nil - end - - it 'falls back to engine layout' do - mock_app do - template(:layout3) { 'Layout 3!<%= yield %>' } - set :erb, :layout => :layout3 - - get('/') do - erb('Hello World!', { :layout => true }) - end - end - - get '/' - assert ok? - assert_equal "Layout 3!Hello World!", body - end - - it 'falls back to default layout if engine layout is true' do - mock_app do - template(:layout) { 'Layout!!! <%= yield %>' } - set :erb, :layout => true - - get('/') do - erb('Hello World!', { :layout => true }) - end - end - - get '/' - assert ok? - assert_equal "Layout!!! Hello World!", body - end - - it 'renders no layout if layout if falsy' do - mock_app do - template(:layout) { 'Layout!!! <%= yield %>' } - set :erb, :layout => true - - get('/') do - erb('Hello World!', { :layout => nil }) - end - end - - get '/' - assert ok? - assert_equal "Hello World!", body - end - - it 'allows overriding false default layout with explicit true' do - mock_app do - template(:layout) { 'Layout!!! <%= yield %>' } - set :erb, :layout => false - - get('/') do - erb('Hello World!', { :layout => true }) - end - end - - get '/' - assert ok? - assert_equal "Layout!!! Hello World!", body - end - - it 'renders String templates directly' do - render_app { render(:test, 'Hello World') } - assert ok? - assert_equal 'Hello World', body - end - - it 'renders Proc templates using the call result' do - render_app { render(:test, Proc.new {'Hello World'}) } - assert ok? - assert_equal 'Hello World', body - end - - it 'looks up Symbol templates in views directory' do - render_app { render(:test, :hello) } - assert ok? - assert_equal "Hello World!\n", body - end - - it 'uses the default layout template if not explicitly overridden' do - with_default_layout do - render_app { render(:test, :hello) } - assert ok? - assert_equal "Layout!\nHello World!\n", body - end - end - - it 'uses the default layout template if not really overriden' do - with_default_layout do - render_app { render(:test, :hello, :layout => true) } - assert ok? - assert_equal "Layout!\nHello World!\n", body - end - end - - it 'uses the layout template specified' do - render_app { render(:test, :hello, :layout => :layout2) } - assert ok? - assert_equal "Layout 2!\nHello World!\n", body - end - - it 'uses layout templates defined with the #template method' do - render_app { render(:test, :hello, :layout => :layout3) } - assert ok? - assert_equal "Layout 3!\nHello World!\n", body - end - - it 'avoids wrapping layouts around nested templates' do - render_app { render(:str, :nested, :layout => :layout2) } - assert ok? - assert_equal( - "

String Layout!

\n

Hello From String

", - body - ) - end - - it 'allows explicitly wrapping layouts around nested templates' do - render_app { render(:str, :explicitly_nested, :layout => :layout2) } - assert ok? - assert_equal( - "

String Layout!

\n

String Layout!

\n

Hello From String

", - body - ) - end - - it 'two independent render calls do not disable layouts' do - render_app do - render :str, :explicitly_nested, :layout => :layout2 - render :str, :nested, :layout => :layout2 - end - assert ok? - assert_equal( - "

String Layout!

\n

Hello From String

", - body - ) - end - - it 'is possible to use partials in layouts' do - render_app do - settings.layout { "<%= erb 'foo' %><%= yield %>" } - erb 'bar' - end - assert ok? - assert_equal "foobar", body - end - - it 'loads templates from source file' do - mock_app { enable(:inline_templates) } - assert_equal "this is foo\n\n", @app.templates[:foo][0] - assert_equal "X\n= yield\nX\n", @app.templates[:layout][0] - end - - it 'ignores spaces after names of inline templates' do - mock_app { enable(:inline_templates) } - assert_equal "There's a space after 'bar'!\n\n", @app.templates[:bar][0] - assert_equal "this is not foo\n\n", @app.templates[:"foo bar"][0] - end - - it 'loads templates from given source file' do - mock_app { set(:inline_templates, __FILE__) } - assert_equal "this is foo\n\n", @app.templates[:foo][0] - end - - test 'inline_templates ignores IO errors' do - assert_nothing_raised { mock_app { set(:inline_templates, '/foo/bar') } } - - assert @app.templates.empty? - end - - it 'allows unicode in inline templates' do - mock_app { set(:inline_templates, __FILE__) } - assert_equal( - "Den som tror at hemma det är där man bor har aldrig vart hos mig.\n\n", - @app.templates[:umlaut][0] - ) - end - - it 'loads templates from specified views directory' do - render_app { render(:test, :hello, :views => settings.views + '/foo') } - - assert_equal "from another views directory\n", body - end - - it 'takes views directory into consideration for caching' do - render_app do - render(:test, :hello) + render(:test, :hello, :views => settings.views + '/foo') - end - assert_equal "Hello World!\nfrom another views directory\n", body - end - - it 'passes locals to the layout' do - mock_app do - template(:my_layout) { 'Hello <%= name %>!<%= yield %>' } - - get('/') do - erb('

content

', { :layout => :my_layout }, { :name => 'Mike'}) - end - end - - get '/' - assert ok? - assert_equal 'Hello Mike!

content

', body - end - - it 'sets layout-only options via layout_options' do - render_app do - render(:str, :in_a, - :views => settings.views + '/a', - :layout_options => { :views => settings.views }, - :layout => :layout2) - end - - assert ok? - assert_equal "

String Layout!

\nGimme an A!\n", body - end - - it 'loads templates defined in subclasses' do - base = Class.new(Sinatra::Base) - base.template(:foo) { 'bar' } - render_app(base) { render(:test, :foo) } - assert ok? - assert_equal 'bar', body - end - - it 'allows setting default content type per template engine' do - render_app(:str => { :content_type => :txt }) { - render :str, 'foo' - } - assert_equal 'text/plain;charset=utf-8', response['Content-Type'] - end - - it 'setting default content type does not affect other template engines' do - render_app(:str => { :content_type => :txt }) { - render :test, 'foo' - } - assert_equal 'text/html;charset=utf-8', response['Content-Type'] - end - - it 'setting default content type per template engine does not override content_type' do - render_app :str => { :content_type => :txt } do - content_type :html - render :str, 'foo' - end - assert_equal 'text/html;charset=utf-8', response['Content-Type'] - end - - it 'uses templates in superclasses before subclasses' do - base = Class.new(Sinatra::Base) - base.template(:foo) { 'template in superclass' } - assert_equal 'template in superclass', base.templates[:foo].first.call - - mock_app(base) do - set :views, File.dirname(__FILE__) + '/views' - template(:foo) { 'template in subclass' } - get('/') { render :test, :foo } - end - assert_equal 'template in subclass', @app.templates[:foo].first.call - - get '/' - assert ok? - assert_equal 'template in subclass', body - end - - it "is possible to use a different engine for the layout than for the template itself explicitly" do - render_app do - settings.template(:layout) { 'Hello <%= yield %>!' } - render :str, "<%= 'World' %>", :layout_engine => :erb - end - assert_equal "Hello <%= 'World' %>!", body - end - - it "is possible to use a different engine for the layout than for the template itself globally" do - render_app :str => { :layout_engine => :erb } do - settings.template(:layout) { 'Hello <%= yield %>!' } - render :str, "<%= 'World' %>" - end - assert_equal "Hello <%= 'World' %>!", body - end - - it "does not leak the content type to the template" do - render_app :str => { :layout_engine => :erb } do - settings.template(:layout) { 'Hello <%= yield %>!' } - render :str, "<%= 'World' %>", :content_type => :txt - end - assert_equal "text/html;charset=utf-8", headers['Content-Type'] - end - - it "is possible to register another template" do - Tilt.register "html.erb", Tilt[:erb] - render_app { render :erb, :calc } - assert_equal '2', body - end - - it "passes scope to the template" do - mock_app do - template(:scoped) { 'Hello <%= foo %>' } - - get('/') do - some_scope = Object.new - def some_scope.foo() 'World!' end - erb :scoped, :scope => some_scope - end - end - - get '/' - assert ok? - assert_equal 'Hello World!', body - end - - it "is possible to use custom logic for finding template files" do - mock_app do - set :views, ["a", "b"].map { |d| File.dirname(__FILE__) + '/views/' + d } - def find_template(views, name, engine, &block) - Array(views).each { |v| super(v, name, engine, &block) } - end - - get('/:name') { render(:str, params[:name].to_sym) } - end - - get '/in_a' - assert_body 'Gimme an A!' - - get '/in_b' - assert_body 'Gimme a B!' - end -end - -# __END__ : this is not the real end of the script. - -__END__ - -@@ foo -this is foo - -@@ bar -There's a space after 'bar'! - -@@ foo bar -this is not foo - -@@ umlaut -Den som tror at hemma det är där man bor har aldrig vart hos mig. - -@@ layout -X -= yield -X diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/textile_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/textile_test.rb deleted file mode 100644 index 907ce63..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/textile_test.rb +++ /dev/null @@ -1,65 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'redcloth' - -class TextileTest < Test::Unit::TestCase - def textile_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline textile strings' do - textile_app { textile('h1. Hiya') } - assert ok? - assert_equal "

Hiya

", body - end - - it 'renders .textile files in views path' do - textile_app { textile(:hello) } - assert ok? - assert_equal "

Hello From Textile

", body - end - - it "raises error if template not found" do - mock_app { get('/') { textile(:no_such_template) } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it "renders with inline layouts" do - mock_app do - layout { 'THIS. IS. #{yield.upcase}!' } - get('/') { textile('Sparta', :layout_engine => :str) } - end - get '/' - assert ok? - assert_like 'THIS. IS.

SPARTA

!', body - end - - it "renders with file layouts" do - textile_app { - textile('Hello World', :layout => :layout2, :layout_engine => :erb) - } - assert ok? - assert_body "ERB Layout!\n

Hello World

" - end - - it "can be used in a nested fashion for partials and whatnot" do - mock_app do - template(:inner) { "hi" } - template(:outer) { "<%= textile :inner %>" } - get('/') { erb :outer } - end - - get '/' - assert ok? - assert_like '

hi

', body - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping textile tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/a/in_a.str b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/a/in_a.str deleted file mode 100644 index 88805dc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/a/in_a.str +++ /dev/null @@ -1 +0,0 @@ -Gimme an A! diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/ascii.erb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/ascii.erb deleted file mode 100644 index 094e6a8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/ascii.erb +++ /dev/null @@ -1,2 +0,0 @@ -This file has no unicode in it! -<%= value %> diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/b/in_b.str b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/b/in_b.str deleted file mode 100644 index 156de21..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/b/in_b.str +++ /dev/null @@ -1 +0,0 @@ -Gimme a B! diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/calc.html.erb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/calc.html.erb deleted file mode 100644 index ff47b84..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/calc.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= 1 + 1 %> \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.builder b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.builder deleted file mode 100644 index 9cf87d5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.builder +++ /dev/null @@ -1,3 +0,0 @@ -xml.error do - raise "goodbye" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.erb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.erb deleted file mode 100644 index b48d1f0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.erb +++ /dev/null @@ -1,3 +0,0 @@ -Hello <%= 'World' %> -<% raise 'Goodbye' unless defined?(french) && french %> -<% raise 'Au revoir' if defined?(french) && french %> diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.haml b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.haml deleted file mode 100644 index 6019007..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.haml +++ /dev/null @@ -1,3 +0,0 @@ -%h1 Hello From Haml -= raise 'goodbye' unless defined?(french) && french -= raise 'au revoir' if defined?(french) && french diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.sass b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.sass deleted file mode 100644 index 42fc56b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/error.sass +++ /dev/null @@ -1,2 +0,0 @@ -#sass - +argle-bargle diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/explicitly_nested.str b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/explicitly_nested.str deleted file mode 100644 index a3b0875..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/explicitly_nested.str +++ /dev/null @@ -1 +0,0 @@ -#{render :str, :hello, :layout => :layout2} \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/foo/hello.test b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/foo/hello.test deleted file mode 100644 index 2aba634..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/foo/hello.test +++ /dev/null @@ -1 +0,0 @@ -from another views directory diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.asciidoc b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.asciidoc deleted file mode 100644 index 1afd160..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.asciidoc +++ /dev/null @@ -1 +0,0 @@ -== Hello from AsciiDoc diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.builder b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.builder deleted file mode 100644 index 16b86d0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.builder +++ /dev/null @@ -1 +0,0 @@ -xml.exclaim "You're my boy, #{@name}!" diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.coffee b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.coffee deleted file mode 100644 index b21e7d6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.coffee +++ /dev/null @@ -1 +0,0 @@ -alert "Aye!" diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.creole b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.creole deleted file mode 100644 index 50db5f8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.creole +++ /dev/null @@ -1 +0,0 @@ -= Hello From Creole diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.erb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.erb deleted file mode 100644 index bcbbc92..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.erb +++ /dev/null @@ -1 +0,0 @@ -Hello <%= 'World' %> diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.haml b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.haml deleted file mode 100644 index d6852a6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.haml +++ /dev/null @@ -1 +0,0 @@ -%h1 Hello From Haml diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.less b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.less deleted file mode 100644 index 9eb99dd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.less +++ /dev/null @@ -1,5 +0,0 @@ -@white_colour: #fff; - -#main { - background-color: @white_colour; -} \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.liquid b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.liquid deleted file mode 100644 index 00d7d26..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.liquid +++ /dev/null @@ -1 +0,0 @@ -

Hello From Liquid

diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.mab b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.mab deleted file mode 100644 index 6e0c9cb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.mab +++ /dev/null @@ -1 +0,0 @@ -h1 "Hello From Markaby" diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.md b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.md deleted file mode 100644 index 31dc9cc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.md +++ /dev/null @@ -1 +0,0 @@ -# Hello From Markdown \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.mediawiki b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.mediawiki deleted file mode 100644 index 55e6513..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.mediawiki +++ /dev/null @@ -1 +0,0 @@ -''Hello from MediaWiki'' diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.nokogiri b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.nokogiri deleted file mode 100644 index 16b86d0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.nokogiri +++ /dev/null @@ -1 +0,0 @@ -xml.exclaim "You're my boy, #{@name}!" diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.rabl b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.rabl deleted file mode 100644 index ebde74d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.rabl +++ /dev/null @@ -1,2 +0,0 @@ -object @foo -attributes :bar diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.radius b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.radius deleted file mode 100644 index 98e35f3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.radius +++ /dev/null @@ -1 +0,0 @@ -

Hello From Radius

diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.rdoc b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.rdoc deleted file mode 100644 index cfba714..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.rdoc +++ /dev/null @@ -1 +0,0 @@ -= Hello From RDoc diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.sass b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.sass deleted file mode 100644 index 090bd4a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.sass +++ /dev/null @@ -1,2 +0,0 @@ -#sass - :background-color white diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.scss b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.scss deleted file mode 100644 index 87d1200..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.scss +++ /dev/null @@ -1,3 +0,0 @@ -#scss { - background-color: white -} \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.slim b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.slim deleted file mode 100644 index 067e671..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.slim +++ /dev/null @@ -1 +0,0 @@ -h1 Hello From Slim diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.str b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.str deleted file mode 100644 index 6c121b3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.str +++ /dev/null @@ -1 +0,0 @@ -

Hello From String

\ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.styl b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.styl deleted file mode 100644 index 3be6744..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.styl +++ /dev/null @@ -1,2 +0,0 @@ -a - margin auto diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.test b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.test deleted file mode 100644 index 980a0d5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.test +++ /dev/null @@ -1 +0,0 @@ -Hello World! diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.textile b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.textile deleted file mode 100644 index 02686a6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.textile +++ /dev/null @@ -1 +0,0 @@ -h1. Hello From Textile diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.wlang b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.wlang deleted file mode 100644 index 43a8650..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.wlang +++ /dev/null @@ -1 +0,0 @@ -Hello from wlang! diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.yajl b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.yajl deleted file mode 100644 index 68ef6a6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/hello.yajl +++ /dev/null @@ -1 +0,0 @@ -json = { :yajl => "hello" } \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.builder b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.builder deleted file mode 100644 index 9491f57..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.builder +++ /dev/null @@ -1,3 +0,0 @@ -xml.layout do - xml << yield -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.erb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.erb deleted file mode 100644 index e097f3b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.erb +++ /dev/null @@ -1,2 +0,0 @@ -ERB Layout! -<%= yield %> diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.haml b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.haml deleted file mode 100644 index 58bfc04..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.haml +++ /dev/null @@ -1,2 +0,0 @@ -%h1 HAML Layout! -%p= yield diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.liquid b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.liquid deleted file mode 100644 index 4b64d4d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.liquid +++ /dev/null @@ -1,2 +0,0 @@ -

Liquid Layout!

-

{{ yield }}

diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.mab b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.mab deleted file mode 100644 index 01da339..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.mab +++ /dev/null @@ -1,2 +0,0 @@ -h1 "Markaby Layout!" -p { yield } diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.nokogiri b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.nokogiri deleted file mode 100644 index 9491f57..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.nokogiri +++ /dev/null @@ -1,3 +0,0 @@ -xml.layout do - xml << yield -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.rabl b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.rabl deleted file mode 100644 index ecd27a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.rabl +++ /dev/null @@ -1,3 +0,0 @@ -node(:qux) do - ::JSON.parse(yield) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.radius b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.radius deleted file mode 100644 index 57a06c0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.radius +++ /dev/null @@ -1,2 +0,0 @@ -

Radius Layout!

-

diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.slim b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.slim deleted file mode 100644 index d296686..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.slim +++ /dev/null @@ -1,3 +0,0 @@ -h1 Slim Layout! -p - == yield diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.str b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.str deleted file mode 100644 index c639181..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.str +++ /dev/null @@ -1,2 +0,0 @@ -

String Layout!

-#{yield} \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.test b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.test deleted file mode 100644 index fb432e3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.test +++ /dev/null @@ -1 +0,0 @@ -Layout 2! diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.wlang b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.wlang deleted file mode 100644 index 6055260..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/layout2.wlang +++ /dev/null @@ -1,2 +0,0 @@ -WLang Layout! -+{yield} diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/nested.str b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/nested.str deleted file mode 100644 index 603038a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/nested.str +++ /dev/null @@ -1 +0,0 @@ -#{render :str, :hello} \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/utf8.erb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/utf8.erb deleted file mode 100644 index de743c5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/views/utf8.erb +++ /dev/null @@ -1,2 +0,0 @@ -

<%= value %>

-Ingen vill veta var du köpt din tröja. diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/wlang_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/wlang_test.rb deleted file mode 100644 index 1ac32e3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/wlang_test.rb +++ /dev/null @@ -1,87 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'wlang' - -class WLangTest < Test::Unit::TestCase - def engine - Tilt::WLangTemplate - end - - def wlang_app(&block) - mock_app { - set :views, File.dirname(__FILE__) + '/views' - get '/', &block - } - get '/' - end - - it 'uses the correct engine' do - assert_equal engine, Tilt[:wlang] - end - - it 'renders .wlang files in views path' do - wlang_app { wlang :hello } - assert ok? - assert_equal "Hello from wlang!\n", body - end - - it 'renders in the app instance scope' do - mock_app do - helpers do - def who; "world"; end - end - get('/') { wlang 'Hello +{who}!' } - end - get '/' - assert ok? - assert_equal 'Hello world!', body - end - - it 'takes a :locals option' do - wlang_app do - locals = {:foo => 'Bar'} - wlang 'Hello ${foo}!', :locals => locals - end - assert ok? - assert_equal 'Hello Bar!', body - end - - it "renders with inline layouts" do - mock_app do - layout { 'THIS. IS. +{yield.upcase}!' } - get('/') { wlang 'Sparta' } - end - get '/' - assert ok? - assert_equal 'THIS. IS. SPARTA!', body - end - - it "renders with file layouts" do - wlang_app { wlang 'Hello World', :layout => :layout2 } - assert ok? - assert_body "WLang Layout!\nHello World" - end - - it "can rendered truly nested layouts by accepting a layout and a block with the contents" do - mock_app do - template(:main_outer_layout) { "

Title

\n>{ yield }" } - template(:an_inner_layout) { "

Subtitle

\n>{ yield }" } - template(:a_page) { "

Contents.

\n" } - get('/') do - wlang :main_outer_layout, :layout => false do - wlang :an_inner_layout do - wlang :a_page - end - end - end - end - get '/' - assert ok? - assert_body "

Title

\n

Subtitle

\n

Contents.

\n" - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping wlang tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/yajl_test.rb b/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/yajl_test.rb deleted file mode 100644 index 69a7d14..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/sinatra-1.4.5/test/yajl_test.rb +++ /dev/null @@ -1,86 +0,0 @@ -require File.expand_path('../helper', __FILE__) - -begin -require 'yajl' - -class YajlTest < Test::Unit::TestCase - def yajl_app(&block) - mock_app do - set :views, File.dirname(__FILE__) + '/views' - get('/', &block) - end - get '/' - end - - it 'renders inline Yajl strings' do - yajl_app { yajl('json = { :foo => "bar" }') } - assert ok? - assert_body '{"foo":"bar"}' - end - - it 'renders .yajl files in views path' do - yajl_app { yajl(:hello) } - assert ok? - assert_body '{"yajl":"hello"}' - end - - it 'raises error if template not found' do - mock_app { get('/') { yajl(:no_such_template) } } - assert_raise(Errno::ENOENT) { get('/') } - end - - it 'accepts a :locals option' do - yajl_app do - locals = { :object => { :foo => 'bar' } } - yajl 'json = object', :locals => locals - end - assert ok? - assert_body '{"foo":"bar"}' - end - - it 'accepts a :scope option' do - yajl_app do - scope = { :object => { :foo => 'bar' } } - yajl 'json = self[:object]', :scope => scope - end - assert ok? - assert_body '{"foo":"bar"}' - end - - it 'decorates the json with a callback' do - yajl_app do - yajl( - 'json = { :foo => "bar" }', - { :callback => 'baz' } - ) - end - assert ok? - assert_body 'baz({"foo":"bar"});' - end - - it 'decorates the json with a variable' do - yajl_app do - yajl( - 'json = { :foo => "bar" }', - { :variable => 'qux' } - ) - end - assert ok? - assert_body 'var qux = {"foo":"bar"};' - end - - it 'decorates the json with a callback and a variable' do - yajl_app do - yajl( - 'json = { :foo => "bar" }', - { :callback => 'baz', :variable => 'qux' } - ) - end - assert ok? - assert_body 'var qux = {"foo":"bar"}; baz(qux);' - end -end - -rescue LoadError - warn "#{$!.to_s}: skipping yajl tests" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/.document b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/.document deleted file mode 100644 index 3ce5450..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/.document +++ /dev/null @@ -1,5 +0,0 @@ -lib/*.rb -lib/**/*.rb -- -CHANGELOG.rdoc -LICENSE.md diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/CHANGELOG.md b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/CHANGELOG.md deleted file mode 100644 index 38687db..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/CHANGELOG.md +++ /dev/null @@ -1,139 +0,0 @@ -## 0.18.1, release 2013-03-30 -* Revert regressions found in 0.18.0 - -## 0.18.0, release 2013-03-26 -* Remove rake2thor -* Only display colors if output medium supports colors -* Pass parent_options to subcommands -* Fix non-dash-prefixed aliases -* Make error messages more helpful -* Rename "task" to "command" -* Add the method to allow for custom package name - -## 0.17.0, release 2013-01-24 -* Add better support for tasks that accept arbitrary additional arguments (e.g. things like `bundle exec`) -* Add #stop_on_unknown_option! -* Only strip from stdin.gets if it wasn't ended with EOF -* Allow "send" as a task name -* Allow passing options as arguments after "--" -* Autoload Thor::Group - -## 0.16.0, release 2012-08-14 -* Add enum to string arguments - -## 0.15.4, release 2012-06-29 -* Fix regression when destination root contains reserved regexp characters - -## 0.15.3, release 2012-06-18 -* Support strict_args_position! for backwards compatibility -* Escape Dir glob characters in paths - -## 0.15.2, released 2012-05-07 -* Added print_in_columns -* Exposed terminal_width as a public API - -## 0.15.1, release 2012-05-06 -* Fix Ruby 1.8 truncation bug with unicode chars -* Fix shell delegate methods to pass their block -* Don't output trailing spaces when printing the last column in a table - -## 0.15, released 2012-04-29 -* Alias method_options to options -* Refactor say to allow multiple colors -* Exposed error as a public API -* Exposed file_collision as a public API -* Exposed print_wrapped as a public API -* Exposed set_color as a public API -* Fix number-formatting bugs in print_table -* Fix "indent" typo in print_table -* Fix Errno::EPIPE when piping tasks to `head` -* More friendly error messages - -## 0.14, released 2010-07-25 -* Added CreateLink class and #link_file method -* Made Thor::Actions#run use system as default method for system calls -* Allow use of private methods from superclass as tasks -* Added mute(&block) method which allows to run block without any output -* Removed config[:pretend] -* Enabled underscores for command line switches -* Added Thor::Base.basename which is used by both Thor.banner and Thor::Group.banner -* Deprecated invoke() without arguments -* Added :only and :except to check_unknown_options - -## 0.13, released 2010-02-03 -* Added :lazy_default which is only triggered if a switch is given -* Added Thor::Shell::HTML -* Added subcommands -* Decoupled Thor::Group and Thor, so it's easier to vendor -* Added check_unknown_options! in case you want error messages to be raised in valid switches -* run(command) should return the results of command - -## 0.12, released 2010-01-02 -* Methods generated by attr_* are automatically not marked as tasks -* inject_into_file does not add the same content twice, unless :force is set -* Removed rr in favor to rspec mock framework -* Improved output for thor -T -* [#7] Do not force white color on status -* [#8] Yield a block with the filename on directory - -## 0.11, released 2009-07-01 -* Added a rake compatibility layer. It allows you to use spec and rdoc tasks on - Thor classes. -* BACKWARDS INCOMPATIBLE: aliases are not generated automatically anymore - since it may cause wrong behavior in the invocation system. -* thor help now show information about any class/task. All those calls are - possible: - - thor help describe - thor help describe:amazing - Or even with default namespaces: - - thor help :spec -* Thor::Runner now invokes the default task if none is supplied: - - thor describe # invokes the default task, usually help -* Thor::Runner now works with mappings: - - thor describe -h -* Added some documentation and code refactoring. - -## 0.9.8, released 2008-10-20 -* Fixed some tiny issues that were introduced lately. - -## 0.9.7, released 2008-10-13 -* Setting global method options on the initialize method works as expected: - All other tasks will accept these global options in addition to their own. -* Added 'group' notion to Thor task sets (class Thor); by default all tasks - are in the 'standard' group. Running 'thor -T' will only show the standard - tasks - adding --all will show all tasks. You can also filter on a specific - group using the --group option: thor -T --group advanced - -## 0.9.6, released 2008-09-13 -* Generic improvements - -## 0.9.5, released 2008-08-27 -* Improve Windows compatibility -* Update (incorrect) README and task.thor sample file -* Options hash is now frozen (once returned) -* Allow magic predicates on options object. For instance: `options.force?` -* Add support for :numeric type -* BACKWARDS INCOMPATIBLE: Refactor Thor::Options. You cannot access shorthand forms in options hash anymore (for instance, options[:f]) -* Allow specifying optional args with default values: method_options(:user => "mislav") -* Don't write options for nil or false values. This allows, for example, turning color off when running specs. -* Exit with the status of the spec command to help CI stuff out some. - -## 0.9.4, released 2008-08-13 -* Try to add Windows compatibility. -* BACKWARDS INCOMPATIBLE: options hash is now accessed as a property in your class and is not passed as last argument anymore -* Allow options at the beginning of the argument list as well as the end. -* Make options available with symbol keys in addition to string keys. -* Allow true to be passed to Thor#method_options to denote a boolean option. -* If loading a thor file fails, don't give up, just print a warning and keep going. -* Make sure that we re-raise errors if they happened further down the pipe than we care about. -* Only delete the old file on updating when the installation of the new one is a success -* Make it Ruby 1.8.5 compatible. -* Don't raise an error if a boolean switch is defined multiple times. -* Thor::Options now doesn't parse through things that look like options but aren't. -* Add URI detection to install task, and make sure we don't append ".thor" to URIs -* Add rake2thor to the gem binfiles. -* Make sure local Thorfiles override system-wide ones. diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/LICENSE.md b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/LICENSE.md deleted file mode 100644 index ef80540..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/LICENSE.md +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008 Yehuda Katz, Eric Hodel, et al. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/README.md b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/README.md deleted file mode 100644 index 74d5144..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/README.md +++ /dev/null @@ -1,41 +0,0 @@ -Thor -==== - -[![Gem Version](http://img.shields.io/gem/v/thor.svg)][gem] -[![Build Status](http://img.shields.io/travis/erikhuda/thor.svg)][travis] -[![Dependency Status](http://img.shields.io/gemnasium/erikhuda/thor.svg)][gemnasium] -[![Code Climate](http://img.shields.io/codeclimate/github/erikhuda/thor.svg)][codeclimate] -[![Coverage Status](http://img.shields.io/coveralls/erikhuda/thor.svg)][coveralls] - -[gem]: https://rubygems.org/gems/thor -[travis]: http://travis-ci.org/erikhuda/thor -[gemnasium]: https://gemnasium.com/erikhuda/thor -[codeclimate]: https://codeclimate.com/github/erikhuda/thor -[coveralls]: https://coveralls.io/r/erikhuda/thor - -Description ------------ -Thor is a simple and efficient tool for building self-documenting command line -utilities. It removes the pain of parsing command line options, writing -"USAGE:" banners, and can also be used as an alternative to the [Rake][rake] -build tool. The syntax is Rake-like, so it should be familiar to most Rake -users. - -[rake]: https://github.com/jimweirich/rake - -Installation ------------- - gem install thor - -Usage and documentation ------------------------ -Please see the [wiki][] for basic usage and other documentation on using Thor. You can also checkout the [official homepage][homepage]. - -[wiki]: https://github.com/erikhuda/thor/wiki -[homepage]: http://whatisthor.com/ - -License -------- -Released under the MIT License. See the [LICENSE][] file for further details. - -[license]: LICENSE.md diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/Thorfile b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/Thorfile deleted file mode 100644 index 3b2df55..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/Thorfile +++ /dev/null @@ -1,29 +0,0 @@ -$LOAD_PATH.unshift File.expand_path("../lib", __FILE__) - -require "bundler" -require "thor/rake_compat" - -class Default < Thor - include Thor::RakeCompat - Bundler::GemHelper.install_tasks - - desc "build", "Build thor-#{Thor::VERSION}.gem into the pkg directory" - def build - Rake::Task["build"].execute - end - - desc "install", "Build and install thor-#{Thor::VERSION}.gem into system gems" - def install - Rake::Task["install"].execute - end - - desc "release", "Create tag v#{Thor::VERSION} and build and push thor-#{Thor::VERSION}.gem to Rubygems" - def release - Rake::Task["release"].execute - end - - desc "spec", "Run RSpec code examples" - def spec - exec "rspec spec" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/bin/thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/bin/thor deleted file mode 100755 index 76e3a94..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/bin/thor +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env ruby -# -*- mode: ruby -*- - -require "thor/runner" -$thor_runner = true -Thor::Runner.start diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor.rb deleted file mode 100644 index d687d3b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor.rb +++ /dev/null @@ -1,484 +0,0 @@ -require "set" -require "thor/base" - -class Thor # rubocop:disable ClassLength - class << self - # Allows for custom "Command" package naming. - # - # === Parameters - # name - # options - # - def package_name(name, options = {}) - @package_name = name.nil? || name == "" ? nil : name - end - - # Sets the default command when thor is executed without an explicit command to be called. - # - # ==== Parameters - # meth:: name of the default command - # - def default_command(meth = nil) - if meth - @default_command = meth == :none ? "help" : meth.to_s - else - @default_command ||= from_superclass(:default_command, "help") - end - end - alias_method :default_task, :default_command - - # Registers another Thor subclass as a command. - # - # ==== Parameters - # klass:: Thor subclass to register - # command:: Subcommand name to use - # usage:: Short usage for the subcommand - # description:: Description for the subcommand - def register(klass, subcommand_name, usage, description, options = {}) - if klass <= Thor::Group - desc usage, description, options - define_method(subcommand_name) { |*args| invoke(klass, args) } - else - desc usage, description, options - subcommand subcommand_name, klass - end - end - - # Defines the usage and the description of the next command. - # - # ==== Parameters - # usage - # description - # options - # - def desc(usage, description, options = {}) - if options[:for] - command = find_and_refresh_command(options[:for]) - command.usage = usage if usage - command.description = description if description - else - @usage, @desc, @hide = usage, description, options[:hide] || false - end - end - - # Defines the long description of the next command. - # - # ==== Parameters - # long description - # - def long_desc(long_description, options = {}) - if options[:for] - command = find_and_refresh_command(options[:for]) - command.long_description = long_description if long_description - else - @long_desc = long_description - end - end - - # Maps an input to a command. If you define: - # - # map "-T" => "list" - # - # Running: - # - # thor -T - # - # Will invoke the list command. - # - # ==== Parameters - # Hash[String|Array => Symbol]:: Maps the string or the strings in the array to the given command. - # - def map(mappings = nil) - @map ||= from_superclass(:map, {}) - - if mappings - mappings.each do |key, value| - if key.respond_to?(:each) - key.each { |subkey| @map[subkey] = value } - else - @map[key] = value - end - end - end - - @map - end - - # Declares the options for the next command to be declared. - # - # ==== Parameters - # Hash[Symbol => Object]:: The hash key is the name of the option and the value - # is the type of the option. Can be :string, :array, :hash, :boolean, :numeric - # or :required (string). If you give a value, the type of the value is used. - # - def method_options(options = nil) - @method_options ||= {} - build_options(options, @method_options) if options - @method_options - end - - alias_method :options, :method_options - - # Adds an option to the set of method options. If :for is given as option, - # it allows you to change the options from a previous defined command. - # - # def previous_command - # # magic - # end - # - # method_option :foo => :bar, :for => :previous_command - # - # def next_command - # # magic - # end - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described below. - # - # ==== Options - # :desc - Description for the argument. - # :required - If the argument is required or not. - # :default - Default value for this argument. It cannot be required and have default values. - # :aliases - Aliases for this option. - # :type - The type of the argument, can be :string, :hash, :array, :numeric or :boolean. - # :banner - String to show on usage notes. - # :hide - If you want to hide this option from the help. - # - def method_option(name, options = {}) - scope = if options[:for] - find_and_refresh_command(options[:for]).options - else - method_options - end - - build_option(name, options, scope) - end - alias_method :option, :method_option - - # Prints help information for the given command. - # - # ==== Parameters - # shell - # command_name - # - def command_help(shell, command_name) - meth = normalize_command_name(command_name) - command = all_commands[meth] - handle_no_command_error(meth) unless command - - shell.say "Usage:" - shell.say " #{banner(command)}" - shell.say - class_options_help(shell, nil => command.options.map { |_, o| o }) - if command.long_description - shell.say "Description:" - shell.print_wrapped(command.long_description, :indent => 2) - else - shell.say command.description - end - end - alias_method :task_help, :command_help - - # Prints help information for this class. - # - # ==== Parameters - # shell - # - def help(shell, subcommand = false) - list = printable_commands(true, subcommand) - Thor::Util.thor_classes_in(self).each do |klass| - list += klass.printable_commands(false) - end - list.sort! { |a, b| a[0] <=> b[0] } - - if defined?(@package_name) && @package_name - shell.say "#{@package_name} commands:" - else - shell.say "Commands:" - end - - shell.print_table(list, :indent => 2, :truncate => true) - shell.say - class_options_help(shell) - end - - # Returns commands ready to be printed. - def printable_commands(all = true, subcommand = false) - (all ? all_commands : commands).map do |_, command| - next if command.hidden? - item = [] - item << banner(command, false, subcommand) - item << (command.description ? "# #{command.description.gsub(/\s+/m, ' ')}" : "") - item - end.compact - end - alias_method :printable_tasks, :printable_commands - - def subcommands - @subcommands ||= from_superclass(:subcommands, []) - end - alias_method :subtasks, :subcommands - - def subcommand_classes - @subcommand_classes ||= {} - end - - def subcommand(subcommand, subcommand_class) - subcommands << subcommand.to_s - subcommand_class.subcommand_help subcommand - subcommand_classes[subcommand.to_s] = subcommand_class - - define_method(subcommand) do |*args| - args, opts = Thor::Arguments.split(args) - args.unshift("help") if opts.include? "--help" or opts.include? "-h" - invoke subcommand_class, args, opts, :invoked_via_subcommand => true, :class_options => options - end - end - alias_method :subtask, :subcommand - - # Extend check unknown options to accept a hash of conditions. - # - # === Parameters - # options: A hash containing :only and/or :except keys - def check_unknown_options!(options = {}) - @check_unknown_options ||= {} - options.each do |key, value| - if value - @check_unknown_options[key] = Array(value) - else - @check_unknown_options.delete(key) - end - end - @check_unknown_options - end - - # Overwrite check_unknown_options? to take subcommands and options into account. - def check_unknown_options?(config) #:nodoc: - options = check_unknown_options - return false unless options - - command = config[:current_command] - return true unless command - - name = command.name - - if subcommands.include?(name) - false - elsif options[:except] - !options[:except].include?(name.to_sym) - elsif options[:only] - options[:only].include?(name.to_sym) - else - true - end - end - - # Stop parsing of options as soon as an unknown option or a regular - # argument is encountered. All remaining arguments are passed to the command. - # This is useful if you have a command that can receive arbitrary additional - # options, and where those additional options should not be handled by - # Thor. - # - # ==== Example - # - # To better understand how this is useful, let's consider a command that calls - # an external command. A user may want to pass arbitrary options and - # arguments to that command. The command itself also accepts some options, - # which should be handled by Thor. - # - # class_option "verbose", :type => :boolean - # stop_on_unknown_option! :exec - # check_unknown_options! :except => :exec - # - # desc "exec", "Run a shell command" - # def exec(*args) - # puts "diagnostic output" if options[:verbose] - # Kernel.exec(*args) - # end - # - # Here +exec+ can be called with +--verbose+ to get diagnostic output, - # e.g.: - # - # $ thor exec --verbose echo foo - # diagnostic output - # foo - # - # But if +--verbose+ is given after +echo+, it is passed to +echo+ instead: - # - # $ thor exec echo --verbose foo - # --verbose foo - # - # ==== Parameters - # Symbol ...:: A list of commands that should be affected. - def stop_on_unknown_option!(*command_names) - stop_on_unknown_option.merge(command_names) - end - - def stop_on_unknown_option?(command) #:nodoc: - command && stop_on_unknown_option.include?(command.name.to_sym) - end - - protected - def stop_on_unknown_option #:nodoc: - @stop_on_unknown_option ||= Set.new - end - - # The method responsible for dispatching given the args. - def dispatch(meth, given_args, given_opts, config) #:nodoc: # rubocop:disable MethodLength - meth ||= retrieve_command_name(given_args) - command = all_commands[normalize_command_name(meth)] - - if !command && config[:invoked_via_subcommand] - # We're a subcommand and our first argument didn't match any of our - # commands. So we put it back and call our default command. - given_args.unshift(meth) - command = all_commands[normalize_command_name(default_command)] - end - - if command - args, opts = Thor::Options.split(given_args) - if stop_on_unknown_option?(command) && !args.empty? - # given_args starts with a non-option, so we treat everything as - # ordinary arguments - args.concat opts - opts.clear - end - else - args, opts = given_args, nil - command = dynamic_command_class.new(meth) - end - - opts = given_opts || opts || [] - config.merge!(:current_command => command, :command_options => command.options) - - instance = new(args, opts, config) - yield instance if block_given? - args = instance.args - trailing = args[Range.new(arguments.size, -1)] - instance.invoke_command(command, trailing || []) - end - - # The banner for this class. You can customize it if you are invoking the - # thor class by another ways which is not the Thor::Runner. It receives - # the command that is going to be invoked and a boolean which indicates if - # the namespace should be displayed as arguments. - # - def banner(command, namespace = nil, subcommand = false) - "#{basename} #{command.formatted_usage(self, $thor_runner, subcommand)}" - end - - def baseclass #:nodoc: - Thor - end - - def dynamic_command_class #:nodoc: - Thor::DynamicCommand - end - - def create_command(meth) #:nodoc: - @usage ||= nil - @desc ||= nil - @long_desc ||= nil - - if @usage && @desc - base_class = @hide ? Thor::HiddenCommand : Thor::Command - commands[meth] = base_class.new(meth, @desc, @long_desc, @usage, method_options) - @usage, @desc, @long_desc, @method_options, @hide = nil - true - elsif all_commands[meth] || meth == "method_missing" - true - else - puts "[WARNING] Attempted to create command #{meth.inspect} without usage or description. " << - "Call desc if you want this method to be available as command or declare it inside a " << - "no_commands{} block. Invoked from #{caller[1].inspect}." - false - end - end - alias_method :create_task, :create_command - - def initialize_added #:nodoc: - class_options.merge!(method_options) - @method_options = nil - end - - # Retrieve the command name from given args. - def retrieve_command_name(args) #:nodoc: - meth = args.first.to_s unless args.empty? - if meth && (map[meth] || meth !~ /^\-/) - args.shift - else - nil - end - end - alias_method :retrieve_task_name, :retrieve_command_name - - # receives a (possibly nil) command name and returns a name that is in - # the commands hash. In addition to normalizing aliases, this logic - # will determine if a shortened command is an unambiguous substring of - # a command or alias. - # - # +normalize_command_name+ also converts names like +animal-prison+ - # into +animal_prison+. - def normalize_command_name(meth) #:nodoc: - return default_command.to_s.gsub("-", "_") unless meth - - possibilities = find_command_possibilities(meth) - if possibilities.size > 1 - fail AmbiguousTaskError, "Ambiguous command #{meth} matches [#{possibilities.join(', ')}]" - elsif possibilities.size < 1 - meth = meth || default_command - elsif map[meth] - meth = map[meth] - else - meth = possibilities.first - end - - meth.to_s.gsub("-", "_") # treat foo-bar as foo_bar - end - alias_method :normalize_task_name, :normalize_command_name - - # this is the logic that takes the command name passed in by the user - # and determines whether it is an unambiguous substrings of a command or - # alias name. - def find_command_possibilities(meth) - len = meth.to_s.length - possibilities = all_commands.merge(map).keys.select { |n| meth == n[0, len] }.sort - unique_possibilities = possibilities.map { |k| map[k] || k }.uniq - - if possibilities.include?(meth) - [meth] - elsif unique_possibilities.size == 1 - unique_possibilities - else - possibilities - end - end - alias_method :find_task_possibilities, :find_command_possibilities - - def subcommand_help(cmd) - desc "help [COMMAND]", "Describe subcommands or one specific subcommand" - class_eval " - def help(command = nil, subcommand = true); super; end -" - end - alias_method :subtask_help, :subcommand_help - end - - include Thor::Base - - map HELP_MAPPINGS => :help - - desc "help [COMMAND]", "Describe available commands or one specific command" - def help(command = nil, subcommand = false) - if command - if self.class.subcommands.include? command - self.class.subcommand_classes[command].help(shell, true) - else - self.class.command_help(shell, command) - end - else - self.class.help(shell, subcommand) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions.rb deleted file mode 100644 index b08046b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions.rb +++ /dev/null @@ -1,319 +0,0 @@ -require "fileutils" -require "uri" -require "thor/core_ext/io_binary_read" -require "thor/actions/create_file" -require "thor/actions/create_link" -require "thor/actions/directory" -require "thor/actions/empty_directory" -require "thor/actions/file_manipulation" -require "thor/actions/inject_into_file" - -class Thor - module Actions - attr_accessor :behavior - - def self.included(base) #:nodoc: - base.extend ClassMethods - end - - module ClassMethods - # Hold source paths for one Thor instance. source_paths_for_search is the - # method responsible to gather source_paths from this current class, - # inherited paths and the source root. - # - def source_paths - @_source_paths ||= [] - end - - # Stores and return the source root for this class - def source_root(path = nil) - @_source_root = path if path - @_source_root ||= nil - end - - # Returns the source paths in the following order: - # - # 1) This class source paths - # 2) Source root - # 3) Parents source paths - # - def source_paths_for_search - paths = [] - paths += source_paths - paths << source_root if source_root - paths += from_superclass(:source_paths, []) - paths - end - - # Add runtime options that help actions execution. - # - def add_runtime_options! - class_option :force, :type => :boolean, :aliases => "-f", :group => :runtime, - :desc => "Overwrite files that already exist" - - class_option :pretend, :type => :boolean, :aliases => "-p", :group => :runtime, - :desc => "Run but do not make any changes" - - class_option :quiet, :type => :boolean, :aliases => "-q", :group => :runtime, - :desc => "Suppress status output" - - class_option :skip, :type => :boolean, :aliases => "-s", :group => :runtime, - :desc => "Skip files that already exist" - end - end - - # Extends initializer to add more configuration options. - # - # ==== Configuration - # behavior:: The actions default behavior. Can be :invoke or :revoke. - # It also accepts :force, :skip and :pretend to set the behavior - # and the respective option. - # - # destination_root:: The root directory needed for some actions. - # - def initialize(args = [], options = {}, config = {}) - self.behavior = case config[:behavior].to_s - when "force", "skip" - _cleanup_options_and_set(options, config[:behavior]) - :invoke - when "revoke" - :revoke - else - :invoke - end - super - self.destination_root = config[:destination_root] - end - - # Wraps an action object and call it accordingly to the thor class behavior. - # - def action(instance) #:nodoc: - if behavior == :revoke - instance.revoke! - else - instance.invoke! - end - end - - # Returns the root for this thor class (also aliased as destination root). - # - def destination_root - @destination_stack.last - end - - # Sets the root for this thor class. Relatives path are added to the - # directory where the script was invoked and expanded. - # - def destination_root=(root) - @destination_stack ||= [] - @destination_stack[0] = File.expand_path(root || "") - end - - # Returns the given path relative to the absolute root (ie, root where - # the script started). - # - def relative_to_original_destination_root(path, remove_dot = true) - path = path.dup - if path.gsub!(@destination_stack[0], ".") - remove_dot ? (path[2..-1] || "") : path - else - path - end - end - - # Holds source paths in instance so they can be manipulated. - # - def source_paths - @source_paths ||= self.class.source_paths_for_search - end - - # Receives a file or directory and search for it in the source paths. - # - def find_in_source_paths(file) # rubocop:disable MethodLength - possible_files = [file, file + TEMPLATE_EXTNAME] - relative_root = relative_to_original_destination_root(destination_root, false) - - source_paths.each do |source| - possible_files.each do |f| - source_file = File.expand_path(f, File.join(source, relative_root)) - return source_file if File.exist?(source_file) - end - end - - message = "Could not find #{file.inspect} in any of your source paths. " - - unless self.class.source_root - message << "Please invoke #{self.class.name}.source_root(PATH) with the PATH containing your templates. " - end - - if source_paths.empty? - message << "Currently you have no source paths." - else - message << "Your current source paths are: \n#{source_paths.join("\n")}" - end - - fail Error, message - end - - # Do something in the root or on a provided subfolder. If a relative path - # is given it's referenced from the current root. The full path is yielded - # to the block you provide. The path is set back to the previous path when - # the method exits. - # - # ==== Parameters - # dir:: the directory to move to. - # config:: give :verbose => true to log and use padding. - # - def inside(dir = "", config = {}, &block) - verbose = config.fetch(:verbose, false) - pretend = options[:pretend] - - say_status :inside, dir, verbose - shell.padding += 1 if verbose - @destination_stack.push File.expand_path(dir, destination_root) - - # If the directory doesnt exist and we're not pretending - if !File.exist?(destination_root) && !pretend - FileUtils.mkdir_p(destination_root) - end - - if pretend - # In pretend mode, just yield down to the block - block.arity == 1 ? yield(destination_root) : yield - else - FileUtils.cd(destination_root) { block.arity == 1 ? yield(destination_root) : yield } - end - - @destination_stack.pop - shell.padding -= 1 if verbose - end - - # Goes to the root and execute the given block. - # - def in_root - inside(@destination_stack.first) { yield } - end - - # Loads an external file and execute it in the instance binding. - # - # ==== Parameters - # path:: The path to the file to execute. Can be a web address or - # a relative path from the source root. - # - # ==== Examples - # - # apply "http://gist.github.com/103208" - # - # apply "recipes/jquery.rb" - # - def apply(path, config = {}) - verbose = config.fetch(:verbose, true) - is_uri = path =~ %r{^https?\://} - path = find_in_source_paths(path) unless is_uri - - say_status :apply, path, verbose - shell.padding += 1 if verbose - - if is_uri - contents = open(path, "Accept" => "application/x-thor-template") { |io| io.read } - else - contents = open(path) { |io| io.read } - end - - instance_eval(contents, path) - shell.padding -= 1 if verbose - end - - # Executes a command returning the contents of the command. - # - # ==== Parameters - # command:: the command to be executed. - # config:: give :verbose => false to not log the status, :capture => true to hide to output. Specify :with - # to append an executable to command execution. - # - # ==== Example - # - # inside('vendor') do - # run('ln -s ~/edge rails') - # end - # - def run(command, config = {}) - return unless behavior == :invoke - - destination = relative_to_original_destination_root(destination_root, false) - desc = "#{command} from #{destination.inspect}" - - if config[:with] - desc = "#{File.basename(config[:with].to_s)} #{desc}" - command = "#{config[:with]} #{command}" - end - - say_status :run, desc, config.fetch(:verbose, true) - - unless options[:pretend] - config[:capture] ? `#{command}` : system("#{command}") - end - end - - # Executes a ruby script (taking into account WIN32 platform quirks). - # - # ==== Parameters - # command:: the command to be executed. - # config:: give :verbose => false to not log the status. - # - def run_ruby_script(command, config = {}) - return unless behavior == :invoke - run command, config.merge(:with => Thor::Util.ruby_command) - end - - # Run a thor command. A hash of options can be given and it's converted to - # switches. - # - # ==== Parameters - # command:: the command to be invoked - # args:: arguments to the command - # config:: give :verbose => false to not log the status, :capture => true to hide to output. - # Other options are given as parameter to Thor. - # - # - # ==== Examples - # - # thor :install, "http://gist.github.com/103208" - # #=> thor install http://gist.github.com/103208 - # - # thor :list, :all => true, :substring => 'rails' - # #=> thor list --all --substring=rails - # - def thor(command, *args) - config = args.last.is_a?(Hash) ? args.pop : {} - verbose = config.key?(:verbose) ? config.delete(:verbose) : true - pretend = config.key?(:pretend) ? config.delete(:pretend) : false - capture = config.key?(:capture) ? config.delete(:capture) : false - - args.unshift(command) - args.push Thor::Options.to_switches(config) - command = args.join(" ").strip - - run command, :with => :thor, :verbose => verbose, :pretend => pretend, :capture => capture - end - - protected - - # Allow current root to be shared between invocations. - # - def _shared_configuration #:nodoc: - super.merge!(:destination_root => destination_root) - end - - def _cleanup_options_and_set(options, key) #:nodoc: - case options - when Array - %w[--force -f --skip -s].each { |i| options.delete(i) } - options << "--#{key}" - when Hash - [:force, :skip, "force", "skip"].each { |i| options.delete(i) } - options.merge!(key => true) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/create_file.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/create_file.rb deleted file mode 100644 index fcea392..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/create_file.rb +++ /dev/null @@ -1,103 +0,0 @@ -require "thor/actions/empty_directory" - -class Thor - module Actions - # Create a new file relative to the destination root with the given data, - # which is the return value of a block or a data string. - # - # ==== Parameters - # destination:: the relative path to the destination root. - # data:: the data to append to the file. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # create_file "lib/fun_party.rb" do - # hostname = ask("What is the virtual hostname I should use?") - # "vhost.name = #{hostname}" - # end - # - # create_file "config/apache.conf", "your apache config" - # - def create_file(destination, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - data = args.first - action CreateFile.new(self, destination, block || data.to_s, config) - end - alias_method :add_file, :create_file - - # CreateFile is a subset of Template, which instead of rendering a file with - # ERB, it gets the content from the user. - # - class CreateFile < EmptyDirectory #:nodoc: - attr_reader :data - - def initialize(base, destination, data, config = {}) - @data = data - super(base, destination, config) - end - - # Checks if the content of the file at the destination is identical to the rendered result. - # - # ==== Returns - # Boolean:: true if it is identical, false otherwise. - # - def identical? - exists? && File.binread(destination) == render - end - - # Holds the content to be added to the file. - # - def render - @render ||= if data.is_a?(Proc) - data.call - else - data - end - end - - def invoke! - invoke_with_conflict_check do - FileUtils.mkdir_p(File.dirname(destination)) - File.open(destination, "wb") { |f| f.write render } - end - given_destination - end - - protected - - # Now on conflict we check if the file is identical or not. - # - def on_conflict_behavior(&block) - if identical? - say_status :identical, :blue - else - options = base.options.merge(config) - force_or_skip_or_conflict(options[:force], options[:skip], &block) - end - end - - # If force is true, run the action, otherwise check if it's not being - # skipped. If both are false, show the file_collision menu, if the menu - # returns true, force it, otherwise skip. - # - def force_or_skip_or_conflict(force, skip, &block) - if force - say_status :force, :yellow - block.call unless pretend? - elsif skip - say_status :skip, :yellow - else - say_status :conflict, :red - force_or_skip_or_conflict(force_on_collision?, true, &block) - end - end - - # Shows the file collision menu to the user and gets the result. - # - def force_on_collision? - base.shell.file_collision(destination) { render } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/create_link.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/create_link.rb deleted file mode 100644 index db2c2a8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/create_link.rb +++ /dev/null @@ -1,59 +0,0 @@ -require "thor/actions/create_file" - -class Thor - module Actions - # Create a new file relative to the destination root from the given source. - # - # ==== Parameters - # destination:: the relative path to the destination root. - # source:: the relative path to the source root. - # config:: give :verbose => false to not log the status. - # :: give :symbolic => false for hard link. - # - # ==== Examples - # - # create_link "config/apache.conf", "/etc/apache.conf" - # - def create_link(destination, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - source = args.first - action CreateLink.new(self, destination, source, config) - end - alias_method :add_link, :create_link - - # CreateLink is a subset of CreateFile, which instead of taking a block of - # data, just takes a source string from the user. - # - class CreateLink < CreateFile #:nodoc: - attr_reader :data - - # Checks if the content of the file at the destination is identical to the rendered result. - # - # ==== Returns - # Boolean:: true if it is identical, false otherwise. - # - def identical? - exists? && File.identical?(render, destination) - end - - def invoke! - invoke_with_conflict_check do - FileUtils.mkdir_p(File.dirname(destination)) - # Create a symlink by default - config[:symbolic] = true if config[:symbolic].nil? - File.unlink(destination) if exists? - if config[:symbolic] - File.symlink(render, destination) - else - File.link(render, destination) - end - end - given_destination - end - - def exists? - super || File.symlink?(destination) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/directory.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/directory.rb deleted file mode 100644 index 9c44cfb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/directory.rb +++ /dev/null @@ -1,118 +0,0 @@ -require "thor/actions/empty_directory" - -class Thor - module Actions - # Copies recursively the files from source directory to root directory. - # If any of the files finishes with .tt, it's considered to be a template - # and is placed in the destination without the extension .tt. If any - # empty directory is found, it's copied and all .empty_directory files are - # ignored. If any file name is wrapped within % signs, the text within - # the % signs will be executed as a method and replaced with the returned - # value. Let's suppose a doc directory with the following files: - # - # doc/ - # components/.empty_directory - # README - # rdoc.rb.tt - # %app_name%.rb - # - # When invoked as: - # - # directory "doc" - # - # It will create a doc directory in the destination with the following - # files (assuming that the `app_name` method returns the value "blog"): - # - # doc/ - # components/ - # README - # rdoc.rb - # blog.rb - # - # Encoded path note: Since Thor internals use Object#respond_to? to check if it can - # expand %something%, this `something` should be a public method in the class calling - # #directory. If a method is private, Thor stack raises PrivateMethodEncodedError. - # - # ==== Parameters - # source:: the relative path to the source root. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # If :recursive => false, does not look for paths recursively. - # If :mode => :preserve, preserve the file mode from the source. - # If :exclude_pattern => /regexp/, prevents copying files that match that regexp. - # - # ==== Examples - # - # directory "doc" - # directory "doc", "docs", :recursive => false - # - def directory(source, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - destination = args.first || source - action Directory.new(self, source, destination || source, config, &block) - end - - class Directory < EmptyDirectory #:nodoc: - attr_reader :source - - def initialize(base, source, destination = nil, config = {}, &block) - @source = File.expand_path(base.find_in_source_paths(source.to_s)) - @block = block - super(base, destination, {:recursive => true}.merge(config)) - end - - def invoke! - base.empty_directory given_destination, config - execute! - end - - def revoke! - execute! - end - - protected - - def execute! # rubocop:disable MethodLength - lookup = Util.escape_globs(source) - lookup = config[:recursive] ? File.join(lookup, "**") : lookup - lookup = file_level_lookup(lookup) - - files(lookup).sort.each do |file_source| - next if File.directory?(file_source) - next if config[:exclude_pattern] && file_source.match(config[:exclude_pattern]) - file_destination = File.join(given_destination, file_source.gsub(source, ".")) - file_destination.gsub!("/./", "/") - - case file_source - when /\.empty_directory$/ - dirname = File.dirname(file_destination).gsub(/\/\.$/, "") - next if dirname == given_destination - base.empty_directory(dirname, config) - when /#{TEMPLATE_EXTNAME}$/ - base.template(file_source, file_destination[0..-4], config, &@block) - else - base.copy_file(file_source, file_destination, config, &@block) - end - end - end - - if RUBY_VERSION < "2.0" - def file_level_lookup(previous_lookup) - File.join(previous_lookup, "{*,.[a-z]*}") - end - - def files(lookup) - Dir[lookup] - end - else - def file_level_lookup(previous_lookup) - File.join(previous_lookup, "*") - end - - def files(lookup) - Dir.glob(lookup, File::FNM_DOTMATCH) - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb deleted file mode 100644 index 281d8fb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/empty_directory.rb +++ /dev/null @@ -1,135 +0,0 @@ -class Thor - module Actions - # Creates an empty directory. - # - # ==== Parameters - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # empty_directory "doc" - # - def empty_directory(destination, config = {}) - action EmptyDirectory.new(self, destination, config) - end - - # Class which holds create directory logic. This is the base class for - # other actions like create_file and directory. - # - # This implementation is based in Templater actions, created by Jonas Nicklas - # and Michael S. Klishin under MIT LICENSE. - # - class EmptyDirectory #:nodoc: - attr_reader :base, :destination, :given_destination, :relative_destination, :config - - # Initializes given the source and destination. - # - # ==== Parameters - # base:: A Thor::Base instance - # source:: Relative path to the source of this file - # destination:: Relative path to the destination of this file - # config:: give :verbose => false to not log the status. - # - def initialize(base, destination, config = {}) - @base, @config = base, {:verbose => true}.merge(config) - self.destination = destination - end - - # Checks if the destination file already exists. - # - # ==== Returns - # Boolean:: true if the file exists, false otherwise. - # - def exists? - ::File.exist?(destination) - end - - def invoke! - invoke_with_conflict_check do - ::FileUtils.mkdir_p(destination) - end - end - - def revoke! - say_status :remove, :red - ::FileUtils.rm_rf(destination) if !pretend? && exists? - given_destination - end - - protected - - # Shortcut for pretend. - # - def pretend? - base.options[:pretend] - end - - # Sets the absolute destination value from a relative destination value. - # It also stores the given and relative destination. Let's suppose our - # script is being executed on "dest", it sets the destination root to - # "dest". The destination, given_destination and relative_destination - # are related in the following way: - # - # inside "bar" do - # empty_directory "baz" - # end - # - # destination #=> dest/bar/baz - # relative_destination #=> bar/baz - # given_destination #=> baz - # - def destination=(destination) - if destination - @given_destination = convert_encoded_instructions(destination.to_s) - @destination = ::File.expand_path(@given_destination, base.destination_root) - @relative_destination = base.relative_to_original_destination_root(@destination) - end - end - - # Filenames in the encoded form are converted. If you have a file: - # - # %file_name%.rb - # - # It calls #file_name from the base and replaces %-string with the - # return value (should be String) of #file_name: - # - # user.rb - # - # The method referenced can be either public or private. - # - def convert_encoded_instructions(filename) - filename.gsub(/%(.*?)%/) do |initial_string| - method = $1.strip - base.respond_to?(method, true) ? base.send(method) : initial_string - end - end - - # Receives a hash of options and just execute the block if some - # conditions are met. - # - def invoke_with_conflict_check(&block) - if exists? - on_conflict_behavior(&block) - else - say_status :create, :green - block.call unless pretend? - end - - destination - end - - # What to do when the destination file already exists. - # - def on_conflict_behavior(&block) - say_status :exist, :blue - end - - # Shortcut to say_status shell method. - # - def say_status(status, color) - base.shell.say_status status, relative_destination, color if config[:verbose] - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/file_manipulation.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/file_manipulation.rb deleted file mode 100644 index 01f6d98..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/file_manipulation.rb +++ /dev/null @@ -1,316 +0,0 @@ -require "erb" -require "open-uri" - -class Thor - module Actions - # Copies the file from the relative source to the relative destination. If - # the destination is not given it's assumed to be equal to the source. - # - # ==== Parameters - # source:: the relative path to the source root. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status, and - # :mode => :preserve, to preserve the file mode from the source. - - # - # ==== Examples - # - # copy_file "README", "doc/README" - # - # copy_file "doc/README" - # - def copy_file(source, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - destination = args.first || source - source = File.expand_path(find_in_source_paths(source.to_s)) - - create_file destination, nil, config do - content = File.binread(source) - content = block.call(content) if block - content - end - if config[:mode] == :preserve - mode = File.stat(source).mode - chmod(destination, mode, config) - end - end - - # Links the file from the relative source to the relative destination. If - # the destination is not given it's assumed to be equal to the source. - # - # ==== Parameters - # source:: the relative path to the source root. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # link_file "README", "doc/README" - # - # link_file "doc/README" - # - def link_file(source, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - destination = args.first || source - source = File.expand_path(find_in_source_paths(source.to_s)) - - create_link destination, source, config - end - - # Gets the content at the given address and places it at the given relative - # destination. If a block is given instead of destination, the content of - # the url is yielded and used as location. - # - # ==== Parameters - # source:: the address of the given content. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # get "http://gist.github.com/103208", "doc/README" - # - # get "http://gist.github.com/103208" do |content| - # content.split("\n").first - # end - # - def get(source, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - destination = args.first - - source = File.expand_path(find_in_source_paths(source.to_s)) unless source =~ %r{^https?\://} - render = open(source) { |input| input.binmode.read } - - destination ||= if block_given? - block.arity == 1 ? block.call(render) : block.call - else - File.basename(source) - end - - create_file destination, render, config - end - - # Gets an ERB template at the relative source, executes it and makes a copy - # at the relative destination. If the destination is not given it's assumed - # to be equal to the source removing .tt from the filename. - # - # ==== Parameters - # source:: the relative path to the source root. - # destination:: the relative path to the destination root. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # template "README", "doc/README" - # - # template "doc/README" - # - def template(source, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - destination = args.first || source.sub(/#{TEMPLATE_EXTNAME}$/, "") - - source = File.expand_path(find_in_source_paths(source.to_s)) - context = instance_eval("binding") - - create_file destination, nil, config do - content = ERB.new(::File.binread(source), nil, "-", "@output_buffer").result(context) - content = block.call(content) if block - content - end - end - - # Changes the mode of the given file or directory. - # - # ==== Parameters - # mode:: the file mode - # path:: the name of the file to change mode - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # chmod "script/server", 0755 - # - def chmod(path, mode, config = {}) - return unless behavior == :invoke - path = File.expand_path(path, destination_root) - say_status :chmod, relative_to_original_destination_root(path), config.fetch(:verbose, true) - FileUtils.chmod_R(mode, path) unless options[:pretend] - end - - # Prepend text to a file. Since it depends on insert_into_file, it's reversible. - # - # ==== Parameters - # path:: path of the file to be changed - # data:: the data to prepend to the file, can be also given as a block. - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # prepend_to_file 'config/environments/test.rb', 'config.gem "rspec"' - # - # prepend_to_file 'config/environments/test.rb' do - # 'config.gem "rspec"' - # end - # - def prepend_to_file(path, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - config.merge!(:after => /\A/) - insert_into_file(path, *(args << config), &block) - end - alias_method :prepend_file, :prepend_to_file - - # Append text to a file. Since it depends on insert_into_file, it's reversible. - # - # ==== Parameters - # path:: path of the file to be changed - # data:: the data to append to the file, can be also given as a block. - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # append_to_file 'config/environments/test.rb', 'config.gem "rspec"' - # - # append_to_file 'config/environments/test.rb' do - # 'config.gem "rspec"' - # end - # - def append_to_file(path, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - config.merge!(:before => /\z/) - insert_into_file(path, *(args << config), &block) - end - alias_method :append_file, :append_to_file - - # Injects text right after the class definition. Since it depends on - # insert_into_file, it's reversible. - # - # ==== Parameters - # path:: path of the file to be changed - # klass:: the class to be manipulated - # data:: the data to append to the class, can be also given as a block. - # config:: give :verbose => false to not log the status. - # - # ==== Examples - # - # inject_into_class "app/controllers/application_controller.rb", ApplicationController, " filter_parameter :password\n" - # - # inject_into_class "app/controllers/application_controller.rb", ApplicationController do - # " filter_parameter :password\n" - # end - # - def inject_into_class(path, klass, *args, &block) - config = args.last.is_a?(Hash) ? args.pop : {} - config.merge!(:after => /class #{klass}\n|class #{klass} .*\n/) - insert_into_file(path, *(args << config), &block) - end - - # Run a regular expression replacement on a file. - # - # ==== Parameters - # path:: path of the file to be changed - # flag:: the regexp or string to be replaced - # replacement:: the replacement, can be also given as a block - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # gsub_file 'app/controllers/application_controller.rb', /#\s*(filter_parameter_logging :password)/, '\1' - # - # gsub_file 'README', /rake/, :green do |match| - # match << " no more. Use thor!" - # end - # - def gsub_file(path, flag, *args, &block) - return unless behavior == :invoke - config = args.last.is_a?(Hash) ? args.pop : {} - - path = File.expand_path(path, destination_root) - say_status :gsub, relative_to_original_destination_root(path), config.fetch(:verbose, true) - - unless options[:pretend] - content = File.binread(path) - content.gsub!(flag, *args, &block) - File.open(path, "wb") { |file| file.write(content) } - end - end - - # Uncomment all lines matching a given regex. It will leave the space - # which existed before the comment hash in tact but will remove any spacing - # between the comment hash and the beginning of the line. - # - # ==== Parameters - # path:: path of the file to be changed - # flag:: the regexp or string used to decide which lines to uncomment - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # uncomment_lines 'config/initializers/session_store.rb', /active_record/ - # - def uncomment_lines(path, flag, *args) - flag = flag.respond_to?(:source) ? flag.source : flag - - gsub_file(path, /^(\s*)#[[:blank:]]*(.*#{flag})/, '\1\2', *args) - end - - # Comment all lines matching a given regex. It will leave the space - # which existed before the beginning of the line in tact and will insert - # a single space after the comment hash. - # - # ==== Parameters - # path:: path of the file to be changed - # flag:: the regexp or string used to decide which lines to comment - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # comment_lines 'config/initializers/session_store.rb', /cookie_store/ - # - def comment_lines(path, flag, *args) - flag = flag.respond_to?(:source) ? flag.source : flag - - gsub_file(path, /^(\s*)([^#|\n]*#{flag})/, '\1# \2', *args) - end - - # Removes a file at the given location. - # - # ==== Parameters - # path:: path of the file to be changed - # config:: give :verbose => false to not log the status. - # - # ==== Example - # - # remove_file 'README' - # remove_file 'app/controllers/application_controller.rb' - # - def remove_file(path, config = {}) - return unless behavior == :invoke - path = File.expand_path(path, destination_root) - - say_status :remove, relative_to_original_destination_root(path), config.fetch(:verbose, true) - ::FileUtils.rm_rf(path) if !options[:pretend] && File.exist?(path) - end - alias_method :remove_dir, :remove_file - - attr_accessor :output_buffer - private :output_buffer, :output_buffer= - - private - - def concat(string) - @output_buffer.concat(string) - end - - def capture(*args, &block) - with_output_buffer { block.call(*args) } - end - - def with_output_buffer(buf = "") #:nodoc: - self.output_buffer, old_buffer = buf, output_buffer - yield - output_buffer - ensure - self.output_buffer = old_buffer - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb deleted file mode 100644 index d617efb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/actions/inject_into_file.rb +++ /dev/null @@ -1,107 +0,0 @@ -require "thor/actions/empty_directory" - -class Thor - module Actions - # Injects the given content into a file. Different from gsub_file, this - # method is reversible. - # - # ==== Parameters - # destination:: Relative path to the destination root - # data:: Data to add to the file. Can be given as a block. - # config:: give :verbose => false to not log the status and the flag - # for injection (:after or :before) or :force => true for - # insert two or more times the same content. - # - # ==== Examples - # - # insert_into_file "config/environment.rb", "config.gem :thor", :after => "Rails::Initializer.run do |config|\n" - # - # insert_into_file "config/environment.rb", :after => "Rails::Initializer.run do |config|\n" do - # gems = ask "Which gems would you like to add?" - # gems.split(" ").map{ |gem| " config.gem :#{gem}" }.join("\n") - # end - # - def insert_into_file(destination, *args, &block) - if block_given? - data, config = block, args.shift - else - data, config = args.shift, args.shift - end - action InjectIntoFile.new(self, destination, data, config) - end - alias_method :inject_into_file, :insert_into_file - - class InjectIntoFile < EmptyDirectory #:nodoc: - attr_reader :replacement, :flag, :behavior - - def initialize(base, destination, data, config) - super(base, destination, {:verbose => true}.merge(config)) - - @behavior, @flag = if @config.key?(:after) - [:after, @config.delete(:after)] - else - [:before, @config.delete(:before)] - end - - @replacement = data.is_a?(Proc) ? data.call : data - @flag = Regexp.escape(@flag) unless @flag.is_a?(Regexp) - end - - def invoke! - say_status :invoke - - content = if @behavior == :after - '\0' + replacement - else - replacement + '\0' - end - - replace!(/#{flag}/, content, config[:force]) - end - - def revoke! - say_status :revoke - - regexp = if @behavior == :after - content = '\1\2' - /(#{flag})(.*)(#{Regexp.escape(replacement)})/m - else - content = '\2\3' - /(#{Regexp.escape(replacement)})(.*)(#{flag})/m - end - - replace!(regexp, content, true) - end - - protected - - def say_status(behavior) - status = if behavior == :invoke - if flag == /\A/ - :prepend - elsif flag == /\z/ - :append - else - :insert - end - else - :subtract - end - - super(status, config[:verbose]) - end - - # Adds the content to the file. - # - def replace!(regexp, string, force) - unless base.options[:pretend] - content = File.binread(destination) - if force || !content.include?(replacement) - content.gsub!(regexp, string) - File.open(destination, "wb") { |file| file.write(content) } - end - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/base.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/base.rb deleted file mode 100644 index 4cfe514..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/base.rb +++ /dev/null @@ -1,656 +0,0 @@ -require "thor/command" -require "thor/core_ext/hash_with_indifferent_access" -require "thor/core_ext/ordered_hash" -require "thor/error" -require "thor/invocation" -require "thor/parser" -require "thor/shell" -require "thor/line_editor" -require "thor/util" - -class Thor - autoload :Actions, "thor/actions" - autoload :RakeCompat, "thor/rake_compat" - autoload :Group, "thor/group" - - # Shortcuts for help. - HELP_MAPPINGS = %w[-h -? --help -D] - - # Thor methods that should not be overwritten by the user. - THOR_RESERVED_WORDS = %w[invoke shell options behavior root destination_root relative_root - action add_file create_file in_root inside run run_ruby_script] - - TEMPLATE_EXTNAME = ".tt" - - module Base - attr_accessor :options, :parent_options, :args - - # It receives arguments in an Array and two hashes, one for options and - # other for configuration. - # - # Notice that it does not check if all required arguments were supplied. - # It should be done by the parser. - # - # ==== Parameters - # args:: An array of objects. The objects are applied to their - # respective accessors declared with argument. - # - # options:: An options hash that will be available as self.options. - # The hash given is converted to a hash with indifferent - # access, magic predicates (options.skip?) and then frozen. - # - # config:: Configuration for this Thor class. - # - def initialize(args = [], local_options = {}, config = {}) # rubocop:disable MethodLength - parse_options = self.class.class_options - - # The start method splits inbound arguments at the first argument - # that looks like an option (starts with - or --). It then calls - # new, passing in the two halves of the arguments Array as the - # first two parameters. - - command_options = config.delete(:command_options) # hook for start - parse_options = parse_options.merge(command_options) if command_options - if local_options.is_a?(Array) - array_options, hash_options = local_options, {} - else - # Handle the case where the class was explicitly instantiated - # with pre-parsed options. - array_options, hash_options = [], local_options - end - - # Let Thor::Options parse the options first, so it can remove - # declared options from the array. This will leave us with - # a list of arguments that weren't declared. - stop_on_unknown = self.class.stop_on_unknown_option? config[:current_command] - opts = Thor::Options.new(parse_options, hash_options, stop_on_unknown) - self.options = opts.parse(array_options) - self.options = config[:class_options].merge(options) if config[:class_options] - - # If unknown options are disallowed, make sure that none of the - # remaining arguments looks like an option. - opts.check_unknown! if self.class.check_unknown_options?(config) - - # Add the remaining arguments from the options parser to the - # arguments passed in to initialize. Then remove any positional - # arguments declared using #argument (this is primarily used - # by Thor::Group). Tis will leave us with the remaining - # positional arguments. - to_parse = args - to_parse += opts.remaining unless self.class.strict_args_position?(config) - - thor_args = Thor::Arguments.new(self.class.arguments) - thor_args.parse(to_parse).each { |k, v| __send__("#{k}=", v) } - @args = thor_args.remaining - end - - class << self - def included(base) #:nodoc: - base.extend ClassMethods - base.send :include, Invocation - base.send :include, Shell - end - - # Returns the classes that inherits from Thor or Thor::Group. - # - # ==== Returns - # Array[Class] - # - def subclasses - @subclasses ||= [] - end - - # Returns the files where the subclasses are kept. - # - # ==== Returns - # Hash[path => Class] - # - def subclass_files - @subclass_files ||= Hash.new { |h, k| h[k] = [] } - end - - # Whenever a class inherits from Thor or Thor::Group, we should track the - # class and the file on Thor::Base. This is the method responsable for it. - # - def register_klass_file(klass) #:nodoc: - file = caller[1].match(/(.*):\d+/)[1] - Thor::Base.subclasses << klass unless Thor::Base.subclasses.include?(klass) - - file_subclasses = Thor::Base.subclass_files[File.expand_path(file)] - file_subclasses << klass unless file_subclasses.include?(klass) - end - end - - module ClassMethods - def attr_reader(*) #:nodoc: - no_commands { super } - end - - def attr_writer(*) #:nodoc: - no_commands { super } - end - - def attr_accessor(*) #:nodoc: - no_commands { super } - end - - # If you want to raise an error for unknown options, call check_unknown_options! - # This is disabled by default to allow dynamic invocations. - def check_unknown_options! - @check_unknown_options = true - end - - def check_unknown_options #:nodoc: - @check_unknown_options ||= from_superclass(:check_unknown_options, false) - end - - def check_unknown_options?(config) #:nodoc: - !!check_unknown_options - end - - # If true, option parsing is suspended as soon as an unknown option or a - # regular argument is encountered. All remaining arguments are passed to - # the command as regular arguments. - def stop_on_unknown_option?(command_name) #:nodoc: - false - end - - # If you want only strict string args (useful when cascading thor classes), - # call strict_args_position! This is disabled by default to allow dynamic - # invocations. - def strict_args_position! - @strict_args_position = true - end - - def strict_args_position #:nodoc: - @strict_args_position ||= from_superclass(:strict_args_position, false) - end - - def strict_args_position?(config) #:nodoc: - !!strict_args_position - end - - # Adds an argument to the class and creates an attr_accessor for it. - # - # Arguments are different from options in several aspects. The first one - # is how they are parsed from the command line, arguments are retrieved - # from position: - # - # thor command NAME - # - # Instead of: - # - # thor command --name=NAME - # - # Besides, arguments are used inside your code as an accessor (self.argument), - # while options are all kept in a hash (self.options). - # - # Finally, arguments cannot have type :default or :boolean but can be - # optional (supplying :optional => :true or :required => false), although - # you cannot have a required argument after a non-required argument. If you - # try it, an error is raised. - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described below. - # - # ==== Options - # :desc - Description for the argument. - # :required - If the argument is required or not. - # :optional - If the argument is optional or not. - # :type - The type of the argument, can be :string, :hash, :array, :numeric. - # :default - Default value for this argument. It cannot be required and have default values. - # :banner - String to show on usage notes. - # - # ==== Errors - # ArgumentError:: Raised if you supply a required argument after a non required one. - # - def argument(name, options = {}) # rubocop:disable MethodLength - is_thor_reserved_word?(name, :argument) - no_commands { attr_accessor name } - - required = if options.key?(:optional) - !options[:optional] - elsif options.key?(:required) - options[:required] - else - options[:default].nil? - end - - remove_argument name - - arguments.each do |argument| - next if argument.required? - fail ArgumentError, "You cannot have #{name.to_s.inspect} as required argument after " << - "the non-required argument #{argument.human_name.inspect}." - end if required - - options[:required] = required - - arguments << Thor::Argument.new(name, options) - end - - # Returns this class arguments, looking up in the ancestors chain. - # - # ==== Returns - # Array[Thor::Argument] - # - def arguments - @arguments ||= from_superclass(:arguments, []) - end - - # Adds a bunch of options to the set of class options. - # - # class_options :foo => false, :bar => :required, :baz => :string - # - # If you prefer more detailed declaration, check class_option. - # - # ==== Parameters - # Hash[Symbol => Object] - # - def class_options(options = nil) - @class_options ||= from_superclass(:class_options, {}) - build_options(options, @class_options) if options - @class_options - end - - # Adds an option to the set of class options - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described below. - # - # ==== Options - # :desc:: -- Description for the argument. - # :required:: -- If the argument is required or not. - # :default:: -- Default value for this argument. - # :group:: -- The group for this options. Use by class options to output options in different levels. - # :aliases:: -- Aliases for this option. Note: Thor follows a convention of one-dash-one-letter options. Thus aliases like "-something" wouldn't be parsed; use either "\--something" or "-s" instead. - # :type:: -- The type of the argument, can be :string, :hash, :array, :numeric or :boolean. - # :banner:: -- String to show on usage notes. - # :hide:: -- If you want to hide this option from the help. - # - def class_option(name, options = {}) - build_option(name, options, class_options) - end - - # Removes a previous defined argument. If :undefine is given, undefine - # accessors as well. - # - # ==== Parameters - # names:: Arguments to be removed - # - # ==== Examples - # - # remove_argument :foo - # remove_argument :foo, :bar, :baz, :undefine => true - # - def remove_argument(*names) - options = names.last.is_a?(Hash) ? names.pop : {} - - names.each do |name| - arguments.delete_if { |a| a.name == name.to_s } - undef_method name, "#{name}=" if options[:undefine] - end - end - - # Removes a previous defined class option. - # - # ==== Parameters - # names:: Class options to be removed - # - # ==== Examples - # - # remove_class_option :foo - # remove_class_option :foo, :bar, :baz - # - def remove_class_option(*names) - names.each do |name| - class_options.delete(name) - end - end - - # Defines the group. This is used when thor list is invoked so you can specify - # that only commands from a pre-defined group will be shown. Defaults to standard. - # - # ==== Parameters - # name - # - def group(name = nil) - if name - @group = name.to_s - else - @group ||= from_superclass(:group, "standard") - end - end - - # Returns the commands for this Thor class. - # - # ==== Returns - # OrderedHash:: An ordered hash with commands names as keys and Thor::Command - # objects as values. - # - def commands - @commands ||= Thor::CoreExt::OrderedHash.new - end - alias_method :tasks, :commands - - # Returns the commands for this Thor class and all subclasses. - # - # ==== Returns - # OrderedHash:: An ordered hash with commands names as keys and Thor::Command - # objects as values. - # - def all_commands - @all_commands ||= from_superclass(:all_commands, Thor::CoreExt::OrderedHash.new) - @all_commands.merge(commands) - end - alias_method :all_tasks, :all_commands - - # Removes a given command from this Thor class. This is usually done if you - # are inheriting from another class and don't want it to be available - # anymore. - # - # By default it only remove the mapping to the command. But you can supply - # :undefine => true to undefine the method from the class as well. - # - # ==== Parameters - # name:: The name of the command to be removed - # options:: You can give :undefine => true if you want commands the method - # to be undefined from the class as well. - # - def remove_command(*names) - options = names.last.is_a?(Hash) ? names.pop : {} - - names.each do |name| - commands.delete(name.to_s) - all_commands.delete(name.to_s) - undef_method name if options[:undefine] - end - end - alias_method :remove_task, :remove_command - - # All methods defined inside the given block are not added as commands. - # - # So you can do: - # - # class MyScript < Thor - # no_commands do - # def this_is_not_a_command - # end - # end - # end - # - # You can also add the method and remove it from the command list: - # - # class MyScript < Thor - # def this_is_not_a_command - # end - # remove_command :this_is_not_a_command - # end - # - def no_commands - @no_commands = true - yield - ensure - @no_commands = false - end - alias_method :no_tasks, :no_commands - - # Sets the namespace for the Thor or Thor::Group class. By default the - # namespace is retrieved from the class name. If your Thor class is named - # Scripts::MyScript, the help method, for example, will be called as: - # - # thor scripts:my_script -h - # - # If you change the namespace: - # - # namespace :my_scripts - # - # You change how your commands are invoked: - # - # thor my_scripts -h - # - # Finally, if you change your namespace to default: - # - # namespace :default - # - # Your commands can be invoked with a shortcut. Instead of: - # - # thor :my_command - # - def namespace(name = nil) - if name - @namespace = name.to_s - else - @namespace ||= Thor::Util.namespace_from_thor_class(self) - end - end - - # Parses the command and options from the given args, instantiate the class - # and invoke the command. This method is used when the arguments must be parsed - # from an array. If you are inside Ruby and want to use a Thor class, you - # can simply initialize it: - # - # script = MyScript.new(args, options, config) - # script.invoke(:command, first_arg, second_arg, third_arg) - # - def start(given_args = ARGV, config = {}) - config[:shell] ||= Thor::Base.shell.new - dispatch(nil, given_args.dup, nil, config) - rescue Thor::Error => e - config[:debug] || ENV["THOR_DEBUG"] == "1" ? (raise e) : config[:shell].error(e.message) - exit(1) if exit_on_failure? - rescue Errno::EPIPE - # This happens if a thor command is piped to something like `head`, - # which closes the pipe when it's done reading. This will also - # mean that if the pipe is closed, further unnecessary - # computation will not occur. - exit(0) - end - - # Allows to use private methods from parent in child classes as commands. - # - # ==== Parameters - # names:: Method names to be used as commands - # - # ==== Examples - # - # public_command :foo - # public_command :foo, :bar, :baz - # - def public_command(*names) - names.each do |name| - class_eval "def #{name}(*); super end" - end - end - alias_method :public_task, :public_command - - def handle_no_command_error(command, has_namespace = $thor_runner) #:nodoc: - if has_namespace - fail UndefinedCommandError, "Could not find command #{command.inspect} in #{namespace.inspect} namespace." - else - fail UndefinedCommandError, "Could not find command #{command.inspect}." - end - end - alias_method :handle_no_task_error, :handle_no_command_error - - def handle_argument_error(command, error, args, arity) #:nodoc: - msg = "ERROR: \"#{basename} #{command.name}\" was called with " - msg << "no arguments" if args.empty? - msg << "arguments " << args.inspect unless args.empty? - msg << "\nUsage: #{banner(command).inspect}" - fail InvocationError, msg - end - - protected - - # Prints the class options per group. If an option does not belong to - # any group, it's printed as Class option. - # - def class_options_help(shell, groups = {}) #:nodoc: - # Group options by group - class_options.each do |_, value| - groups[value.group] ||= [] - groups[value.group] << value - end - - # Deal with default group - global_options = groups.delete(nil) || [] - print_options(shell, global_options) - - # Print all others - groups.each do |group_name, options| - print_options(shell, options, group_name) - end - end - - # Receives a set of options and print them. - def print_options(shell, options, group_name = nil) - return if options.empty? - - list = [] - padding = options.map { |o| o.aliases.size }.max.to_i * 4 - - options.each do |option| - unless option.hide - item = [option.usage(padding)] - item.push(option.description ? "# #{option.description}" : "") - - list << item - list << ["", "# Default: #{option.default}"] if option.show_default? - list << ["", "# Possible values: #{option.enum.join(', ')}"] if option.enum - end - end - - shell.say(group_name ? "#{group_name} options:" : "Options:") - shell.print_table(list, :indent => 2) - shell.say "" - end - - # Raises an error if the word given is a Thor reserved word. - def is_thor_reserved_word?(word, type) #:nodoc: - return false unless THOR_RESERVED_WORDS.include?(word.to_s) - fail "#{word.inspect} is a Thor reserved word and cannot be defined as #{type}" - end - - # Build an option and adds it to the given scope. - # - # ==== Parameters - # name:: The name of the argument. - # options:: Described in both class_option and method_option. - # scope:: Options hash that is being built up - def build_option(name, options, scope) #:nodoc: - scope[name] = Thor::Option.new(name, options) - end - - # Receives a hash of options, parse them and add to the scope. This is a - # fast way to set a bunch of options: - # - # build_options :foo => true, :bar => :required, :baz => :string - # - # ==== Parameters - # Hash[Symbol => Object] - def build_options(options, scope) #:nodoc: - options.each do |key, value| - scope[key] = Thor::Option.parse(key, value) - end - end - - # Finds a command with the given name. If the command belongs to the current - # class, just return it, otherwise dup it and add the fresh copy to the - # current command hash. - def find_and_refresh_command(name) #:nodoc: - if commands[name.to_s] - commands[name.to_s] - elsif command = all_commands[name.to_s] # rubocop:disable AssignmentInCondition - commands[name.to_s] = command.clone - else - fail ArgumentError, "You supplied :for => #{name.inspect}, but the command #{name.inspect} could not be found." - end - end - alias_method :find_and_refresh_task, :find_and_refresh_command - - # Everytime someone inherits from a Thor class, register the klass - # and file into baseclass. - def inherited(klass) - Thor::Base.register_klass_file(klass) - klass.instance_variable_set(:@no_commands, false) - end - - # Fire this callback whenever a method is added. Added methods are - # tracked as commands by invoking the create_command method. - def method_added(meth) - meth = meth.to_s - - if meth == "initialize" - initialize_added - return - end - - # Return if it's not a public instance method - return unless public_method_defined?(meth.to_sym) - - @no_commands ||= false - return if @no_commands || !create_command(meth) - - is_thor_reserved_word?(meth, :command) - Thor::Base.register_klass_file(self) - end - - # Retrieves a value from superclass. If it reaches the baseclass, - # returns default. - def from_superclass(method, default = nil) - if self == baseclass || !superclass.respond_to?(method, true) - default - else - value = superclass.send(method) - - # Ruby implements `dup` on Object, but raises a `TypeError` - # if the method is called on immediates. As a result, we - # don't have a good way to check whether dup will succeed - # without calling it and rescuing the TypeError. - begin - value.dup - rescue TypeError - value - end - - end - end - - # A flag that makes the process exit with status 1 if any error happens. - def exit_on_failure? - false - end - - # - # The basename of the program invoking the thor class. - # - def basename - File.basename($PROGRAM_NAME).split(" ").first - end - - # SIGNATURE: Sets the baseclass. This is where the superclass lookup - # finishes. - def baseclass #:nodoc: - end - - # SIGNATURE: Creates a new command if valid_command? is true. This method is - # called when a new method is added to the class. - def create_command(meth) #:nodoc: - end - alias_method :create_task, :create_command - - # SIGNATURE: Defines behavior when the initialize method is added to the - # class. - def initialize_added #:nodoc: - end - - # SIGNATURE: The hook invoked by start. - def dispatch(command, given_args, given_opts, config) #:nodoc: - fail NotImplementedError - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/command.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/command.rb deleted file mode 100644 index 71d1545..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/command.rb +++ /dev/null @@ -1,133 +0,0 @@ -class Thor - class Command < Struct.new(:name, :description, :long_description, :usage, :options) - FILE_REGEXP = /^#{Regexp.escape(File.dirname(__FILE__))}/ - - def initialize(name, description, long_description, usage, options = nil) - super(name.to_s, description, long_description, usage, options || {}) - end - - def initialize_copy(other) #:nodoc: - super(other) - self.options = other.options.dup if other.options - end - - def hidden? - false - end - - # By default, a command invokes a method in the thor class. You can change this - # implementation to create custom commands. - def run(instance, args = []) - arity = nil - - if private_method?(instance) - instance.class.handle_no_command_error(name) - elsif public_method?(instance) - arity = instance.method(name).arity - instance.__send__(name, *args) - elsif local_method?(instance, :method_missing) - instance.__send__(:method_missing, name.to_sym, *args) - else - instance.class.handle_no_command_error(name) - end - rescue ArgumentError => e - handle_argument_error?(instance, e, caller) ? instance.class.handle_argument_error(self, e, args, arity) : (raise e) - rescue NoMethodError => e - handle_no_method_error?(instance, e, caller) ? instance.class.handle_no_command_error(name) : (fail e) - end - - # Returns the formatted usage by injecting given required arguments - # and required options into the given usage. - def formatted_usage(klass, namespace = true, subcommand = false) - if namespace - namespace = klass.namespace - formatted = "#{namespace.gsub(/^(default)/, '')}:" - end - formatted = "#{klass.namespace.split(':').last} " if subcommand - - formatted ||= "" - - # Add usage with required arguments - formatted << if klass && !klass.arguments.empty? - usage.to_s.gsub(/^#{name}/) do |match| - match << " " << klass.arguments.map { |a| a.usage }.compact.join(" ") - end - else - usage.to_s - end - - # Add required options - formatted << " #{required_options}" - - # Strip and go! - formatted.strip - end - - protected - - def not_debugging?(instance) - !(instance.class.respond_to?(:debugging) && instance.class.debugging) - end - - def required_options - @required_options ||= options.map { |_, o| o.usage if o.required? }.compact.sort.join(" ") - end - - # Given a target, checks if this class name is a public method. - def public_method?(instance) #:nodoc: - !(instance.public_methods & [name.to_s, name.to_sym]).empty? - end - - def private_method?(instance) - !(instance.private_methods & [name.to_s, name.to_sym]).empty? - end - - def local_method?(instance, name) - methods = instance.public_methods(false) + instance.private_methods(false) + instance.protected_methods(false) - !(methods & [name.to_s, name.to_sym]).empty? - end - - def sans_backtrace(backtrace, caller) #:nodoc: - saned = backtrace.reject { |frame| frame =~ FILE_REGEXP || (frame =~ /\.java:/ && RUBY_PLATFORM =~ /java/) || (frame =~ /^kernel\// && RUBY_ENGINE =~ /rbx/) } - saned - caller - end - - def handle_argument_error?(instance, error, caller) - not_debugging?(instance) && (error.message =~ /wrong number of arguments/ || error.message =~ /given \d*, expected \d*/) && begin - saned = sans_backtrace(error.backtrace, caller) - # Ruby 1.9 always include the called method in the backtrace - saned.empty? || (saned.size == 1 && RUBY_VERSION >= "1.9") - end - end - - def handle_no_method_error?(instance, error, caller) - not_debugging?(instance) && - error.message =~ /^undefined method `#{name}' for #{Regexp.escape(instance.to_s)}$/ - end - end - Task = Command # rubocop:disable ConstantName - - # A command that is hidden in help messages but still invocable. - class HiddenCommand < Command - def hidden? - true - end - end - HiddenTask = HiddenCommand # rubocop:disable ConstantName - - # A dynamic command that handles method missing scenarios. - class DynamicCommand < Command - def initialize(name, options = nil) - super(name.to_s, "A dynamically-generated command", name.to_s, name.to_s, options) - end - - def run(instance, args = []) - if (instance.methods & [name.to_s, name.to_sym]).empty? - super - else - instance.class.handle_no_command_error(name) - end - end - end - DynamicTask = DynamicCommand # rubocop:disable ConstantName -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/hash_with_indifferent_access.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/hash_with_indifferent_access.rb deleted file mode 100644 index 35dbf07..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/hash_with_indifferent_access.rb +++ /dev/null @@ -1,77 +0,0 @@ -class Thor - module CoreExt #:nodoc: - # A hash with indifferent access and magic predicates. - # - # hash = Thor::CoreExt::HashWithIndifferentAccess.new 'foo' => 'bar', 'baz' => 'bee', 'force' => true - # - # hash[:foo] #=> 'bar' - # hash['foo'] #=> 'bar' - # hash.foo? #=> true - # - class HashWithIndifferentAccess < ::Hash #:nodoc: - def initialize(hash = {}) - super() - hash.each do |key, value| - self[convert_key(key)] = value - end - end - - def [](key) - super(convert_key(key)) - end - - def []=(key, value) - super(convert_key(key), value) - end - - def delete(key) - super(convert_key(key)) - end - - def values_at(*indices) - indices.map { |key| self[convert_key(key)] } - end - - def merge(other) - dup.merge!(other) - end - - def merge!(other) - other.each do |key, value| - self[convert_key(key)] = value - end - self - end - - # Convert to a Hash with String keys. - def to_hash - Hash.new(default).merge!(self) - end - - protected - - def convert_key(key) - key.is_a?(Symbol) ? key.to_s : key - end - - # Magic predicates. For instance: - # - # options.force? # => !!options['force'] - # options.shebang # => "/usr/lib/local/ruby" - # options.test_framework?(:rspec) # => options[:test_framework] == :rspec - # - def method_missing(method, *args, &block) - method = method.to_s - if method =~ /^(\w+)\?$/ - if args.empty? - !!self[$1] - else - self[$1] == args.first - end - else - self[method] - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/io_binary_read.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/io_binary_read.rb deleted file mode 100644 index 19f3c3d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/io_binary_read.rb +++ /dev/null @@ -1,10 +0,0 @@ -class IO #:nodoc: - class << self - def binread(file, *args) - fail ArgumentError, "wrong number of arguments (#{1 + args.size} for 1..3)" unless args.size < 3 - File.open(file, "rb") do |f| - f.read(*args) - end - end unless method_defined? :binread - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/ordered_hash.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/ordered_hash.rb deleted file mode 100644 index d3b2bc9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/core_ext/ordered_hash.rb +++ /dev/null @@ -1,98 +0,0 @@ -class Thor - module CoreExt #:nodoc: - if RUBY_VERSION >= "1.9" - class OrderedHash < ::Hash - end - else - # This class is based on the Ruby 1.9 ordered hashes. - # - # It keeps the semantics and most of the efficiency of normal hashes - # while also keeping track of the order in which elements were set. - # - class OrderedHash #:nodoc: - include Enumerable - - Node = Struct.new(:key, :value, :next, :prev) - - def initialize - @hash = {} - end - - def [](key) - @hash[key] && @hash[key].value - end - - def []=(key, value) - if node = @hash[key] # rubocop:disable AssignmentInCondition - node.value = value - else - node = Node.new(key, value) - - if !defined?(@first) || @first.nil? - @first = @last = node - else - node.prev = @last - @last.next = node - @last = node - end - end - - @hash[key] = node - value - end - - def delete(key) - if node = @hash[key] # rubocop:disable AssignmentInCondition - prev_node = node.prev - next_node = node.next - - next_node.prev = prev_node if next_node - prev_node.next = next_node if prev_node - - @first = next_node if @first == node - @last = prev_node if @last == node - - value = node.value - end - - @hash.delete(key) - value - end - - def keys - map { |k, v| k } - end - - def values - map { |k, v| v } - end - - def each - return unless defined?(@first) && @first - yield [@first.key, @first.value] - node = @first - yield [node.key, node.value] while node = node.next # rubocop:disable AssignmentInCondition - self - end - - def merge(other) - hash = self.class.new - - each do |key, value| - hash[key] = value - end - - other.each do |key, value| - hash[key] = value - end - - hash - end - - def empty? - @hash.empty? - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/error.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/error.rb deleted file mode 100644 index c53be49..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/error.rb +++ /dev/null @@ -1,32 +0,0 @@ -class Thor - # Thor::Error is raised when it's caused by wrong usage of thor classes. Those - # errors have their backtrace suppressed and are nicely shown to the user. - # - # Errors that are caused by the developer, like declaring a method which - # overwrites a thor keyword, it SHOULD NOT raise a Thor::Error. This way, we - # ensure that developer errors are shown with full backtrace. - class Error < StandardError - end - - # Raised when a command was not found. - class UndefinedCommandError < Error - end - UndefinedTaskError = UndefinedCommandError # rubocop:disable ConstantName - - class AmbiguousCommandError < Error - end - AmbiguousTaskError = AmbiguousCommandError # rubocop:disable ConstantName - - # Raised when a command was found, but not invoked properly. - class InvocationError < Error - end - - class UnknownArgumentError < Error - end - - class RequiredArgumentMissingError < InvocationError - end - - class MalformattedArgumentError < InvocationError - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/group.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/group.rb deleted file mode 100644 index c4ee890..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/group.rb +++ /dev/null @@ -1,281 +0,0 @@ -require "thor/base" - -# Thor has a special class called Thor::Group. The main difference to Thor class -# is that it invokes all commands at once. It also include some methods that allows -# invocations to be done at the class method, which are not available to Thor -# commands. -class Thor::Group # rubocop:disable ClassLength - class << self - # The description for this Thor::Group. If none is provided, but a source root - # exists, tries to find the USAGE one folder above it, otherwise searches - # in the superclass. - # - # ==== Parameters - # description:: The description for this Thor::Group. - # - def desc(description = nil) - if description - @desc = description - else - @desc ||= from_superclass(:desc, nil) - end - end - - # Prints help information. - # - # ==== Options - # short:: When true, shows only usage. - # - def help(shell) - shell.say "Usage:" - shell.say " #{banner}\n" - shell.say - class_options_help(shell) - shell.say desc if desc - end - - # Stores invocations for this class merging with superclass values. - # - def invocations #:nodoc: - @invocations ||= from_superclass(:invocations, {}) - end - - # Stores invocation blocks used on invoke_from_option. - # - def invocation_blocks #:nodoc: - @invocation_blocks ||= from_superclass(:invocation_blocks, {}) - end - - # Invoke the given namespace or class given. It adds an instance - # method that will invoke the klass and command. You can give a block to - # configure how it will be invoked. - # - # The namespace/class given will have its options showed on the help - # usage. Check invoke_from_option for more information. - # - def invoke(*names, &block) # rubocop:disable MethodLength - options = names.last.is_a?(Hash) ? names.pop : {} - verbose = options.fetch(:verbose, true) - - names.each do |name| - invocations[name] = false - invocation_blocks[name] = block if block_given? - - class_eval <<-METHOD, __FILE__, __LINE__ - def _invoke_#{name.to_s.gsub(/\W/, "_")} - klass, command = self.class.prepare_for_invocation(nil, #{name.inspect}) - - if klass - say_status :invoke, #{name.inspect}, #{verbose.inspect} - block = self.class.invocation_blocks[#{name.inspect}] - _invoke_for_class_method klass, command, &block - else - say_status :error, %(#{name.inspect} [not found]), :red - end - end - METHOD - end - end - - # Invoke a thor class based on the value supplied by the user to the - # given option named "name". A class option must be created before this - # method is invoked for each name given. - # - # ==== Examples - # - # class GemGenerator < Thor::Group - # class_option :test_framework, :type => :string - # invoke_from_option :test_framework - # end - # - # ==== Boolean options - # - # In some cases, you want to invoke a thor class if some option is true or - # false. This is automatically handled by invoke_from_option. Then the - # option name is used to invoke the generator. - # - # ==== Preparing for invocation - # - # In some cases you want to customize how a specified hook is going to be - # invoked. You can do that by overwriting the class method - # prepare_for_invocation. The class method must necessarily return a klass - # and an optional command. - # - # ==== Custom invocations - # - # You can also supply a block to customize how the option is going to be - # invoked. The block receives two parameters, an instance of the current - # class and the klass to be invoked. - # - def invoke_from_option(*names, &block) # rubocop:disable MethodLength - options = names.last.is_a?(Hash) ? names.pop : {} - verbose = options.fetch(:verbose, :white) - - names.each do |name| - unless class_options.key?(name) - fail ArgumentError, "You have to define the option #{name.inspect} " << - "before setting invoke_from_option." - end - - invocations[name] = true - invocation_blocks[name] = block if block_given? - - class_eval <<-METHOD, __FILE__, __LINE__ - def _invoke_from_option_#{name.to_s.gsub(/\W/, "_")} - return unless options[#{name.inspect}] - - value = options[#{name.inspect}] - value = #{name.inspect} if TrueClass === value - klass, command = self.class.prepare_for_invocation(#{name.inspect}, value) - - if klass - say_status :invoke, value, #{verbose.inspect} - block = self.class.invocation_blocks[#{name.inspect}] - _invoke_for_class_method klass, command, &block - else - say_status :error, %(\#{value} [not found]), :red - end - end - METHOD - end - end - - # Remove a previously added invocation. - # - # ==== Examples - # - # remove_invocation :test_framework - # - def remove_invocation(*names) - names.each do |name| - remove_command(name) - remove_class_option(name) - invocations.delete(name) - invocation_blocks.delete(name) - end - end - - # Overwrite class options help to allow invoked generators options to be - # shown recursively when invoking a generator. - # - def class_options_help(shell, groups = {}) #:nodoc: - get_options_from_invocations(groups, class_options) do |klass| - klass.send(:get_options_from_invocations, groups, class_options) - end - super(shell, groups) - end - - # Get invocations array and merge options from invocations. Those - # options are added to group_options hash. Options that already exists - # in base_options are not added twice. - # - def get_options_from_invocations(group_options, base_options) #:nodoc: # rubocop:disable MethodLength - invocations.each do |name, from_option| - value = if from_option - option = class_options[name] - option.type == :boolean ? name : option.default - else - name - end - next unless value - - klass, _ = prepare_for_invocation(name, value) - next unless klass && klass.respond_to?(:class_options) - - value = value.to_s - human_name = value.respond_to?(:classify) ? value.classify : value - - group_options[human_name] ||= [] - group_options[human_name] += klass.class_options.values.select do |class_option| - base_options[class_option.name.to_sym].nil? && class_option.group.nil? && - !group_options.values.flatten.any? { |i| i.name == class_option.name } - end - - yield klass if block_given? - end - end - - # Returns commands ready to be printed. - def printable_commands(*) - item = [] - item << banner - item << (desc ? "# #{desc.gsub(/\s+/m, ' ')}" : "") - [item] - end - alias_method :printable_tasks, :printable_commands - - def handle_argument_error(command, error, args, arity) #:nodoc: - msg = "#{basename} #{command.name} takes #{arity} argument" - msg << "s" if arity > 1 - msg << ", but it should not." - fail error, msg - end - - protected - - # The method responsible for dispatching given the args. - def dispatch(command, given_args, given_opts, config) #:nodoc: - if Thor::HELP_MAPPINGS.include?(given_args.first) - help(config[:shell]) - return - end - - args, opts = Thor::Options.split(given_args) - opts = given_opts || opts - - instance = new(args, opts, config) - yield instance if block_given? - - if command - instance.invoke_command(all_commands[command]) - else - instance.invoke_all - end - end - - # The banner for this class. You can customize it if you are invoking the - # thor class by another ways which is not the Thor::Runner. - def banner - "#{basename} #{self_command.formatted_usage(self, false)}" - end - - # Represents the whole class as a command. - def self_command #:nodoc: - Thor::DynamicCommand.new(namespace, class_options) - end - alias_method :self_task, :self_command - - def baseclass #:nodoc: - Thor::Group - end - - def create_command(meth) #:nodoc: - commands[meth.to_s] = Thor::Command.new(meth, nil, nil, nil, nil) - true - end - alias_method :create_task, :create_command - end - - include Thor::Base - -protected - - # Shortcut to invoke with padding and block handling. Use internally by - # invoke and invoke_from_option class methods. - def _invoke_for_class_method(klass, command = nil, *args, &block) #:nodoc: - with_padding do - if block - case block.arity - when 3 - block.call(self, klass, command) - when 2 - block.call(self, klass) - when 1 - instance_exec(klass, &block) - end - else - invoke klass, command, *args - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/invocation.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/invocation.rb deleted file mode 100644 index 108c704..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/invocation.rb +++ /dev/null @@ -1,178 +0,0 @@ -class Thor - module Invocation - def self.included(base) #:nodoc: - base.extend ClassMethods - end - - module ClassMethods - # This method is responsible for receiving a name and find the proper - # class and command for it. The key is an optional parameter which is - # available only in class methods invocations (i.e. in Thor::Group). - def prepare_for_invocation(key, name) #:nodoc: - case name - when Symbol, String - Thor::Util.find_class_and_command_by_namespace(name.to_s, !key) - else - name - end - end - end - - # Make initializer aware of invocations and the initialization args. - def initialize(args = [], options = {}, config = {}, &block) #:nodoc: - @_invocations = config[:invocations] || Hash.new { |h, k| h[k] = [] } - @_initializer = [args, options, config] - super - end - - # Make the current command chain accessible with in a Thor-(sub)command - def current_command_chain - @_invocations.values.flatten.map(&:to_sym) - end - - # Receives a name and invokes it. The name can be a string (either "command" or - # "namespace:command"), a Thor::Command, a Class or a Thor instance. If the - # command cannot be guessed by name, it can also be supplied as second argument. - # - # You can also supply the arguments, options and configuration values for - # the command to be invoked, if none is given, the same values used to - # initialize the invoker are used to initialize the invoked. - # - # When no name is given, it will invoke the default command of the current class. - # - # ==== Examples - # - # class A < Thor - # def foo - # invoke :bar - # invoke "b:hello", ["Erik"] - # end - # - # def bar - # invoke "b:hello", ["Erik"] - # end - # end - # - # class B < Thor - # def hello(name) - # puts "hello #{name}" - # end - # end - # - # You can notice that the method "foo" above invokes two commands: "bar", - # which belongs to the same class and "hello" which belongs to the class B. - # - # By using an invocation system you ensure that a command is invoked only once. - # In the example above, invoking "foo" will invoke "b:hello" just once, even - # if it's invoked later by "bar" method. - # - # When class A invokes class B, all arguments used on A initialization are - # supplied to B. This allows lazy parse of options. Let's suppose you have - # some rspec commands: - # - # class Rspec < Thor::Group - # class_option :mock_framework, :type => :string, :default => :rr - # - # def invoke_mock_framework - # invoke "rspec:#{options[:mock_framework]}" - # end - # end - # - # As you noticed, it invokes the given mock framework, which might have its - # own options: - # - # class Rspec::RR < Thor::Group - # class_option :style, :type => :string, :default => :mock - # end - # - # Since it's not rspec concern to parse mock framework options, when RR - # is invoked all options are parsed again, so RR can extract only the options - # that it's going to use. - # - # If you want Rspec::RR to be initialized with its own set of options, you - # have to do that explicitly: - # - # invoke "rspec:rr", [], :style => :foo - # - # Besides giving an instance, you can also give a class to invoke: - # - # invoke Rspec::RR, [], :style => :foo - # - def invoke(name = nil, *args) - if name.nil? - warn "[Thor] Calling invoke() without argument is deprecated. Please use invoke_all instead.\n#{caller.join("\n")}" - return invoke_all - end - - args.unshift(nil) if args.first.is_a?(Array) || args.first.nil? - command, args, opts, config = args - - klass, command = _retrieve_class_and_command(name, command) - fail "Missing Thor class for invoke #{name}" unless klass - fail "Expected Thor class, got #{klass}" unless klass <= Thor::Base - - args, opts, config = _parse_initialization_options(args, opts, config) - klass.send(:dispatch, command, args, opts, config) do |instance| - instance.parent_options = options - end - end - - # Invoke the given command if the given args. - def invoke_command(command, *args) #:nodoc: - current = @_invocations[self.class] - - unless current.include?(command.name) - current << command.name - command.run(self, *args) - end - end - alias_method :invoke_task, :invoke_command - - # Invoke all commands for the current instance. - def invoke_all #:nodoc: - self.class.all_commands.map { |_, command| invoke_command(command) } - end - - # Invokes using shell padding. - def invoke_with_padding(*args) - with_padding { invoke(*args) } - end - - protected - - # Configuration values that are shared between invocations. - def _shared_configuration #:nodoc: - {:invocations => @_invocations} - end - - # This method simply retrieves the class and command to be invoked. - # If the name is nil or the given name is a command in the current class, - # use the given name and return self as class. Otherwise, call - # prepare_for_invocation in the current class. - def _retrieve_class_and_command(name, sent_command = nil) #:nodoc: - case - when name.nil? - [self.class, nil] - when self.class.all_commands[name.to_s] - [self.class, name.to_s] - else - klass, command = self.class.prepare_for_invocation(nil, name) - [klass, command || sent_command] - end - end - alias_method :_retrieve_class_and_task, :_retrieve_class_and_command - - # Initialize klass using values stored in the @_initializer. - def _parse_initialization_options(args, opts, config) #:nodoc: - stored_args, stored_opts, stored_config = @_initializer - - args ||= stored_args.dup - opts ||= stored_opts.dup - - config ||= {} - config = stored_config.merge(_shared_configuration).merge!(config) - - [args, opts, config] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor.rb deleted file mode 100644 index a38bae8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "thor/line_editor/basic" -require "thor/line_editor/readline" - -class Thor - module LineEditor - def self.readline(prompt, options = {}) - best_available.new(prompt, options).readline - end - - def self.best_available - [ - Thor::LineEditor::Readline, - Thor::LineEditor::Basic - ].detect(&:available?) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor/basic.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor/basic.rb deleted file mode 100644 index 1ffbdf0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor/basic.rb +++ /dev/null @@ -1,35 +0,0 @@ -class Thor - module LineEditor - class Basic - attr_reader :prompt, :options - - def self.available? - true - end - - def initialize(prompt, options) - @prompt = prompt - @options = options - end - - def readline - $stdout.print(prompt) - get_input - end - - private - - def get_input - if echo? - $stdin.gets - else - $stdin.noecho(&:gets) - end - end - - def echo? - options.fetch(:echo, true) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor/readline.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor/readline.rb deleted file mode 100644 index 32446e3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/line_editor/readline.rb +++ /dev/null @@ -1,88 +0,0 @@ -begin - require "readline" -rescue LoadError -end - -class Thor - module LineEditor - class Readline < Basic - def self.available? - Object.const_defined?(:Readline) - end - - def readline - if echo? - ::Readline.completion_append_character = nil - # Ruby 1.8.7 does not allow Readline.completion_proc= to receive nil. - if complete = completion_proc - ::Readline.completion_proc = complete - end - ::Readline.readline(prompt, add_to_history?) - else - super - end - end - - private - - def add_to_history? - options.fetch(:add_to_history, true) - end - - def completion_proc - if use_path_completion? - proc { |text| PathCompletion.new(text).matches } - elsif completion_options.any? - proc do |text| - completion_options.select { |option| option.start_with?(text) } - end - end - end - - def completion_options - options.fetch(:limited_to, []) - end - - def use_path_completion? - options.fetch(:path, false) - end - - class PathCompletion - attr_reader :text - private :text - - def initialize(text) - @text = text - end - - def matches - relative_matches - end - - private - - def relative_matches - absolute_matches.map { |path| path.sub(base_path, "") } - end - - def absolute_matches - Dir[glob_pattern].map do |path| - if File.directory?(path) - "#{path}/" - else - path - end - end - end - - def glob_pattern - "#{base_path}#{text}*" - end - - def base_path - "#{Dir.pwd}/" - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser.rb deleted file mode 100644 index 74c789b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser.rb +++ /dev/null @@ -1,4 +0,0 @@ -require "thor/parser/argument" -require "thor/parser/arguments" -require "thor/parser/option" -require "thor/parser/options" diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/argument.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/argument.rb deleted file mode 100644 index 96f0eff..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/argument.rb +++ /dev/null @@ -1,73 +0,0 @@ -class Thor - class Argument #:nodoc: - VALID_TYPES = [:numeric, :hash, :array, :string] - - attr_reader :name, :description, :enum, :required, :type, :default, :banner - alias_method :human_name, :name - - def initialize(name, options = {}) - class_name = self.class.name.split("::").last - - type = options[:type] - - fail ArgumentError, "#{class_name} name can't be nil." if name.nil? - fail ArgumentError, "Type :#{type} is not valid for #{class_name.downcase}s." if type && !valid_type?(type) - - @name = name.to_s - @description = options[:desc] - @required = options.key?(:required) ? options[:required] : true - @type = (type || :string).to_sym - @default = options[:default] - @banner = options[:banner] || default_banner - @enum = options[:enum] - - validate! # Trigger specific validations - end - - def usage - required? ? banner : "[#{banner}]" - end - - def required? - required - end - - def show_default? - case default - when Array, String, Hash - !default.empty? - else - default - end - end - - protected - - def validate! - if required? && !default.nil? - fail ArgumentError, "An argument cannot be required and have default value." - elsif @enum && !@enum.is_a?(Array) - fail ArgumentError, "An argument cannot have an enum other than an array." - end - end - - def valid_type?(type) - self.class::VALID_TYPES.include?(type.to_sym) - end - - def default_banner - case type - when :boolean - nil - when :string, :default - human_name.upcase - when :numeric - "N" - when :hash - "key:value" - when :array - "one two three" - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/arguments.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/arguments.rb deleted file mode 100644 index 8e9e973..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/arguments.rb +++ /dev/null @@ -1,175 +0,0 @@ -class Thor - class Arguments #:nodoc: # rubocop:disable ClassLength - NUMERIC = /(\d*\.\d+|\d+)/ - - # Receives an array of args and returns two arrays, one with arguments - # and one with switches. - # - def self.split(args) - arguments = [] - - args.each do |item| - break if item =~ /^-/ - arguments << item - end - - [arguments, args[Range.new(arguments.size, -1)]] - end - - def self.parse(*args) - to_parse = args.pop - new(*args).parse(to_parse) - end - - # Takes an array of Thor::Argument objects. - # - def initialize(arguments = []) - @assigns, @non_assigned_required = {}, [] - @switches = arguments - - arguments.each do |argument| - if !argument.default.nil? - @assigns[argument.human_name] = argument.default - elsif argument.required? - @non_assigned_required << argument - end - end - end - - def parse(args) - @pile = args.dup - - @switches.each do |argument| - break unless peek - @non_assigned_required.delete(argument) - @assigns[argument.human_name] = send(:"parse_#{argument.type}", argument.human_name) - end - - check_requirement! - @assigns - end - - def remaining # rubocop:disable TrivialAccessors - @pile - end - - private - - def no_or_skip?(arg) - arg =~ /^--(no|skip)-([-\w]+)$/ - $2 - end - - def last? - @pile.empty? - end - - def peek - @pile.first - end - - def shift - @pile.shift - end - - def unshift(arg) - if arg.kind_of?(Array) - @pile = arg + @pile - else - @pile.unshift(arg) - end - end - - def current_is_value? - peek && peek.to_s !~ /^-/ - end - - # Runs through the argument array getting strings that contains ":" and - # mark it as a hash: - # - # [ "name:string", "age:integer" ] - # - # Becomes: - # - # { "name" => "string", "age" => "integer" } - # - def parse_hash(name) - return shift if peek.is_a?(Hash) - hash = {} - - while current_is_value? && peek.include?(":") - key, value = shift.split(":", 2) - hash[key] = value - end - hash - end - - # Runs through the argument array getting all strings until no string is - # found or a switch is found. - # - # ["a", "b", "c"] - # - # And returns it as an array: - # - # ["a", "b", "c"] - # - def parse_array(name) - return shift if peek.is_a?(Array) - array = [] - array << shift while current_is_value? - array - end - - # Check if the peek is numeric format and return a Float or Integer. - # Check if the peek is included in enum if enum is provided. - # Otherwise raises an error. - # - def parse_numeric(name) - return shift if peek.is_a?(Numeric) - - unless peek =~ NUMERIC && $& == peek - fail MalformattedArgumentError, "Expected numeric value for '#{name}'; got #{peek.inspect}" - end - - value = $&.index(".") ? shift.to_f : shift.to_i - if @switches.is_a?(Hash) && switch = @switches[name] - if switch.enum && !switch.enum.include?(value) - fail MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}" - end - end - value - end - - # Parse string: - # for --string-arg, just return the current value in the pile - # for --no-string-arg, nil - # Check if the peek is included in enum if enum is provided. Otherwise raises an error. - # - def parse_string(name) - if no_or_skip?(name) - nil - else - value = shift - if @switches.is_a?(Hash) && switch = @switches[name] # rubocop:disable AssignmentInCondition - if switch.enum && !switch.enum.include?(value) - fail MalformattedArgumentError, "Expected '#{name}' to be one of #{switch.enum.join(', ')}; got #{value}" - end - end - value - end - end - - # Raises an error if @non_assigned_required array is not empty. - # - def check_requirement! - unless @non_assigned_required.empty? - names = @non_assigned_required.map do |o| - o.respond_to?(:switch_name) ? o.switch_name : o.human_name - end.join("', '") - - class_name = self.class.name.split("::").last.downcase - fail RequiredArgumentMissingError, "No value provided for required #{class_name} '#{names}'" - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/option.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/option.rb deleted file mode 100644 index 9099a3d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/option.rb +++ /dev/null @@ -1,125 +0,0 @@ -class Thor - class Option < Argument #:nodoc: - attr_reader :aliases, :group, :lazy_default, :hide - - VALID_TYPES = [:boolean, :numeric, :hash, :array, :string] - - def initialize(name, options = {}) - options[:required] = false unless options.key?(:required) - super - @lazy_default = options[:lazy_default] - @group = options[:group].to_s.capitalize if options[:group] - @aliases = Array(options[:aliases]) - @hide = options[:hide] - end - - # This parse quick options given as method_options. It makes several - # assumptions, but you can be more specific using the option method. - # - # parse :foo => "bar" - # #=> Option foo with default value bar - # - # parse [:foo, :baz] => "bar" - # #=> Option foo with default value bar and alias :baz - # - # parse :foo => :required - # #=> Required option foo without default value - # - # parse :foo => 2 - # #=> Option foo with default value 2 and type numeric - # - # parse :foo => :numeric - # #=> Option foo without default value and type numeric - # - # parse :foo => true - # #=> Option foo with default value true and type boolean - # - # The valid types are :boolean, :numeric, :hash, :array and :string. If none - # is given a default type is assumed. This default type accepts arguments as - # string (--foo=value) or booleans (just --foo). - # - # By default all options are optional, unless :required is given. - # - def self.parse(key, value) # rubocop:disable MethodLength - if key.is_a?(Array) - name, *aliases = key - else - name, aliases = key, [] - end - - name = name.to_s - default = value - - type = case value - when Symbol - default = nil - if VALID_TYPES.include?(value) - value - elsif required = (value == :required) # rubocop:disable AssignmentInCondition - :string - end - when TrueClass, FalseClass - :boolean - when Numeric - :numeric - when Hash, Array, String - value.class.name.downcase.to_sym - end - new(name.to_s, :required => required, :type => type, :default => default, :aliases => aliases) - end - - def switch_name - @switch_name ||= dasherized? ? name : dasherize(name) - end - - def human_name - @human_name ||= dasherized? ? undasherize(name) : name - end - - def usage(padding = 0) - sample = if banner && !banner.to_s.empty? - "#{switch_name}=#{banner}" - else - switch_name - end - - sample = "[#{sample}]" unless required? - - if boolean? - sample << ", [#{dasherize("no-" + human_name)}]" unless name == "force" - end - - if aliases.empty? - (" " * padding) << sample - else - "#{aliases.join(', ')}, #{sample}" - end - end - - VALID_TYPES.each do |type| - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{type}? - self.type == #{type.inspect} - end - RUBY - end - - protected - - def validate! - fail ArgumentError, "An option cannot be boolean and required." if boolean? && required? - end - - def dasherized? - name.index("-") == 0 - end - - def undasherize(str) - str.sub(/^-{1,2}/, "") - end - - def dasherize(str) - (str.length > 1 ? "--" : "-") + str.gsub("_", "-") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/options.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/options.rb deleted file mode 100644 index 6cfba11..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/parser/options.rb +++ /dev/null @@ -1,218 +0,0 @@ -class Thor - class Options < Arguments #:nodoc: # rubocop:disable ClassLength - LONG_RE = /^(--\w+(?:-\w+)*)$/ - SHORT_RE = /^(-[a-z])$/i - EQ_RE = /^(--\w+(?:-\w+)*|-[a-z])=(.*)$/i - SHORT_SQ_RE = /^-([a-z]{2,})$/i # Allow either -x -v or -xv style for single char args - SHORT_NUM = /^(-[a-z])#{NUMERIC}$/i - OPTS_END = "--".freeze - - # Receives a hash and makes it switches. - def self.to_switches(options) - options.map do |key, value| - case value - when true - "--#{key}" - when Array - "--#{key} #{value.map { |v| v.inspect }.join(' ')}" - when Hash - "--#{key} #{value.map { |k, v| "#{k}:#{v}" }.join(' ')}" - when nil, false - "" - else - "--#{key} #{value.inspect}" - end - end.join(" ") - end - - # Takes a hash of Thor::Option and a hash with defaults. - # - # If +stop_on_unknown+ is true, #parse will stop as soon as it encounters - # an unknown option or a regular argument. - def initialize(hash_options = {}, defaults = {}, stop_on_unknown = false) - @stop_on_unknown = stop_on_unknown - options = hash_options.values - super(options) - - # Add defaults - defaults.each do |key, value| - @assigns[key.to_s] = value - @non_assigned_required.delete(hash_options[key]) - end - - @shorts, @switches, @extra = {}, {}, [] - - options.each do |option| - @switches[option.switch_name] = option - - option.aliases.each do |short| - name = short.to_s.sub(/^(?!\-)/, "-") - @shorts[name] ||= option.switch_name - end - end - end - - def remaining # rubocop:disable TrivialAccessors - @extra - end - - def peek - return super unless @parsing_options - - result = super - if result == OPTS_END - shift - @parsing_options = false - super - else - result - end - end - - def parse(args) # rubocop:disable MethodLength - @pile = args.dup - @parsing_options = true - - while peek - if parsing_options? - match, is_switch = current_is_switch? - shifted = shift - - if is_switch - case shifted - when SHORT_SQ_RE - unshift($1.split("").map { |f| "-#{f}" }) - next - when EQ_RE, SHORT_NUM - unshift($2) - switch = $1 - when LONG_RE, SHORT_RE - switch = $1 - end - - switch = normalize_switch(switch) - option = switch_option(switch) - @assigns[option.human_name] = parse_peek(switch, option) - elsif @stop_on_unknown - @parsing_options = false - @extra << shifted - @extra << shift while peek - break - elsif match - @extra << shifted - @extra << shift while peek && peek !~ /^-/ - else - @extra << shifted - end - else - @extra << shift - end - end - - check_requirement! - - assigns = Thor::CoreExt::HashWithIndifferentAccess.new(@assigns) - assigns.freeze - assigns - end - - def check_unknown! - # an unknown option starts with - or -- and has no more --'s afterward. - unknown = @extra.select { |str| str =~ /^--?(?:(?!--).)*$/ } - fail UnknownArgumentError, "Unknown switches '#{unknown.join(', ')}'" unless unknown.empty? - end - - protected - - # Check if the current value in peek is a registered switch. - # - # Two booleans are returned. The first is true if the current value - # starts with a hyphen; the second is true if it is a registered switch. - def current_is_switch? - case peek - when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM - [true, switch?($1)] - when SHORT_SQ_RE - [true, $1.split("").any? { |f| switch?("-#{f}") }] - else - [false, false] - end - end - - def current_is_switch_formatted? - case peek - when LONG_RE, SHORT_RE, EQ_RE, SHORT_NUM, SHORT_SQ_RE - true - else - false - end - end - - def current_is_value? - peek && (!parsing_options? || super) - end - - def switch?(arg) - switch_option(normalize_switch(arg)) - end - - def switch_option(arg) - if match = no_or_skip?(arg) # rubocop:disable AssignmentInCondition - @switches[arg] || @switches["--#{match}"] - else - @switches[arg] - end - end - - # Check if the given argument is actually a shortcut. - # - def normalize_switch(arg) - (@shorts[arg] || arg).tr("_", "-") - end - - def parsing_options? - peek - @parsing_options - end - - # Parse boolean values which can be given as --foo=true, --foo or --no-foo. - # - def parse_boolean(switch) - if current_is_value? - if ["true", "TRUE", "t", "T", true].include?(peek) - shift - true - elsif ["false", "FALSE", "f", "F", false].include?(peek) - shift - false - else - true - end - else - @switches.key?(switch) || !no_or_skip?(switch) - end - end - - # Parse the value at the peek analyzing if it requires an input or not. - # - def parse_peek(switch, option) - if parsing_options? && (current_is_switch_formatted? || last?) - if option.boolean? - # No problem for boolean types - elsif no_or_skip?(switch) - return nil # User set value to nil - elsif option.string? && !option.required? - # Return the default if there is one, else the human name - return option.lazy_default || option.default || option.human_name - elsif option.lazy_default - return option.lazy_default - else - fail MalformattedArgumentError, "No value provided for option '#{switch}'" - end - end - - @non_assigned_required.delete(option) - send(:"parse_#{option.type}", switch) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/rake_compat.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/rake_compat.rb deleted file mode 100644 index a42045f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/rake_compat.rb +++ /dev/null @@ -1,71 +0,0 @@ -require "rake" -require "rake/dsl_definition" - -class Thor - # Adds a compatibility layer to your Thor classes which allows you to use - # rake package tasks. For example, to use rspec rake tasks, one can do: - # - # require 'thor/rake_compat' - # require 'rspec/core/rake_task' - # - # class Default < Thor - # include Thor::RakeCompat - # - # RSpec::Core::RakeTask.new(:spec) do |t| - # t.spec_opts = ['--options', './.rspec'] - # t.spec_files = FileList['spec/**/*_spec.rb'] - # end - # end - # - module RakeCompat - include Rake::DSL if defined?(Rake::DSL) - - def self.rake_classes - @rake_classes ||= [] - end - - def self.included(base) - # Hack. Make rakefile point to invoker, so rdoc task is generated properly. - rakefile = File.basename(caller[0].match(/(.*):\d+/)[1]) - Rake.application.instance_variable_set(:@rakefile, rakefile) - rake_classes << base - end - end -end - -# override task on (main), for compatibility with Rake 0.9 -instance_eval do - alias rake_namespace namespace - - def task(*) - task = super - - if klass = Thor::RakeCompat.rake_classes.last # rubocop:disable AssignmentInCondition - non_namespaced_name = task.name.split(":").last - - description = non_namespaced_name - description << task.arg_names.map { |n| n.to_s.upcase }.join(" ") - description.strip! - - klass.desc description, Rake.application.last_description || non_namespaced_name - Rake.application.last_description = nil - klass.send :define_method, non_namespaced_name do |*args| - Rake::Task[task.name.to_sym].invoke(*args) - end - end - - task - end - - def namespace(name) - if klass = Thor::RakeCompat.rake_classes.last # rubocop:disable AssignmentInCondition - const_name = Thor::Util.camel_case(name.to_s).to_sym - klass.const_set(const_name, Class.new(Thor)) - new_klass = klass.const_get(const_name) - Thor::RakeCompat.rake_classes << new_klass - end - - super - Thor::RakeCompat.rake_classes.pop - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/runner.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/runner.rb deleted file mode 100644 index 1d768a4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/runner.rb +++ /dev/null @@ -1,322 +0,0 @@ -require "thor" -require "thor/group" -require "thor/core_ext/io_binary_read" - -require "fileutils" -require "open-uri" -require "yaml" -require "digest/md5" -require "pathname" - -class Thor::Runner < Thor #:nodoc: # rubocop:disable ClassLength - map "-T" => :list, "-i" => :install, "-u" => :update, "-v" => :version - - # Override Thor#help so it can give information about any class and any method. - # - def help(meth = nil) - if meth && !self.respond_to?(meth) - initialize_thorfiles(meth) - klass, command = Thor::Util.find_class_and_command_by_namespace(meth) - self.class.handle_no_command_error(command, false) if klass.nil? - klass.start(["-h", command].compact, :shell => shell) - else - super - end - end - - # If a command is not found on Thor::Runner, method missing is invoked and - # Thor::Runner is then responsible for finding the command in all classes. - # - def method_missing(meth, *args) - meth = meth.to_s - initialize_thorfiles(meth) - klass, command = Thor::Util.find_class_and_command_by_namespace(meth) - self.class.handle_no_command_error(command, false) if klass.nil? - args.unshift(command) if command - klass.start(args, :shell => shell) - end - - desc "install NAME", "Install an optionally named Thor file into your system commands" - method_options :as => :string, :relative => :boolean, :force => :boolean - def install(name) # rubocop:disable MethodLength - initialize_thorfiles - - # If a directory name is provided as the argument, look for a 'main.thor' - # command in said directory. - begin - if File.directory?(File.expand_path(name)) - base, package = File.join(name, "main.thor"), :directory - contents = open(base) { |input| input.read } - else - base, package = name, :file - contents = open(name) { |input| input.read } - end - rescue OpenURI::HTTPError - raise Error, "Error opening URI '#{name}'" - rescue Errno::ENOENT - fail Error, "Error opening file '#{name}'" - end - - say "Your Thorfile contains:" - say contents - - unless options["force"] - return false if no?("Do you wish to continue [y/N]?") - end - - as = options["as"] || begin - first_line = contents.split("\n")[0] - (match = first_line.match(/\s*#\s*module:\s*([^\n]*)/)) ? match[1].strip : nil - end - - unless as - basename = File.basename(name) - as = ask("Please specify a name for #{name} in the system repository [#{basename}]:") - as = basename if as.empty? - end - - location = if options[:relative] || name =~ %r{^https?://} - name - else - File.expand_path(name) - end - - thor_yaml[as] = { - :filename => Digest::MD5.hexdigest(name + as), - :location => location, - :namespaces => Thor::Util.namespaces_in_content(contents, base) - } - - save_yaml(thor_yaml) - say "Storing thor file in your system repository" - destination = File.join(thor_root, thor_yaml[as][:filename]) - - if package == :file - File.open(destination, "w") { |f| f.puts contents } - else - FileUtils.cp_r(name, destination) - end - - thor_yaml[as][:filename] # Indicate success - end - - desc "version", "Show Thor version" - def version - require "thor/version" - say "Thor #{Thor::VERSION}" - end - - desc "uninstall NAME", "Uninstall a named Thor module" - def uninstall(name) - fail Error, "Can't find module '#{name}'" unless thor_yaml[name] - say "Uninstalling #{name}." - FileUtils.rm_rf(File.join(thor_root, "#{thor_yaml[name][:filename]}")) - - thor_yaml.delete(name) - save_yaml(thor_yaml) - - puts "Done." - end - - desc "update NAME", "Update a Thor file from its original location" - def update(name) - fail Error, "Can't find module '#{name}'" if !thor_yaml[name] || !thor_yaml[name][:location] - - say "Updating '#{name}' from #{thor_yaml[name][:location]}" - - old_filename = thor_yaml[name][:filename] - self.options = options.merge("as" => name) - - if File.directory? File.expand_path(name) - FileUtils.rm_rf(File.join(thor_root, old_filename)) - - thor_yaml.delete(old_filename) - save_yaml(thor_yaml) - - filename = install(name) - else - filename = install(thor_yaml[name][:location]) - end - - unless filename == old_filename - File.delete(File.join(thor_root, old_filename)) - end - end - - desc "installed", "List the installed Thor modules and commands" - method_options :internal => :boolean - def installed - initialize_thorfiles(nil, true) - display_klasses(true, options["internal"]) - end - - desc "list [SEARCH]", "List the available thor commands (--substring means .*SEARCH)" - method_options :substring => :boolean, :group => :string, :all => :boolean, :debug => :boolean - def list(search = "") - initialize_thorfiles - - search = ".*#{search}" if options["substring"] - search = /^#{search}.*/i - group = options[:group] || "standard" - - klasses = Thor::Base.subclasses.select do |k| - (options[:all] || k.group == group) && k.namespace =~ search - end - - display_klasses(false, false, klasses) - end - -private - - def self.banner(command, all = false, subcommand = false) - "thor " + command.formatted_usage(self, all, subcommand) - end - - def thor_root - Thor::Util.thor_root - end - - def thor_yaml - @thor_yaml ||= begin - yaml_file = File.join(thor_root, "thor.yml") - yaml = YAML.load_file(yaml_file) if File.exist?(yaml_file) - yaml || {} - end - end - - # Save the yaml file. If none exists in thor root, creates one. - # - def save_yaml(yaml) - yaml_file = File.join(thor_root, "thor.yml") - - unless File.exist?(yaml_file) - FileUtils.mkdir_p(thor_root) - yaml_file = File.join(thor_root, "thor.yml") - FileUtils.touch(yaml_file) - end - - File.open(yaml_file, "w") { |f| f.puts yaml.to_yaml } - end - - def self.exit_on_failure? - true - end - - # Load the Thorfiles. If relevant_to is supplied, looks for specific files - # in the thor_root instead of loading them all. - # - # By default, it also traverses the current path until find Thor files, as - # described in thorfiles. This look up can be skipped by supplying - # skip_lookup true. - # - def initialize_thorfiles(relevant_to = nil, skip_lookup = false) - thorfiles(relevant_to, skip_lookup).each do |f| - Thor::Util.load_thorfile(f, nil, options[:debug]) unless Thor::Base.subclass_files.keys.include?(File.expand_path(f)) - end - end - - # Finds Thorfiles by traversing from your current directory down to the root - # directory of your system. If at any time we find a Thor file, we stop. - # - # We also ensure that system-wide Thorfiles are loaded first, so local - # Thorfiles can override them. - # - # ==== Example - # - # If we start at /Users/wycats/dev/thor ... - # - # 1. /Users/wycats/dev/thor - # 2. /Users/wycats/dev - # 3. /Users/wycats <-- we find a Thorfile here, so we stop - # - # Suppose we start at c:\Documents and Settings\james\dev\thor ... - # - # 1. c:\Documents and Settings\james\dev\thor - # 2. c:\Documents and Settings\james\dev - # 3. c:\Documents and Settings\james - # 4. c:\Documents and Settings - # 5. c:\ <-- no Thorfiles found! - # - def thorfiles(relevant_to = nil, skip_lookup = false) - thorfiles = [] - - unless skip_lookup - Pathname.pwd.ascend do |path| - thorfiles = Thor::Util.globs_for(path).map { |g| Dir[g] }.flatten - break unless thorfiles.empty? - end - end - - files = (relevant_to ? thorfiles_relevant_to(relevant_to) : Thor::Util.thor_root_glob) - files += thorfiles - files -= ["#{thor_root}/thor.yml"] - - files.map! do |file| - File.directory?(file) ? File.join(file, "main.thor") : file - end - end - - # Load Thorfiles relevant to the given method. If you provide "foo:bar" it - # will load all thor files in the thor.yaml that has "foo" e "foo:bar" - # namespaces registered. - # - def thorfiles_relevant_to(meth) - lookup = [meth, meth.split(":")[0...-1].join(":")] - - files = thor_yaml.select do |k, v| - v[:namespaces] && !(v[:namespaces] & lookup).empty? - end - - files.map { |k, v| File.join(thor_root, "#{v[:filename]}") } - end - - # Display information about the given klasses. If with_module is given, - # it shows a table with information extracted from the yaml file. - # - def display_klasses(with_modules = false, show_internal = false, klasses = Thor::Base.subclasses) - klasses -= [Thor, Thor::Runner, Thor::Group] unless show_internal - - fail Error, "No Thor commands available" if klasses.empty? - show_modules if with_modules && !thor_yaml.empty? - - list = Hash.new { |h, k| h[k] = [] } - groups = klasses.select { |k| k.ancestors.include?(Thor::Group) } - - # Get classes which inherit from Thor - (klasses - groups).each { |k| list[k.namespace.split(":").first] += k.printable_commands(false) } - - # Get classes which inherit from Thor::Base - groups.map! { |k| k.printable_commands(false).first } - list["root"] = groups - - # Order namespaces with default coming first - list = list.sort { |a, b| a[0].sub(/^default/, "") <=> b[0].sub(/^default/, "") } - list.each { |n, commands| display_commands(n, commands) unless commands.empty? } - end - - def display_commands(namespace, list) #:nodoc: - list.sort! { |a, b| a[0] <=> b[0] } - - say shell.set_color(namespace, :blue, true) - say "-" * namespace.size - - print_table(list, :truncate => true) - say - end - alias_method :display_tasks, :display_commands - - def show_modules #:nodoc: - info = [] - labels = %w[Modules Namespaces] - - info << labels - info << ["-" * labels[0].size, "-" * labels[1].size] - - thor_yaml.each do |name, hash| - info << [name, hash[:namespaces].join(", ")] - end - - print_table info - say "" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell.rb deleted file mode 100644 index 707aac9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell.rb +++ /dev/null @@ -1,81 +0,0 @@ -require "rbconfig" - -class Thor - module Base - class << self - attr_writer :shell - - # Returns the shell used in all Thor classes. If you are in a Unix platform - # it will use a colored log, otherwise it will use a basic one without color. - # - def shell - @shell ||= if ENV["THOR_SHELL"] && ENV["THOR_SHELL"].size > 0 - Thor::Shell.const_get(ENV["THOR_SHELL"]) - elsif RbConfig::CONFIG["host_os"] =~ /mswin|mingw/ && !ENV["ANSICON"] - Thor::Shell::Basic - else - Thor::Shell::Color - end - end - end - end - - module Shell - SHELL_DELEGATED_METHODS = [:ask, :error, :set_color, :yes?, :no?, :say, :say_status, :print_in_columns, :print_table, :print_wrapped, :file_collision, :terminal_width] - attr_writer :shell - - autoload :Basic, "thor/shell/basic" - autoload :Color, "thor/shell/color" - autoload :HTML, "thor/shell/html" - - # Add shell to initialize config values. - # - # ==== Configuration - # shell:: An instance of the shell to be used. - # - # ==== Examples - # - # class MyScript < Thor - # argument :first, :type => :numeric - # end - # - # MyScript.new [1.0], { :foo => :bar }, :shell => Thor::Shell::Basic.new - # - def initialize(args = [], options = {}, config = {}) - super - self.shell = config[:shell] - shell.base ||= self if shell.respond_to?(:base) - end - - # Holds the shell for the given Thor instance. If no shell is given, - # it gets a default shell from Thor::Base.shell. - def shell - @shell ||= Thor::Base.shell.new - end - - # Common methods that are delegated to the shell. - SHELL_DELEGATED_METHODS.each do |method| - module_eval <<-METHOD, __FILE__, __LINE__ - def #{method}(*args,&block) - shell.#{method}(*args,&block) - end - METHOD - end - - # Yields the given block with padding. - def with_padding - shell.padding += 1 - yield - ensure - shell.padding -= 1 - end - - protected - - # Allow shell to be shared between invocations. - # - def _shared_configuration #:nodoc: - super.merge!(:shell => shell) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/basic.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/basic.rb deleted file mode 100644 index 700b0eb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/basic.rb +++ /dev/null @@ -1,421 +0,0 @@ -require "tempfile" -require "io/console" if RUBY_VERSION > "1.9.2" - -class Thor - module Shell - class Basic # rubocop:disable ClassLength - attr_accessor :base - attr_reader :padding - - # Initialize base, mute and padding to nil. - # - def initialize #:nodoc: - @base, @mute, @padding, @always_force = nil, false, 0, false - end - - # Mute everything that's inside given block - # - def mute - @mute = true - yield - ensure - @mute = false - end - - # Check if base is muted - # - def mute? # rubocop:disable TrivialAccessors - @mute - end - - # Sets the output padding, not allowing less than zero values. - # - def padding=(value) - @padding = [0, value].max - end - - # Asks something to the user and receives a response. - # - # If asked to limit the correct responses, you can pass in an - # array of acceptable answers. If one of those is not supplied, - # they will be shown a message stating that one of those answers - # must be given and re-asked the question. - # - # If asking for sensitive information, the :echo option can be set - # to false to mask user input from $stdin. - # - # If the required input is a path, then set the path option to - # true. This will enable tab completion for file paths relative - # to the current working directory on systems that support - # Readline. - # - # ==== Example - # ask("What is your name?") - # - # ask("What is your favorite Neopolitan flavor?", :limited_to => ["strawberry", "chocolate", "vanilla"]) - # - # ask("What is your password?", :echo => false) - # - # ask("Where should the file be saved?", :path => true) - # - def ask(statement, *args) - options = args.last.is_a?(Hash) ? args.pop : {} - color = args.first - - if options[:limited_to] - ask_filtered(statement, color, options) - else - ask_simply(statement, color, options) - end - end - - # Say (print) something to the user. If the sentence ends with a whitespace - # or tab character, a new line is not appended (print + flush). Otherwise - # are passed straight to puts (behavior got from Highline). - # - # ==== Example - # say("I know you knew that.") - # - def say(message = "", color = nil, force_new_line = (message.to_s !~ /( |\t)\Z/)) - buffer = prepare_message(message, *color) - buffer << "\n" if force_new_line && !message.to_s.end_with?("\n") - - stdout.print(buffer) - stdout.flush - end - - # Say a status with the given color and appends the message. Since this - # method is used frequently by actions, it allows nil or false to be given - # in log_status, avoiding the message from being shown. If a Symbol is - # given in log_status, it's used as the color. - # - def say_status(status, message, log_status = true) - return if quiet? || log_status == false - spaces = " " * (padding + 1) - color = log_status.is_a?(Symbol) ? log_status : :green - - status = status.to_s.rjust(12) - status = set_color status, color, true if color - - buffer = "#{status}#{spaces}#{message}" - buffer << "\n" unless buffer.end_with?("\n") - - stdout.print(buffer) - stdout.flush - end - - # Make a question the to user and returns true if the user replies "y" or - # "yes". - # - def yes?(statement, color = nil) - !!(ask(statement, color, :add_to_history => false) =~ is?(:yes)) - end - - # Make a question the to user and returns true if the user replies "n" or - # "no". - # - def no?(statement, color = nil) - !!(ask(statement, color, :add_to_history => false) =~ is?(:no)) - end - - # Prints values in columns - # - # ==== Parameters - # Array[String, String, ...] - # - def print_in_columns(array) - return if array.empty? - colwidth = (array.map { |el| el.to_s.size }.max || 0) + 2 - array.each_with_index do |value, index| - # Don't output trailing spaces when printing the last column - if ((((index + 1) % (terminal_width / colwidth))).zero? && !index.zero?) || index + 1 == array.length - stdout.puts value - else - stdout.printf("%-#{colwidth}s", value) - end - end - end - - # Prints a table. - # - # ==== Parameters - # Array[Array[String, String, ...]] - # - # ==== Options - # indent:: Indent the first column by indent value. - # colwidth:: Force the first column to colwidth spaces wide. - # - def print_table(array, options = {}) # rubocop:disable MethodLength - return if array.empty? - - formats, indent, colwidth = [], options[:indent].to_i, options[:colwidth] - options[:truncate] = terminal_width if options[:truncate] == true - - formats << "%-#{colwidth + 2}s" if colwidth - start = colwidth ? 1 : 0 - - colcount = array.max { |a, b| a.size <=> b.size }.size - - maximas = [] - - start.upto(colcount - 1) do |index| - maxima = array.map { |row| row[index] ? row[index].to_s.size : 0 }.max - maximas << maxima - if index == colcount - 1 - # Don't output 2 trailing spaces when printing the last column - formats << "%-s" - else - formats << "%-#{maxima + 2}s" - end - end - - formats[0] = formats[0].insert(0, " " * indent) - formats << "%s" - - array.each do |row| - sentence = "" - - row.each_with_index do |column, index| - maxima = maximas[index] - - if column.is_a?(Numeric) - if index == row.size - 1 - # Don't output 2 trailing spaces when printing the last column - f = "%#{maxima}s" - else - f = "%#{maxima}s " - end - else - f = formats[index] - end - sentence << f % column.to_s - end - - sentence = truncate(sentence, options[:truncate]) if options[:truncate] - stdout.puts sentence - end - end - - # Prints a long string, word-wrapping the text to the current width of the - # terminal display. Ideal for printing heredocs. - # - # ==== Parameters - # String - # - # ==== Options - # indent:: Indent each line of the printed paragraph by indent value. - # - def print_wrapped(message, options = {}) - indent = options[:indent] || 0 - width = terminal_width - indent - paras = message.split("\n\n") - - paras.map! do |unwrapped| - unwrapped.strip.gsub(/\n/, " ").squeeze(" ").gsub(/.{1,#{width}}(?:\s|\Z)/) { ($& + 5.chr).gsub(/\n\005/, "\n").gsub(/\005/, "\n") } - end - - paras.each do |para| - para.split("\n").each do |line| - stdout.puts line.insert(0, " " * indent) - end - stdout.puts unless para == paras.last - end - end - - # Deals with file collision and returns true if the file should be - # overwritten and false otherwise. If a block is given, it uses the block - # response as the content for the diff. - # - # ==== Parameters - # destination:: the destination file to solve conflicts - # block:: an optional block that returns the value to be used in diff - # - def file_collision(destination) # rubocop:disable MethodLength - return true if @always_force - options = block_given? ? "[Ynaqdh]" : "[Ynaqh]" - - loop do - answer = ask( - %[Overwrite #{destination}? (enter "h" for help) #{options}], - :add_to_history => false - ) - - case answer - when is?(:yes), is?(:force), "" - return true - when is?(:no), is?(:skip) - return false - when is?(:always) - return @always_force = true - when is?(:quit) - say "Aborting..." - fail SystemExit - when is?(:diff) - show_diff(destination, yield) if block_given? - say "Retrying..." - else - say file_collision_help - end - end - end - - # This code was copied from Rake, available under MIT-LICENSE - # Copyright (c) 2003, 2004 Jim Weirich - def terminal_width - if ENV["THOR_COLUMNS"] - result = ENV["THOR_COLUMNS"].to_i - else - result = unix? ? dynamic_width : 80 - end - result < 10 ? 80 : result - rescue - 80 - end - - # Called if something goes wrong during the execution. This is used by Thor - # internally and should not be used inside your scripts. If something went - # wrong, you can always raise an exception. If you raise a Thor::Error, it - # will be rescued and wrapped in the method below. - # - def error(statement) - stderr.puts statement - end - - # Apply color to the given string with optional bold. Disabled in the - # Thor::Shell::Basic class. - # - def set_color(string, *args) #:nodoc: - string - end - - protected - - def prepare_message(message, *color) - spaces = " " * padding - spaces + set_color(message.to_s, *color) - end - - def can_display_colors? - false - end - - def lookup_color(color) - return color unless color.is_a?(Symbol) - self.class.const_get(color.to_s.upcase) - end - - def stdout - $stdout - end - - def stderr - $stderr - end - - def is?(value) #:nodoc: - value = value.to_s - - if value.size == 1 - /\A#{value}\z/i - else - /\A(#{value}|#{value[0, 1]})\z/i - end - end - - def file_collision_help #:nodoc: - <<-HELP - Y - yes, overwrite - n - no, do not overwrite - a - all, overwrite this and all others - q - quit, abort - d - diff, show the differences between the old and the new - h - help, show this help - HELP - end - - def show_diff(destination, content) #:nodoc: - diff_cmd = ENV["THOR_DIFF"] || ENV["RAILS_DIFF"] || "diff -u" - - Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp| - temp.write content - temp.rewind - system %(#{diff_cmd} "#{destination}" "#{temp.path}") - end - end - - def quiet? #:nodoc: - mute? || (base && base.options[:quiet]) - end - - # Calculate the dynamic width of the terminal - def dynamic_width - @dynamic_width ||= (dynamic_width_stty.nonzero? || dynamic_width_tput) - end - - def dynamic_width_stty - %x(stty size 2>/dev/null).split[1].to_i - end - - def dynamic_width_tput - %x(tput cols 2>/dev/null).to_i - end - - def unix? - RUBY_PLATFORM =~ /(aix|darwin|linux|(net|free|open)bsd|cygwin|solaris|irix|hpux)/i - end - - def truncate(string, width) - as_unicode do - chars = string.chars.to_a - if chars.length <= width - chars.join - else - ( chars[0, width - 3].join) + "..." - end - end - end - - if "".respond_to?(:encode) - def as_unicode - yield - end - else - def as_unicode - old, $KCODE = $KCODE, "U" - yield - ensure - $KCODE = old - end - end - - def ask_simply(statement, color, options) - default = options[:default] - message = [statement, ("(#{default})" if default), nil].uniq.join(" ") - message = prepare_message(message, color) - result = Thor::LineEditor.readline(message, options) - - return unless result - - result.strip! - - if default && result == "" - default - else - result - end - end - - def ask_filtered(statement, color, options) - answer_set = options[:limited_to] - correct_answer = nil - until correct_answer - answers = answer_set.join(", ") - answer = ask_simply("#{statement} [#{answers}]", color, options) - correct_answer = answer_set.include?(answer) ? answer : nil - say("Your response must be one of: [#{answers}]. Please try again.") unless correct_answer - end - correct_answer - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/color.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/color.rb deleted file mode 100644 index 744a737..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/color.rb +++ /dev/null @@ -1,149 +0,0 @@ -require "thor/shell/basic" - -class Thor - module Shell - # Inherit from Thor::Shell::Basic and add set_color behavior. Check - # Thor::Shell::Basic to see all available methods. - # - class Color < Basic - # Embed in a String to clear all previous ANSI sequences. - CLEAR = "\e[0m" - # The start of an ANSI bold sequence. - BOLD = "\e[1m" - - # Set the terminal's foreground ANSI color to black. - BLACK = "\e[30m" - # Set the terminal's foreground ANSI color to red. - RED = "\e[31m" - # Set the terminal's foreground ANSI color to green. - GREEN = "\e[32m" - # Set the terminal's foreground ANSI color to yellow. - YELLOW = "\e[33m" - # Set the terminal's foreground ANSI color to blue. - BLUE = "\e[34m" - # Set the terminal's foreground ANSI color to magenta. - MAGENTA = "\e[35m" - # Set the terminal's foreground ANSI color to cyan. - CYAN = "\e[36m" - # Set the terminal's foreground ANSI color to white. - WHITE = "\e[37m" - - # Set the terminal's background ANSI color to black. - ON_BLACK = "\e[40m" - # Set the terminal's background ANSI color to red. - ON_RED = "\e[41m" - # Set the terminal's background ANSI color to green. - ON_GREEN = "\e[42m" - # Set the terminal's background ANSI color to yellow. - ON_YELLOW = "\e[43m" - # Set the terminal's background ANSI color to blue. - ON_BLUE = "\e[44m" - # Set the terminal's background ANSI color to magenta. - ON_MAGENTA = "\e[45m" - # Set the terminal's background ANSI color to cyan. - ON_CYAN = "\e[46m" - # Set the terminal's background ANSI color to white. - ON_WHITE = "\e[47m" - - # Set color by using a string or one of the defined constants. If a third - # option is set to true, it also adds bold to the string. This is based - # on Highline implementation and it automatically appends CLEAR to the end - # of the returned String. - # - # Pass foreground, background and bold options to this method as - # symbols. - # - # Example: - # - # set_color "Hi!", :red, :on_white, :bold - # - # The available colors are: - # - # :bold - # :black - # :red - # :green - # :yellow - # :blue - # :magenta - # :cyan - # :white - # :on_black - # :on_red - # :on_green - # :on_yellow - # :on_blue - # :on_magenta - # :on_cyan - # :on_white - def set_color(string, *colors) - if colors.compact.empty? || !can_display_colors? - string - elsif colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) } - ansi_colors = colors.map { |color| lookup_color(color) } - "#{ansi_colors.join}#{string}#{CLEAR}" - else - # The old API was `set_color(color, bold=boolean)`. We - # continue to support the old API because you should never - # break old APIs unnecessarily :P - foreground, bold = colors - foreground = self.class.const_get(foreground.to_s.upcase) if foreground.is_a?(Symbol) - - bold = bold ? BOLD : "" - "#{bold}#{foreground}#{string}#{CLEAR}" - end - end - - protected - - def can_display_colors? - stdout.tty? - end - - # Overwrite show_diff to show diff with colors if Diff::LCS is - # available. - # - def show_diff(destination, content) #:nodoc: - if diff_lcs_loaded? && ENV["THOR_DIFF"].nil? && ENV["RAILS_DIFF"].nil? - actual = File.binread(destination).to_s.split("\n") - content = content.to_s.split("\n") - - Diff::LCS.sdiff(actual, content).each do |diff| - output_diff_line(diff) - end - else - super - end - end - - def output_diff_line(diff) #:nodoc: - case diff.action - when "-" - say "- #{diff.old_element.chomp}", :red, true - when "+" - say "+ #{diff.new_element.chomp}", :green, true - when "!" - say "- #{diff.old_element.chomp}", :red, true - say "+ #{diff.new_element.chomp}", :green, true - else - say " #{diff.old_element.chomp}", nil, true - end - end - - # Check if Diff::LCS is loaded. If it is, use it to create pretty output - # for diff. - # - def diff_lcs_loaded? #:nodoc: - return true if defined?(Diff::LCS) - return @diff_lcs_loaded unless @diff_lcs_loaded.nil? - - @diff_lcs_loaded = begin - require "diff/lcs" - true - rescue LoadError - false - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/html.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/html.rb deleted file mode 100644 index 525f9a3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/shell/html.rb +++ /dev/null @@ -1,126 +0,0 @@ -require "thor/shell/basic" - -class Thor - module Shell - # Inherit from Thor::Shell::Basic and add set_color behavior. Check - # Thor::Shell::Basic to see all available methods. - # - class HTML < Basic - # The start of an HTML bold sequence. - BOLD = "font-weight: bold" - - # Set the terminal's foreground HTML color to black. - BLACK = "color: black" - # Set the terminal's foreground HTML color to red. - RED = "color: red" - # Set the terminal's foreground HTML color to green. - GREEN = "color: green" - # Set the terminal's foreground HTML color to yellow. - YELLOW = "color: yellow" - # Set the terminal's foreground HTML color to blue. - BLUE = "color: blue" - # Set the terminal's foreground HTML color to magenta. - MAGENTA = "color: magenta" - # Set the terminal's foreground HTML color to cyan. - CYAN = "color: cyan" - # Set the terminal's foreground HTML color to white. - WHITE = "color: white" - - # Set the terminal's background HTML color to black. - ON_BLACK = "background-color: black" - # Set the terminal's background HTML color to red. - ON_RED = "background-color: red" - # Set the terminal's background HTML color to green. - ON_GREEN = "background-color: green" - # Set the terminal's background HTML color to yellow. - ON_YELLOW = "background-color: yellow" - # Set the terminal's background HTML color to blue. - ON_BLUE = "background-color: blue" - # Set the terminal's background HTML color to magenta. - ON_MAGENTA = "background-color: magenta" - # Set the terminal's background HTML color to cyan. - ON_CYAN = "background-color: cyan" - # Set the terminal's background HTML color to white. - ON_WHITE = "background-color: white" - - # Set color by using a string or one of the defined constants. If a third - # option is set to true, it also adds bold to the string. This is based - # on Highline implementation and it automatically appends CLEAR to the end - # of the returned String. - # - def set_color(string, *colors) - if colors.all? { |color| color.is_a?(Symbol) || color.is_a?(String) } - html_colors = colors.map { |color| lookup_color(color) } - "#{string}" - else - color, bold = colors - html_color = self.class.const_get(color.to_s.upcase) if color.is_a?(Symbol) - styles = [html_color] - styles << BOLD if bold - "#{string}" - end - end - - # Ask something to the user and receives a response. - # - # ==== Example - # ask("What is your name?") - # - # TODO: Implement #ask for Thor::Shell::HTML - def ask(statement, color = nil) - fail NotImplementedError, "Implement #ask for Thor::Shell::HTML" - end - - protected - - def can_display_colors? - true - end - - # Overwrite show_diff to show diff with colors if Diff::LCS is - # available. - # - def show_diff(destination, content) #:nodoc: - if diff_lcs_loaded? && ENV["THOR_DIFF"].nil? && ENV["RAILS_DIFF"].nil? - actual = File.binread(destination).to_s.split("\n") - content = content.to_s.split("\n") - - Diff::LCS.sdiff(actual, content).each do |diff| - output_diff_line(diff) - end - else - super - end - end - - def output_diff_line(diff) #:nodoc: - case diff.action - when "-" - say "- #{diff.old_element.chomp}", :red, true - when "+" - say "+ #{diff.new_element.chomp}", :green, true - when "!" - say "- #{diff.old_element.chomp}", :red, true - say "+ #{diff.new_element.chomp}", :green, true - else - say " #{diff.old_element.chomp}", nil, true - end - end - - # Check if Diff::LCS is loaded. If it is, use it to create pretty output - # for diff. - # - def diff_lcs_loaded? #:nodoc: - return true if defined?(Diff::LCS) - return @diff_lcs_loaded unless @diff_lcs_loaded.nil? - - @diff_lcs_loaded = begin - require "diff/lcs" - true - rescue LoadError - false - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/util.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/util.rb deleted file mode 100644 index f4ec83a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/util.rb +++ /dev/null @@ -1,267 +0,0 @@ -require "rbconfig" - -class Thor - module Sandbox #:nodoc: - end - - # This module holds several utilities: - # - # 1) Methods to convert thor namespaces to constants and vice-versa. - # - # Thor::Util.namespace_from_thor_class(Foo::Bar::Baz) #=> "foo:bar:baz" - # - # 2) Loading thor files and sandboxing: - # - # Thor::Util.load_thorfile("~/.thor/foo") - # - module Util - class << self - # Receives a namespace and search for it in the Thor::Base subclasses. - # - # ==== Parameters - # namespace:: The namespace to search for. - # - def find_by_namespace(namespace) - namespace = "default#{namespace}" if namespace.empty? || namespace =~ /^:/ - Thor::Base.subclasses.detect { |klass| klass.namespace == namespace } - end - - # Receives a constant and converts it to a Thor namespace. Since Thor - # commands can be added to a sandbox, this method is also responsable for - # removing the sandbox namespace. - # - # This method should not be used in general because it's used to deal with - # older versions of Thor. On current versions, if you need to get the - # namespace from a class, just call namespace on it. - # - # ==== Parameters - # constant:: The constant to be converted to the thor path. - # - # ==== Returns - # String:: If we receive Foo::Bar::Baz it returns "foo:bar:baz" - # - def namespace_from_thor_class(constant) - constant = constant.to_s.gsub(/^Thor::Sandbox::/, "") - constant = snake_case(constant).squeeze(":") - constant - end - - # Given the contents, evaluate it inside the sandbox and returns the - # namespaces defined in the sandbox. - # - # ==== Parameters - # contents - # - # ==== Returns - # Array[Object] - # - def namespaces_in_content(contents, file = __FILE__) - old_constants = Thor::Base.subclasses.dup - Thor::Base.subclasses.clear - - load_thorfile(file, contents) - - new_constants = Thor::Base.subclasses.dup - Thor::Base.subclasses.replace(old_constants) - - new_constants.map! { |c| c.namespace } - new_constants.compact! - new_constants - end - - # Returns the thor classes declared inside the given class. - # - def thor_classes_in(klass) - stringfied_constants = klass.constants.map { |c| c.to_s } - Thor::Base.subclasses.select do |subclass| - next unless subclass.name - stringfied_constants.include?(subclass.name.gsub("#{klass.name}::", "")) - end - end - - # Receives a string and convert it to snake case. SnakeCase returns snake_case. - # - # ==== Parameters - # String - # - # ==== Returns - # String - # - def snake_case(str) - return str.downcase if str =~ /^[A-Z_]+$/ - str.gsub(/\B[A-Z]/, '_\&').squeeze("_") =~ /_*(.*)/ - $+.downcase - end - - # Receives a string and convert it to camel case. camel_case returns CamelCase. - # - # ==== Parameters - # String - # - # ==== Returns - # String - # - def camel_case(str) - return str if str !~ /_/ && str =~ /[A-Z]+.*/ - str.split("_").map { |i| i.capitalize }.join - end - - # Receives a namespace and tries to retrieve a Thor or Thor::Group class - # from it. It first searches for a class using the all the given namespace, - # if it's not found, removes the highest entry and searches for the class - # again. If found, returns the highest entry as the class name. - # - # ==== Examples - # - # class Foo::Bar < Thor - # def baz - # end - # end - # - # class Baz::Foo < Thor::Group - # end - # - # Thor::Util.namespace_to_thor_class("foo:bar") #=> Foo::Bar, nil # will invoke default command - # Thor::Util.namespace_to_thor_class("baz:foo") #=> Baz::Foo, nil - # Thor::Util.namespace_to_thor_class("foo:bar:baz") #=> Foo::Bar, "baz" - # - # ==== Parameters - # namespace - # - def find_class_and_command_by_namespace(namespace, fallback = true) - if namespace.include?(":") # look for a namespaced command - pieces = namespace.split(":") - command = pieces.pop - klass = Thor::Util.find_by_namespace(pieces.join(":")) - end - unless klass # look for a Thor::Group with the right name - klass, command = Thor::Util.find_by_namespace(namespace), nil - end - if !klass && fallback # try a command in the default namespace - command = namespace - klass = Thor::Util.find_by_namespace("") - end - [klass, command] - end - alias_method :find_class_and_task_by_namespace, :find_class_and_command_by_namespace - - # Receives a path and load the thor file in the path. The file is evaluated - # inside the sandbox to avoid namespacing conflicts. - # - def load_thorfile(path, content = nil, debug = false) - content ||= File.binread(path) - - begin - Thor::Sandbox.class_eval(content, path) - rescue StandardError => e - $stderr.puts("WARNING: unable to load thorfile #{path.inspect}: #{e.message}") - if debug - $stderr.puts(*e.backtrace) - else - $stderr.puts(e.backtrace.first) - end - end - end - - def user_home # rubocop:disable MethodLength - @@user_home ||= if ENV["HOME"] - ENV["HOME"] - elsif ENV["USERPROFILE"] - ENV["USERPROFILE"] - elsif ENV["HOMEDRIVE"] && ENV["HOMEPATH"] - File.join(ENV["HOMEDRIVE"], ENV["HOMEPATH"]) - elsif ENV["APPDATA"] - ENV["APPDATA"] - else - begin - File.expand_path("~") - rescue - if File::ALT_SEPARATOR - "C:/" - else - "/" - end - end - end - end - - # Returns the root where thor files are located, depending on the OS. - # - def thor_root - File.join(user_home, ".thor").gsub(/\\/, "/") - end - - # Returns the files in the thor root. On Windows thor_root will be something - # like this: - # - # C:\Documents and Settings\james\.thor - # - # If we don't #gsub the \ character, Dir.glob will fail. - # - def thor_root_glob - files = Dir["#{escape_globs(thor_root)}/*"] - - files.map! do |file| - File.directory?(file) ? File.join(file, "main.thor") : file - end - end - - # Where to look for Thor files. - # - def globs_for(path) - path = escape_globs(path) - ["#{path}/Thorfile", "#{path}/*.thor", "#{path}/tasks/*.thor", "#{path}/lib/tasks/*.thor"] - end - - # Return the path to the ruby interpreter taking into account multiple - # installations and windows extensions. - # - def ruby_command # rubocop:disable MethodLength - @ruby_command ||= begin - ruby_name = RbConfig::CONFIG["ruby_install_name"] - ruby = File.join(RbConfig::CONFIG["bindir"], ruby_name) - ruby << RbConfig::CONFIG["EXEEXT"] - - # avoid using different name than ruby (on platforms supporting links) - if ruby_name != "ruby" && File.respond_to?(:readlink) - begin - alternate_ruby = File.join(RbConfig::CONFIG["bindir"], "ruby") - alternate_ruby << RbConfig::CONFIG["EXEEXT"] - - # ruby is a symlink - if File.symlink? alternate_ruby - linked_ruby = File.readlink alternate_ruby - - # symlink points to 'ruby_install_name' - ruby = alternate_ruby if linked_ruby == ruby_name || linked_ruby == ruby - end - rescue NotImplementedError # rubocop:disable HandleExceptions - # just ignore on windows - end - end - - # escape string in case path to ruby executable contain spaces. - ruby.sub!(/.*\s.*/m, '"\&"') - ruby - end - end - - # Returns a string that has had any glob characters escaped. - # The glob characters are `* ? { } [ ]`. - # - # ==== Examples - # - # Thor::Util.escape_globs('[apps]') # => '\[apps\]' - # - # ==== Parameters - # String - # - # ==== Returns - # String - # - def escape_globs(path) - path.to_s.gsub(/[*?{}\[\]]/, '\\\\\\&') - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/version.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/version.rb deleted file mode 100644 index 1391ce4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/lib/thor/version.rb +++ /dev/null @@ -1,3 +0,0 @@ -class Thor - VERSION = "0.19.1" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/create_file_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/create_file_spec.rb deleted file mode 100644 index 4bf82c9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/create_file_spec.rb +++ /dev/null @@ -1,168 +0,0 @@ -require "helper" -require "thor/actions" - -describe Thor::Actions::CreateFile do - before do - @silence = false - ::FileUtils.rm_rf(destination_root) - end - - def create_file(destination = nil, config = {}, options = {}) - @base = MyCounter.new([1, 2], options, :destination_root => destination_root) - allow(@base).to receive(:file_name).and_return("rdoc") - - @action = Thor::Actions::CreateFile.new(@base, destination, "CONFIGURATION", {:verbose => !@silence}.merge(config)) - end - - def invoke! - capture(:stdout) { @action.invoke! } - end - - def revoke! - capture(:stdout) { @action.revoke! } - end - - def silence! - @silence = true - end - - describe "#invoke!" do - it "creates a file" do - create_file("doc/config.rb") - invoke! - expect(File.exist?(File.join(destination_root, "doc/config.rb"))).to be true - end - - it "does not create a file if pretending" do - create_file("doc/config.rb", {}, :pretend => true) - invoke! - expect(File.exist?(File.join(destination_root, "doc/config.rb"))).to be false - end - - it "shows created status to the user" do - create_file("doc/config.rb") - expect(invoke!).to eq(" create doc/config.rb\n") - end - - it "does not show any information if log status is false" do - silence! - create_file("doc/config.rb") - expect(invoke!).to be_empty - end - - it "returns the given destination" do - capture(:stdout) do - expect(create_file("doc/config.rb").invoke!).to eq("doc/config.rb") - end - end - - it "converts encoded instructions" do - create_file("doc/%file_name%.rb.tt") - invoke! - expect(File.exist?(File.join(destination_root, "doc/rdoc.rb.tt"))).to be true - end - - describe "when file exists" do - before do - create_file("doc/config.rb") - invoke! - end - - describe "and is identical" do - it "shows identical status" do - create_file("doc/config.rb") - invoke! - expect(invoke!).to eq(" identical doc/config.rb\n") - end - end - - describe "and is not identical" do - before do - File.open(File.join(destination_root, "doc/config.rb"), "w") { |f| f.write("FOO = 3") } - end - - it "shows forced status to the user if force is given" do - expect(create_file("doc/config.rb", {}, :force => true)).not_to be_identical - expect(invoke!).to eq(" force doc/config.rb\n") - end - - it "shows skipped status to the user if skip is given" do - expect(create_file("doc/config.rb", {}, :skip => true)).not_to be_identical - expect(invoke!).to eq(" skip doc/config.rb\n") - end - - it "shows forced status to the user if force is configured" do - expect(create_file("doc/config.rb", :force => true)).not_to be_identical - expect(invoke!).to eq(" force doc/config.rb\n") - end - - it "shows skipped status to the user if skip is configured" do - expect(create_file("doc/config.rb", :skip => true)).not_to be_identical - expect(invoke!).to eq(" skip doc/config.rb\n") - end - - it "shows conflict status to the user" do - file = File.join(destination_root, "doc/config.rb") - expect(create_file("doc/config.rb")).not_to be_identical - expect(Thor::LineEditor).to receive(:readline).with("Overwrite #{file}? (enter \"h\" for help) [Ynaqdh] ", anything).and_return("s") - - content = invoke! - expect(content).to match(/conflict doc\/config\.rb/) - expect(content).to match(/skip doc\/config\.rb/) - end - - it "creates the file if the file collision menu returns true" do - create_file("doc/config.rb") - expect(Thor::LineEditor).to receive(:readline).and_return("y") - expect(invoke!).to match(/force doc\/config\.rb/) - end - - it "skips the file if the file collision menu returns false" do - create_file("doc/config.rb") - expect(Thor::LineEditor).to receive(:readline).and_return("n") - expect(invoke!).to match(/skip doc\/config\.rb/) - end - - it "executes the block given to show file content" do - create_file("doc/config.rb") - expect(Thor::LineEditor).to receive(:readline).and_return("d", "n") - expect(@base.shell).to receive(:system).with(/diff -u/) - invoke! - end - end - end - end - - describe "#revoke!" do - it "removes the destination file" do - create_file("doc/config.rb") - invoke! - revoke! - expect(File.exist?(@action.destination)).to be false - end - - it "does not raise an error if the file does not exist" do - create_file("doc/config.rb") - revoke! - expect(File.exist?(@action.destination)).to be false - end - end - - describe "#exists?" do - it "returns true if the destination file exists" do - create_file("doc/config.rb") - expect(@action.exists?).to be false - invoke! - expect(@action.exists?).to be true - end - end - - describe "#identical?" do - it "returns true if the destination file exists and is identical" do - create_file("doc/config.rb") - expect(@action.identical?).to be false - invoke! - expect(@action.identical?).to be true - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/create_link_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/create_link_spec.rb deleted file mode 100644 index 7eaab7e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/create_link_spec.rb +++ /dev/null @@ -1,96 +0,0 @@ -require "helper" -require "thor/actions" -require "tempfile" - -describe Thor::Actions::CreateLink do - before do - @silence = false - @hardlink_to = File.join(Dir.tmpdir, "linkdest.rb") - ::FileUtils.rm_rf(destination_root) - ::FileUtils.rm_rf(@hardlink_to) - end - - def create_link(destination = nil, config = {}, options = {}) - @base = MyCounter.new([1, 2], options, :destination_root => destination_root) - allow(@base).to receive(:file_name).and_return("rdoc") - - @tempfile = Tempfile.new("config.rb") - - @action = Thor::Actions::CreateLink.new(@base, destination, @tempfile.path, - {:verbose => !@silence}.merge(config)) - end - - def invoke! - capture(:stdout) { @action.invoke! } - end - - def revoke! - capture(:stdout) { @action.revoke! } - end - - def silence! - @silence = true - end - - describe "#invoke!" do - it "creates a symbolic link for :symbolic => true" do - create_link("doc/config.rb", :symbolic => true) - invoke! - destination_path = File.join(destination_root, "doc/config.rb") - expect(File.exist?(destination_path)).to be true - expect(File.symlink?(destination_path)).to be true - end - - it "creates a hard link for :symbolic => false" do - create_link(@hardlink_to, :symbolic => false) - invoke! - destination_path = @hardlink_to - expect(File.exist?(destination_path)).to be true - expect(File.symlink?(destination_path)).to be false - end - - it "creates a symbolic link by default" do - create_link("doc/config.rb") - invoke! - destination_path = File.join(destination_root, "doc/config.rb") - expect(File.exist?(destination_path)).to be true - expect(File.symlink?(destination_path)).to be true - end - - it "does not create a link if pretending" do - create_link("doc/config.rb", {}, :pretend => true) - invoke! - expect(File.exist?(File.join(destination_root, "doc/config.rb"))).to be false - end - - it "shows created status to the user" do - create_link("doc/config.rb") - expect(invoke!).to eq(" create doc/config.rb\n") - end - - it "does not show any information if log status is false" do - silence! - create_link("doc/config.rb") - expect(invoke!).to be_empty - end - end - - describe "#identical?" do - it "returns true if the destination link exists and is identical" do - create_link("doc/config.rb") - expect(@action.identical?).to be false - invoke! - expect(@action.identical?).to be true - end - end - - describe "#revoke!" do - it "removes the symbolic link of non-existent destination" do - create_link("doc/config.rb") - invoke! - File.delete(@tempfile.path) - revoke! - expect(File.symlink?(@action.destination)).to be false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/directory_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/directory_spec.rb deleted file mode 100644 index 23a1637..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/directory_spec.rb +++ /dev/null @@ -1,169 +0,0 @@ -require "helper" -require "thor/actions" - -describe Thor::Actions::Directory do - before do - ::FileUtils.rm_rf(destination_root) - allow(invoker).to receive(:file_name).and_return("rdoc") - end - - def invoker - @invoker ||= WhinyGenerator.new([1, 2], {}, :destination_root => destination_root) - end - - def revoker - @revoker ||= WhinyGenerator.new([1, 2], {}, :destination_root => destination_root, :behavior => :revoke) - end - - def invoke!(*args, &block) - capture(:stdout) { invoker.directory(*args, &block) } - end - - def revoke!(*args, &block) - capture(:stdout) { revoker.directory(*args, &block) } - end - - def exists_and_identical?(source_path, destination_path) - %w[config.rb README].each do |file| - source = File.join(source_root, source_path, file) - destination = File.join(destination_root, destination_path, file) - - expect(File.exist?(destination)).to be true - expect(FileUtils.identical?(source, destination)).to be true - end - end - - describe "#invoke!" do - it "raises an error if the source does not exist" do - expect do - invoke! "unknown" - end.to raise_error(Thor::Error, /Could not find "unknown" in any of your source paths/) - end - - it "does not create a directory in pretend mode" do - invoke! "doc", "ghost", :pretend => true - expect(File.exist?("ghost")).to be false - end - - it "copies the whole directory recursively to the default destination" do - invoke! "doc" - exists_and_identical?("doc", "doc") - end - - it "copies the whole directory recursively to the specified destination" do - invoke! "doc", "docs" - exists_and_identical?("doc", "docs") - end - - it "copies only the first level files if recursive" do - invoke! ".", "commands", :recursive => false - - file = File.join(destination_root, "commands", "group.thor") - expect(File.exist?(file)).to be true - - file = File.join(destination_root, "commands", "doc") - expect(File.exist?(file)).to be false - - file = File.join(destination_root, "commands", "doc", "README") - expect(File.exist?(file)).to be false - end - - it "ignores files within excluding/ directories when exclude_pattern is provided" do - invoke! "doc", "docs", :exclude_pattern => /excluding\// - file = File.join(destination_root, "docs", "excluding", "rdoc.rb") - expect(File.exist?(file)).to be false - end - - it "copies and evaluates files within excluding/ directory when no exclude_pattern is present" do - invoke! "doc", "docs" - file = File.join(destination_root, "docs", "excluding", "rdoc.rb") - expect(File.exist?(file)).to be true - expect(File.read(file)).to eq("BAR = BAR\n") - end - - it "copies files from the source relative to the current path" do - invoker.inside "doc" do - invoke! "." - end - exists_and_identical?("doc", "doc") - end - - it "copies and evaluates templates" do - invoke! "doc", "docs" - file = File.join(destination_root, "docs", "rdoc.rb") - expect(File.exist?(file)).to be true - expect(File.read(file)).to eq("FOO = FOO\n") - end - - it "copies directories and preserves file mode" do - invoke! "preserve", "preserved", :mode => :preserve - original = File.join(source_root, "preserve", "script.sh") - copy = File.join(destination_root, "preserved", "script.sh") - expect(File.stat(original).mode).to eq(File.stat(copy).mode) - end - - it "copies directories" do - invoke! "doc", "docs" - file = File.join(destination_root, "docs", "components") - expect(File.exist?(file)).to be true - expect(File.directory?(file)).to be true - end - - it "does not copy .empty_directory files" do - invoke! "doc", "docs" - file = File.join(destination_root, "docs", "components", ".empty_directory") - expect(File.exist?(file)).to be false - end - - it "copies directories even if they are empty" do - invoke! "doc/components", "docs/components" - file = File.join(destination_root, "docs", "components") - expect(File.exist?(file)).to be true - end - - it "does not copy empty directories twice" do - content = invoke!("doc/components", "docs/components") - expect(content).not_to match(/exist/) - end - - it "logs status" do - content = invoke!("doc") - expect(content).to match(/create doc\/README/) - expect(content).to match(/create doc\/config\.rb/) - expect(content).to match(/create doc\/rdoc\.rb/) - expect(content).to match(/create doc\/components/) - end - - it "yields a block" do - checked = false - invoke!("doc") do |content| - checked ||= !!(content =~ /FOO/) - end - expect(checked).to be true - end - - it "works with glob characters in the path" do - content = invoke!("app{1}") - expect(content).to match(/create app\{1\}\/README/) - end - end - - describe "#revoke!" do - it "removes the destination file" do - invoke! "doc" - revoke! "doc" - - expect(File.exist?(File.join(destination_root, "doc", "README"))).to be false - expect(File.exist?(File.join(destination_root, "doc", "config.rb"))).to be false - expect(File.exist?(File.join(destination_root, "doc", "components"))).to be false - end - - it "works with glob characters in the path" do - invoke! "app{1}" - expect(File.exist?(File.join(destination_root, "app{1}", "README"))).to be true - - revoke! "app{1}" - expect(File.exist?(File.join(destination_root, "app{1}", "README"))).to be false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/empty_directory_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/empty_directory_spec.rb deleted file mode 100644 index 7304a24..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/empty_directory_spec.rb +++ /dev/null @@ -1,129 +0,0 @@ -require "helper" -require "thor/actions" - -describe Thor::Actions::EmptyDirectory do - before do - ::FileUtils.rm_rf(destination_root) - end - - def empty_directory(destination, options = {}) - @action = Thor::Actions::EmptyDirectory.new(base, destination) - end - - def invoke! - capture(:stdout) { @action.invoke! } - end - - def revoke! - capture(:stdout) { @action.revoke! } - end - - def base - @base ||= MyCounter.new([1, 2], {}, :destination_root => destination_root) - end - - describe "#destination" do - it "returns the full destination with the destination_root" do - expect(empty_directory("doc").destination).to eq(File.join(destination_root, "doc")) - end - - it "takes relative root into account" do - base.inside("doc") do - expect(empty_directory("contents").destination).to eq(File.join(destination_root, "doc", "contents")) - end - end - end - - describe "#relative_destination" do - it "returns the relative destination to the original destination root" do - base.inside("doc") do - expect(empty_directory("contents").relative_destination).to eq("doc/contents") - end - end - end - - describe "#given_destination" do - it "returns the destination supplied by the user" do - base.inside("doc") do - expect(empty_directory("contents").given_destination).to eq("contents") - end - end - end - - describe "#invoke!" do - it "copies the file to the specified destination" do - empty_directory("doc") - invoke! - expect(File.exist?(File.join(destination_root, "doc"))).to be true - end - - it "shows created status to the user" do - empty_directory("doc") - expect(invoke!).to eq(" create doc\n") - end - - it "does not create a directory if pretending" do - base.inside("foo", :pretend => true) do - empty_directory("ghost") - end - expect(File.exist?(File.join(base.destination_root, "ghost"))).to be false - end - - describe "when directory exists" do - it "shows exist status" do - empty_directory("doc") - invoke! - expect(invoke!).to eq(" exist doc\n") - end - end - end - - describe "#revoke!" do - it "removes the destination file" do - empty_directory("doc") - invoke! - revoke! - expect(File.exist?(@action.destination)).to be false - end - end - - describe "#exists?" do - it "returns true if the destination file exists" do - empty_directory("doc") - expect(@action.exists?).to be false - invoke! - expect(@action.exists?).to be true - end - end - - context "protected methods" do - describe "#convert_encoded_instructions" do - before do - empty_directory("test_dir") - allow(@action.base).to receive(:file_name).and_return("expected") - end - - it "accepts and executes a 'legal' %\w+% encoded instruction" do - expect(@action.send(:convert_encoded_instructions, "%file_name%.txt")).to eq("expected.txt") - end - - it "accepts and executes a private %\w+% encoded instruction" do - @action.base.extend Module.new { - def private_file_name - "expected" - end - private :private_file_name - } - expect(@action.send(:convert_encoded_instructions, "%private_file_name%.txt")).to eq("expected.txt") - end - - it "ignores an 'illegal' %\w+% encoded instruction" do - expect(@action.send(:convert_encoded_instructions, "%some_name%.txt")).to eq("%some_name%.txt") - end - - it "ignores incorrectly encoded instruction" do - expect(@action.send(:convert_encoded_instructions, "%some.name%.txt")).to eq("%some.name%.txt") - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/file_manipulation_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/file_manipulation_spec.rb deleted file mode 100644 index 878b438..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/file_manipulation_spec.rb +++ /dev/null @@ -1,392 +0,0 @@ -require "helper" - -class Application; end - -describe Thor::Actions do - def runner(options = {}) - @runner ||= MyCounter.new([1], options, :destination_root => destination_root) - end - - def action(*args, &block) - capture(:stdout) { runner.send(*args, &block) } - end - - def exists_and_identical?(source, destination) - destination = File.join(destination_root, destination) - expect(File.exist?(destination)).to be true - - source = File.join(source_root, source) - expect(FileUtils).to be_identical(source, destination) - end - - def file - File.join(destination_root, "foo") - end - - before do - ::FileUtils.rm_rf(destination_root) - end - - describe "#chmod" do - it "executes the command given" do - expect(FileUtils).to receive(:chmod_R).with(0755, file) # rubocop:disable SymbolName - action :chmod, "foo", 0755 - end - - it "does not execute the command if pretending" do - expect(FileUtils).not_to receive(:chmod_R) # rubocop:disable SymbolName - runner(:pretend => true) - action :chmod, "foo", 0755 - end - - it "logs status" do - expect(FileUtils).to receive(:chmod_R).with(0755, file) # rubocop:disable SymbolName - expect(action(:chmod, "foo", 0755)).to eq(" chmod foo\n") - end - - it "does not log status if required" do - expect(FileUtils).to receive(:chmod_R).with(0755, file) # rubocop:disable SymbolName - expect(action(:chmod, "foo", 0755, :verbose => false)).to be_empty - end - end - - describe "#copy_file" do - it "copies file from source to default destination" do - action :copy_file, "command.thor" - exists_and_identical?("command.thor", "command.thor") - end - - it "copies file from source to the specified destination" do - action :copy_file, "command.thor", "foo.thor" - exists_and_identical?("command.thor", "foo.thor") - end - - it "copies file from the source relative to the current path" do - runner.inside("doc") do - action :copy_file, "README" - end - exists_and_identical?("doc/README", "doc/README") - end - - it "copies file from source to default destination and preserves file mode" do - action :copy_file, "preserve/script.sh", :mode => :preserve - original = File.join(source_root, "preserve/script.sh") - copy = File.join(destination_root, "preserve/script.sh") - expect(File.stat(original).mode).to eq(File.stat(copy).mode) - end - - it "logs status" do - expect(action(:copy_file, "command.thor")).to eq(" create command.thor\n") - end - - it "accepts a block to change output" do - action :copy_file, "command.thor" do |content| - "OMG" + content - end - expect(File.read(File.join(destination_root, "command.thor"))).to match(/^OMG/) - end - end - - describe "#link_file" do - it "links file from source to default destination" do - action :link_file, "command.thor" - exists_and_identical?("command.thor", "command.thor") - end - - it "links file from source to the specified destination" do - action :link_file, "command.thor", "foo.thor" - exists_and_identical?("command.thor", "foo.thor") - end - - it "links file from the source relative to the current path" do - runner.inside("doc") do - action :link_file, "README" - end - exists_and_identical?("doc/README", "doc/README") - end - - it "logs status" do - expect(action(:link_file, "command.thor")).to eq(" create command.thor\n") - end - end - - describe "#get" do - it "copies file from source to the specified destination" do - action :get, "doc/README", "docs/README" - exists_and_identical?("doc/README", "docs/README") - end - - it "uses just the source basename as destination if none is specified" do - action :get, "doc/README" - exists_and_identical?("doc/README", "README") - end - - it "allows the destination to be set as a block result" do - action(:get, "doc/README") { |c| "docs/README" } - exists_and_identical?("doc/README", "docs/README") - end - - it "yields file content to a block" do - action :get, "doc/README" do |content| - expect(content).to eq("__start__\nREADME\n__end__\n") - end - end - - it "logs status" do - expect(action(:get, "doc/README", "docs/README")).to eq(" create docs/README\n") - end - - it "accepts http remote sources" do - body = "__start__\nHTTPFILE\n__end__\n" - FakeWeb.register_uri(:get, "http://example.com/file.txt", :body => body) - action :get, "http://example.com/file.txt" do |content| - expect(content).to eq(body) - end - FakeWeb.clean_registry - end - - it "accepts https remote sources" do - body = "__start__\nHTTPSFILE\n__end__\n" - FakeWeb.register_uri(:get, "https://example.com/file.txt", :body => body) - action :get, "https://example.com/file.txt" do |content| - expect(content).to eq(body) - end - FakeWeb.clean_registry - end - end - - describe "#template" do - it "allows using block helpers in the template" do - action :template, "doc/block_helper.rb" - - file = File.join(destination_root, "doc/block_helper.rb") - expect(File.read(file)).to eq("Hello world!") - end - - it "evaluates the template given as source" do - runner.instance_variable_set("@klass", "Config") - action :template, "doc/config.rb" - - file = File.join(destination_root, "doc/config.rb") - expect(File.read(file)).to eq("class Config; end\n") - end - - it "copies the template to the specified destination" do - runner.instance_variable_set("@klass", "Config") - action :template, "doc/config.rb", "doc/configuration.rb" - file = File.join(destination_root, "doc/configuration.rb") - expect(File.exist?(file)).to be true - end - - it "converts encoded instructions" do - expect(runner).to receive(:file_name).and_return("rdoc") - action :template, "doc/%file_name%.rb.tt" - file = File.join(destination_root, "doc/rdoc.rb") - expect(File.exist?(file)).to be true - end - - it "accepts filename without .tt for template method" do - expect(runner).to receive(:file_name).and_return("rdoc") - action :template, "doc/%file_name%.rb" - file = File.join(destination_root, "doc/rdoc.rb") - expect(File.exist?(file)).to be true - end - - it "logs status" do - runner.instance_variable_set("@klass", "Config") - expect(capture(:stdout) { runner.template("doc/config.rb") }).to eq(" create doc/config.rb\n") - end - - it "accepts a block to change output" do - runner.instance_variable_set("@klass", "Config") - action :template, "doc/config.rb" do |content| - "OMG" + content - end - expect(File.read(File.join(destination_root, "doc/config.rb"))).to match(/^OMG/) - end - - it "guesses the destination name when given only a source" do - action :template, "doc/config.yaml.tt" - - file = File.join(destination_root, "doc/config.yaml") - expect(File.exist?(file)).to be true - end - end - - describe "when changing existent files" do - before do - ::FileUtils.cp_r(source_root, destination_root) - end - - def file - File.join(destination_root, "doc", "README") - end - - describe "#remove_file" do - it "removes the file given" do - action :remove_file, "doc/README" - expect(File.exist?(file)).to be false - end - - it "removes directories too" do - action :remove_dir, "doc" - expect(File.exist?(File.join(destination_root, "doc"))).to be false - end - - it "does not remove if pretending" do - runner(:pretend => true) - action :remove_file, "doc/README" - expect(File.exist?(file)).to be true - end - - it "logs status" do - expect(action(:remove_file, "doc/README")).to eq(" remove doc/README\n") - end - - it "does not log status if required" do - expect(action(:remove_file, "doc/README", :verbose => false)).to be_empty - end - end - - describe "#gsub_file" do - it "replaces the content in the file" do - action :gsub_file, "doc/README", "__start__", "START" - expect(File.binread(file)).to eq("START\nREADME\n__end__\n") - end - - it "does not replace if pretending" do - runner(:pretend => true) - action :gsub_file, "doc/README", "__start__", "START" - expect(File.binread(file)).to eq("__start__\nREADME\n__end__\n") - end - - it "accepts a block" do - action(:gsub_file, "doc/README", "__start__") { |match| match.gsub("__", "").upcase } - expect(File.binread(file)).to eq("START\nREADME\n__end__\n") - end - - it "logs status" do - expect(action(:gsub_file, "doc/README", "__start__", "START")).to eq(" gsub doc/README\n") - end - - it "does not log status if required" do - expect(action(:gsub_file, file, "__", :verbose => false) { |match| match * 2 }).to be_empty - end - end - - describe "#append_to_file" do - it "appends content to the file" do - action :append_to_file, "doc/README", "END\n" - expect(File.binread(file)).to eq("__start__\nREADME\n__end__\nEND\n") - end - - it "accepts a block" do - action(:append_to_file, "doc/README") { "END\n" } - expect(File.binread(file)).to eq("__start__\nREADME\n__end__\nEND\n") - end - - it "logs status" do - expect(action(:append_to_file, "doc/README", "END")).to eq(" append doc/README\n") - end - end - - describe "#prepend_to_file" do - it "prepends content to the file" do - action :prepend_to_file, "doc/README", "START\n" - expect(File.binread(file)).to eq("START\n__start__\nREADME\n__end__\n") - end - - it "accepts a block" do - action(:prepend_to_file, "doc/README") { "START\n" } - expect(File.binread(file)).to eq("START\n__start__\nREADME\n__end__\n") - end - - it "logs status" do - expect(action(:prepend_to_file, "doc/README", "START")).to eq(" prepend doc/README\n") - end - end - - describe "#inject_into_class" do - def file - File.join(destination_root, "application.rb") - end - - it "appends content to a class" do - action :inject_into_class, "application.rb", Application, " filter_parameters :password\n" - expect(File.binread(file)).to eq("class Application < Base\n filter_parameters :password\nend\n") - end - - it "accepts a block" do - action(:inject_into_class, "application.rb", Application) { " filter_parameters :password\n" } - expect(File.binread(file)).to eq("class Application < Base\n filter_parameters :password\nend\n") - end - - it "logs status" do - expect(action(:inject_into_class, "application.rb", Application, " filter_parameters :password\n")).to eq(" insert application.rb\n") - end - - it "does not append if class name does not match" do - action :inject_into_class, "application.rb", "App", " filter_parameters :password\n" - expect(File.binread(file)).to eq("class Application < Base\nend\n") - end - end - end - - describe "when adjusting comments" do - before do - ::FileUtils.cp_r(source_root, destination_root) - end - - def file - File.join(destination_root, "doc", "COMMENTER") - end - - unmodified_comments_file = /__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\norange\n purple\n ind#igo\n # ind#igo\n__end__/ - - describe "#uncomment_lines" do - it "uncomments all matching lines in the file" do - action :uncomment_lines, "doc/COMMENTER", "green" - expect(File.binread(file)).to match(/__start__\n greenblue\n#\n# yellowblue\n#yellowred\n greenred\norange\n purple\n ind#igo\n # ind#igo\n__end__/) - - action :uncomment_lines, "doc/COMMENTER", "red" - expect(File.binread(file)).to match(/__start__\n greenblue\n#\n# yellowblue\nyellowred\n greenred\norange\n purple\n ind#igo\n # ind#igo\n__end__/) - end - - it "correctly uncomments lines with hashes in them" do - action :uncomment_lines, "doc/COMMENTER", "ind#igo" - expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\norange\n purple\n ind#igo\n ind#igo\n__end__/) - end - - it "does not modify already uncommented lines in the file" do - action :uncomment_lines, "doc/COMMENTER", "orange" - action :uncomment_lines, "doc/COMMENTER", "purple" - expect(File.binread(file)).to match(unmodified_comments_file) - end - - it "does not uncomment the wrong line when uncommenting lines preceded by blank commented line" do - action :uncomment_lines, "doc/COMMENTER", "yellow" - expect(File.binread(file)).to match(/__start__\n # greenblue\n#\nyellowblue\nyellowred\n #greenred\norange\n purple\n ind#igo\n # ind#igo\n__end__/) - end - end - - describe "#comment_lines" do - it "comments lines which are not commented" do - action :comment_lines, "doc/COMMENTER", "orange" - expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\n# orange\n purple\n ind#igo\n # ind#igo\n__end__/) - - action :comment_lines, "doc/COMMENTER", "purple" - expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\n# orange\n # purple\n ind#igo\n # ind#igo\n__end__/) - end - - it "correctly comments lines with hashes in them" do - action :comment_lines, "doc/COMMENTER", "ind#igo" - expect(File.binread(file)).to match(/__start__\n # greenblue\n#\n# yellowblue\n#yellowred\n #greenred\norange\n purple\n # ind#igo\n # ind#igo\n__end__/) - end - - it "does not modify already commented lines" do - action :comment_lines, "doc/COMMENTER", "green" - expect(File.binread(file)).to match(unmodified_comments_file) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/inject_into_file_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/inject_into_file_spec.rb deleted file mode 100644 index 05112a1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions/inject_into_file_spec.rb +++ /dev/null @@ -1,135 +0,0 @@ -require "helper" -require "thor/actions" - -describe Thor::Actions::InjectIntoFile do - before do - ::FileUtils.rm_rf(destination_root) - ::FileUtils.cp_r(source_root, destination_root) - end - - def invoker(options = {}) - @invoker ||= MyCounter.new([1, 2], options, :destination_root => destination_root) - end - - def revoker - @revoker ||= MyCounter.new([1, 2], {}, :destination_root => destination_root, :behavior => :revoke) - end - - def invoke!(*args, &block) - capture(:stdout) { invoker.insert_into_file(*args, &block) } - end - - def revoke!(*args, &block) - capture(:stdout) { revoker.insert_into_file(*args, &block) } - end - - def file - File.join(destination_root, "doc/README") - end - - describe "#invoke!" do - it "changes the file adding content after the flag" do - invoke! "doc/README", "\nmore content", :after => "__start__" - expect(File.read(file)).to eq("__start__\nmore content\nREADME\n__end__\n") - end - - it "changes the file adding content before the flag" do - invoke! "doc/README", "more content\n", :before => "__end__" - expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n") - end - - it "accepts data as a block" do - invoke! "doc/README", :before => "__end__" do - "more content\n" - end - - expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n") - end - - it "logs status" do - expect(invoke!("doc/README", "\nmore content", :after => "__start__")).to eq(" insert doc/README\n") - end - - it "does not change the file if pretending" do - invoker :pretend => true - invoke! "doc/README", "\nmore content", :after => "__start__" - expect(File.read(file)).to eq("__start__\nREADME\n__end__\n") - end - - it "does not change the file if already includes content" do - invoke! "doc/README", :before => "__end__" do - "more content\n" - end - - expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n") - - invoke! "doc/README", :before => "__end__" do - "more content\n" - end - - expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n") - end - - it "does change the file if already includes content and :force is true" do - invoke! "doc/README", :before => "__end__" do - "more content\n" - end - - expect(File.read(file)).to eq("__start__\nREADME\nmore content\n__end__\n") - - invoke! "doc/README", :before => "__end__", :force => true do - "more content\n" - end - - expect(File.read(file)).to eq("__start__\nREADME\nmore content\nmore content\n__end__\n") - end - - end - - describe "#revoke!" do - it "subtracts the destination file after injection" do - invoke! "doc/README", "\nmore content", :after => "__start__" - revoke! "doc/README", "\nmore content", :after => "__start__" - expect(File.read(file)).to eq("__start__\nREADME\n__end__\n") - end - - it "subtracts the destination file before injection" do - invoke! "doc/README", "more content\n", :before => "__start__" - revoke! "doc/README", "more content\n", :before => "__start__" - expect(File.read(file)).to eq("__start__\nREADME\n__end__\n") - end - - it "subtracts even with double after injection" do - invoke! "doc/README", "\nmore content", :after => "__start__" - invoke! "doc/README", "\nanother stuff", :after => "__start__" - revoke! "doc/README", "\nmore content", :after => "__start__" - expect(File.read(file)).to eq("__start__\nanother stuff\nREADME\n__end__\n") - end - - it "subtracts even with double before injection" do - invoke! "doc/README", "more content\n", :before => "__start__" - invoke! "doc/README", "another stuff\n", :before => "__start__" - revoke! "doc/README", "more content\n", :before => "__start__" - expect(File.read(file)).to eq("another stuff\n__start__\nREADME\n__end__\n") - end - - it "subtracts when prepending" do - invoke! "doc/README", "more content\n", :after => /\A/ - invoke! "doc/README", "another stuff\n", :after => /\A/ - revoke! "doc/README", "more content\n", :after => /\A/ - expect(File.read(file)).to eq("another stuff\n__start__\nREADME\n__end__\n") - end - - it "subtracts when appending" do - invoke! "doc/README", "more content\n", :before => /\z/ - invoke! "doc/README", "another stuff\n", :before => /\z/ - revoke! "doc/README", "more content\n", :before => /\z/ - expect(File.read(file)).to eq("__start__\nREADME\n__end__\nanother stuff\n") - end - - it "shows progress information to the user" do - invoke!("doc/README", "\nmore content", :after => "__start__") - expect(revoke!("doc/README", "\nmore content", :after => "__start__")).to eq(" subtract doc/README\n") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions_spec.rb deleted file mode 100644 index e296780..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/actions_spec.rb +++ /dev/null @@ -1,331 +0,0 @@ -require "helper" - -describe Thor::Actions do - def runner(options = {}) - @runner ||= MyCounter.new([1], options, :destination_root => destination_root) - end - - def action(*args, &block) - capture(:stdout) { runner.send(*args, &block) } - end - - def file - File.join(destination_root, "foo") - end - - describe "on include" do - it "adds runtime options to the base class" do - expect(MyCounter.class_options.keys).to include(:pretend) - expect(MyCounter.class_options.keys).to include(:force) - expect(MyCounter.class_options.keys).to include(:quiet) - expect(MyCounter.class_options.keys).to include(:skip) - end - end - - describe "#initialize" do - it "has default behavior invoke" do - expect(runner.behavior).to eq(:invoke) - end - - it "can have behavior revoke" do - expect(MyCounter.new([1], {}, :behavior => :revoke).behavior).to eq(:revoke) - end - - it "when behavior is set to force, overwrite options" do - runner = MyCounter.new([1], {:force => false, :skip => true}, :behavior => :force) - expect(runner.behavior).to eq(:invoke) - expect(runner.options.force).to be true - expect(runner.options.skip).not_to be true - end - - it "when behavior is set to skip, overwrite options" do - runner = MyCounter.new([1], %w[--force], :behavior => :skip) - expect(runner.behavior).to eq(:invoke) - expect(runner.options.force).not_to be true - expect(runner.options.skip).to be true - end - end - - describe "accessors" do - describe "#destination_root=" do - it "gets the current directory and expands the path to set the root" do - base = MyCounter.new([1]) - base.destination_root = "here" - expect(base.destination_root).to eq(File.expand_path(File.join(File.dirname(__FILE__), "..", "here"))) - end - - it "does not use the current directory if one is given" do - root = File.expand_path("/") - base = MyCounter.new([1]) - base.destination_root = root - expect(base.destination_root).to eq(root) - end - - it "uses the current directory if none is given" do - base = MyCounter.new([1]) - expect(base.destination_root).to eq(File.expand_path(File.join(File.dirname(__FILE__), ".."))) - end - end - - describe "#relative_to_original_destination_root" do - it "returns the path relative to the absolute root" do - expect(runner.relative_to_original_destination_root(file)).to eq("foo") - end - - it "does not remove dot if required" do - expect(runner.relative_to_original_destination_root(file, false)).to eq("./foo") - end - - it "always use the absolute root" do - runner.inside("foo") do - expect(runner.relative_to_original_destination_root(file)).to eq("foo") - end - end - - it "creates proper relative paths for absolute file location" do - expect(runner.relative_to_original_destination_root("/test/file")).to eq("/test/file") - end - - it "does not fail with files containing regexp characters" do - runner = MyCounter.new([1], {}, :destination_root => File.join(destination_root, "fo[o-b]ar")) - expect(runner.relative_to_original_destination_root("bar")).to eq("bar") - end - - describe "#source_paths_for_search" do - it "add source_root to source_paths_for_search" do - expect(MyCounter.source_paths_for_search).to include(File.expand_path("fixtures", File.dirname(__FILE__))) - end - - it "keeps only current source root in source paths" do - expect(ClearCounter.source_paths_for_search).to include(File.expand_path("fixtures/bundle", File.dirname(__FILE__))) - expect(ClearCounter.source_paths_for_search).not_to include(File.expand_path("fixtures", File.dirname(__FILE__))) - end - - it "customized source paths should be before source roots" do - expect(ClearCounter.source_paths_for_search[0]).to eq(File.expand_path("fixtures/doc", File.dirname(__FILE__))) - expect(ClearCounter.source_paths_for_search[1]).to eq(File.expand_path("fixtures/bundle", File.dirname(__FILE__))) - end - - it "keeps inherited source paths at the end" do - expect(ClearCounter.source_paths_for_search.last).to eq(File.expand_path("fixtures/broken", File.dirname(__FILE__))) - end - end - end - - describe "#find_in_source_paths" do - it "raises an error if source path is empty" do - expect do - A.new.find_in_source_paths("foo") - end.to raise_error(Thor::Error, /Currently you have no source paths/) - end - - it "finds a template inside the source path" do - expect(runner.find_in_source_paths("doc")).to eq(File.expand_path("doc", source_root)) - expect { runner.find_in_source_paths("README") }.to raise_error - - new_path = File.join(source_root, "doc") - runner.instance_variable_set(:@source_paths, nil) - runner.source_paths.unshift(new_path) - expect(runner.find_in_source_paths("README")).to eq(File.expand_path("README", new_path)) - end - end - end - - describe "#inside" do - it "executes the block inside the given folder" do - runner.inside("foo") do - expect(Dir.pwd).to eq(file) - end - end - - it "changes the base root" do - runner.inside("foo") do - expect(runner.destination_root).to eq(file) - end - end - - it "creates the directory if it does not exist" do - runner.inside("foo") do - expect(File.exist?(file)).to be true - end - end - - describe "when pretending" do - it "no directories should be created" do - runner.inside("bar", :pretend => true) {} - expect(File.exist?("bar")).to be false - end - end - - describe "when verbose" do - it "logs status" do - expect(capture(:stdout) do - runner.inside("foo", :verbose => true) {} - end).to match(/inside foo/) - end - - it "uses padding in next status" do - expect(capture(:stdout) do - runner.inside("foo", :verbose => true) do - runner.say_status :cool, :padding - end - end).to match(/cool padding/) - end - - it "removes padding after block" do - expect(capture(:stdout) do - runner.inside("foo", :verbose => true) {} - runner.say_status :no, :padding - end).to match(/no padding/) - end - end - end - - describe "#in_root" do - it "executes the block in the root folder" do - runner.inside("foo") do - runner.in_root { expect(Dir.pwd).to eq(destination_root) } - end - end - - it "changes the base root" do - runner.inside("foo") do - runner.in_root { expect(runner.destination_root).to eq(destination_root) } - end - end - - it "returns to the previous state" do - runner.inside("foo") do - runner.in_root {} - expect(runner.destination_root).to eq(file) - end - end - end - - describe "#apply" do - before do - @template = <<-TEMPLATE - @foo = "FOO" - say_status :cool, :padding - TEMPLATE - allow(@template).to receive(:read).and_return(@template) - - @file = "/" - allow(runner).to receive(:open).and_return(@template) - end - - it "accepts a URL as the path" do - @file = "http://gist.github.com/103208.txt" - expect(runner).to receive(:open).with(@file, "Accept" => "application/x-thor-template").and_return(@template) - action(:apply, @file) - end - - it "accepts a secure URL as the path" do - @file = "https://gist.github.com/103208.txt" - expect(runner).to receive(:open).with(@file, "Accept" => "application/x-thor-template").and_return(@template) - action(:apply, @file) - end - - it "accepts a local file path with spaces" do - @file = File.expand_path("fixtures/path with spaces", File.dirname(__FILE__)) - expect(runner).to receive(:open).with(@file).and_return(@template) - action(:apply, @file) - end - - it "opens a file and executes its content in the instance binding" do - action :apply, @file - expect(runner.instance_variable_get("@foo")).to eq("FOO") - end - - it "applies padding to the content inside the file" do - expect(action(:apply, @file)).to match(/cool padding/) - end - - it "logs its status" do - expect(action(:apply, @file)).to match(/ apply #{@file}\n/) - end - - it "does not log status" do - content = action(:apply, @file, :verbose => false) - expect(content).to match(/cool padding/) - expect(content).not_to match(/apply http/) - end - end - - describe "#run" do - before do - expect(runner).to receive(:system).with("ls") - end - - it "executes the command given" do - action :run, "ls" - end - - it "logs status" do - expect(action(:run, "ls")).to eq(" run ls from \".\"\n") - end - - it "does not log status if required" do - expect(action(:run, "ls", :verbose => false)).to be_empty - end - - it "accepts a color as status" do - expect(runner.shell).to receive(:say_status).with(:run, 'ls from "."', :yellow) - action :run, "ls", :verbose => :yellow - end - end - - describe "#run_ruby_script" do - before do - allow(Thor::Util).to receive(:ruby_command).and_return("/opt/jruby") - expect(runner).to receive(:system).with("/opt/jruby script.rb") - end - - it "executes the ruby script" do - action :run_ruby_script, "script.rb" - end - - it "logs status" do - expect(action(:run_ruby_script, "script.rb")).to eq(" run jruby script.rb from \".\"\n") - end - - it "does not log status if required" do - expect(action(:run_ruby_script, "script.rb", :verbose => false)).to be_empty - end - end - - describe "#thor" do - it "executes the thor command" do - expect(runner).to receive(:system).with("thor list") - action :thor, :list, :verbose => true - end - - it "converts extra arguments to command arguments" do - expect(runner).to receive(:system).with("thor list foo bar") - action :thor, :list, "foo", "bar" - end - - it "converts options hash to switches" do - expect(runner).to receive(:system).with("thor list foo bar --foo") - action :thor, :list, "foo", "bar", :foo => true - - expect(runner).to receive(:system).with("thor list --foo 1 2 3") - action :thor, :list, :foo => [1, 2, 3] - end - - it "logs status" do - expect(runner).to receive(:system).with("thor list") - expect(action(:thor, :list)).to eq(" run thor list from \".\"\n") - end - - it "does not log status if required" do - expect(runner).to receive(:system).with("thor list --foo 1 2 3") - expect(action(:thor, :list, :foo => [1, 2, 3], :verbose => false)).to be_empty - end - - it "captures the output when :capture is given" do - expect(runner).to receive(:`).with("thor foo bar") - action(:thor, "foo", "bar", :capture => true) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/base_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/base_spec.rb deleted file mode 100644 index fb6d6a9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/base_spec.rb +++ /dev/null @@ -1,298 +0,0 @@ -require "helper" -require "thor/base" - -class Amazing - desc "hello", "say hello" - def hello - puts "Hello" - end -end - -describe Thor::Base do - describe "#initialize" do - it "sets arguments array" do - base = MyCounter.new [1, 2] - expect(base.first).to eq(1) - expect(base.second).to eq(2) - end - - it "sets arguments default values" do - base = MyCounter.new [1] - expect(base.second).to eq(2) - end - - it "sets options default values" do - base = MyCounter.new [1, 2] - expect(base.options[:third]).to eq(3) - end - - it "allows options to be given as symbols or strings" do - base = MyCounter.new [1, 2], :third => 4 - expect(base.options[:third]).to eq(4) - - base = MyCounter.new [1, 2], "third" => 4 - expect(base.options[:third]).to eq(4) - end - - it "creates options with indifferent access" do - base = MyCounter.new [1, 2], :third => 3 - expect(base.options["third"]).to eq(3) - end - - it "creates options with magic predicates" do - base = MyCounter.new [1, 2], :third => 3 - expect(base.options.third).to eq(3) - end - end - - describe "#no_commands" do - it "avoids methods being added as commands" do - expect(MyScript.commands.keys).to include("animal") - expect(MyScript.commands.keys).not_to include("this_is_not_a_command") - end - end - - describe "#argument" do - it "sets a value as required and creates an accessor for it" do - expect(MyCounter.start(%w[1 2 --third 3])[0]).to eq(1) - expect(Scripts::MyScript.start(%w[zoo my_special_param --param=normal_param])).to eq("my_special_param") - end - - it "does not set a value in the options hash" do - expect(BrokenCounter.start(%w[1 2 --third 3])[0]).to be nil - end - end - - describe "#arguments" do - it "returns the arguments for the class" do - expect(MyCounter.arguments.size).to be(2) - end - end - - describe ":aliases" do - it "supports string aliases without a dash prefix" do - expect(MyCounter.start(%w[1 2 -z 3])[4]).to eq(3) - end - - it "supports symbol aliases" do - expect(MyCounter.start(%w[1 2 -y 3])[5]).to eq(3) - expect(MyCounter.start(%w[1 2 -r 3])[5]).to eq(3) - end - end - - describe "#class_option" do - it "sets options class wise" do - expect(MyCounter.start(%w[1 2 --third 3])[2]).to eq(3) - end - - it "does not create an accessor for it" do - expect(BrokenCounter.start(%w[1 2 --third 3])[3]).to be false - end - end - - describe "#class_options" do - it "sets default options overwriting superclass definitions" do - options = Scripts::MyScript.class_options - expect(options[:force]).not_to be_required - end - end - - describe "#remove_argument" do - it "removes previously defined arguments from class" do - expect(ClearCounter.arguments).to be_empty - end - - it "undefine accessors if required" do - expect(ClearCounter.new).not_to respond_to(:first) - expect(ClearCounter.new).not_to respond_to(:second) - end - end - - describe "#remove_class_option" do - it "removes previous defined class option" do - expect(ClearCounter.class_options[:third]).to be nil - end - end - - describe "#class_options_help" do - before do - @content = capture(:stdout) { MyCounter.help(Thor::Base.shell.new) } - end - - it "shows option's description" do - expect(@content).to match(/# The third argument/) - end - - it "shows usage with banner content" do - expect(@content).to match(/\[\-\-third=THREE\]/) - end - - it "shows default values below descriptions" do - expect(@content).to match(/# Default: 3/) - end - - it "shows options in different groups" do - expect(@content).to match(/Options\:/) - expect(@content).to match(/Runtime options\:/) - expect(@content).to match(/\-p, \[\-\-pretend\]/) - end - - it "use padding in options that do not have aliases" do - expect(@content).to match(/^ -t, \[--third/) - expect(@content).to match(/^ \[--fourth/) - end - - it "allows extra options to be given" do - hash = {"Foo" => B.class_options.values} - - content = capture(:stdout) { MyCounter.send(:class_options_help, Thor::Base.shell.new, hash) } - expect(content).to match(/Foo options\:/) - expect(content).to match(/--last-name=LAST_NAME/) - end - - it "displays choices for enums" do - content = capture(:stdout) { Enum.help(Thor::Base.shell.new) } - expect(content).to match(/Possible values\: apple, banana/) - end - end - - describe "#namespace" do - it "returns the default class namespace" do - expect(Scripts::MyScript.namespace).to eq("scripts:my_script") - end - - it "sets a namespace to the class" do - expect(Scripts::MyDefaults.namespace).to eq("default") - end - end - - describe "#group" do - it "sets a group" do - expect(MyScript.group).to eq("script") - end - - it "inherits the group from parent" do - expect(MyChildScript.group).to eq("script") - end - - it "defaults to standard if no group is given" do - expect(Amazing.group).to eq("standard") - end - end - - describe "#subclasses" do - it "tracks its subclasses in an Array" do - expect(Thor::Base.subclasses).to include(MyScript) - expect(Thor::Base.subclasses).to include(MyChildScript) - expect(Thor::Base.subclasses).to include(Scripts::MyScript) - end - end - - describe "#subclass_files" do - it "returns tracked subclasses, grouped by the files they come from" do - thorfile = File.join(File.dirname(__FILE__), "fixtures", "script.thor") - expect(Thor::Base.subclass_files[File.expand_path(thorfile)]).to eq([ - MyScript, MyScript::AnotherScript, MyChildScript, Barn, - PackageNameScript, Scripts::MyScript, Scripts::MyDefaults, - Scripts::ChildDefault, Scripts::Arities - ]) - end - - it "tracks a single subclass across multiple files" do - thorfile = File.join(File.dirname(__FILE__), "fixtures", "command.thor") - expect(Thor::Base.subclass_files[File.expand_path(thorfile)]).to include(Amazing) - expect(Thor::Base.subclass_files[File.expand_path(__FILE__)]).to include(Amazing) - end - end - - describe "#commands" do - it "returns a list with all commands defined in this class" do - expect(MyChildScript.new).to respond_to("animal") - expect(MyChildScript.commands.keys).to include("animal") - end - - it "raises an error if a command with reserved word is defined" do - expect do - klass = Class.new(Thor::Group) - klass.class_eval "def shell; end" - end.to raise_error(RuntimeError, /"shell" is a Thor reserved word and cannot be defined as command/) - end - end - - describe "#all_commands" do - it "returns a list with all commands defined in this class plus superclasses" do - expect(MyChildScript.new).to respond_to("foo") - expect(MyChildScript.all_commands.keys).to include("foo") - end - end - - describe "#remove_command" do - it "removes the command from its commands hash" do - expect(MyChildScript.commands.keys).not_to include("bar") - expect(MyChildScript.commands.keys).not_to include("boom") - end - - it "undefines the method if desired" do - expect(MyChildScript.new).not_to respond_to("boom") - end - end - - describe "#from_superclass" do - it "does not send a method to the superclass if the superclass does not respond to it" do - expect(MyCounter.get_from_super).to eq(13) - end - end - - describe "#start" do - it "raises an error instead of rescuing if THOR_DEBUG=1 is given" do - begin - ENV["THOR_DEBUG"] = "1" - - expect do - MyScript.start %w[what --debug] - end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "what" in "my_script" namespace.') - ensure - ENV["THOR_DEBUG"] = nil - end - end - - it "raises an error instead of rescuing if :debug option is given" do - expect do - MyScript.start %w[what], :debug => true - end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "what" in "my_script" namespace.') - end - - it "does not steal args" do - args = %w[foo bar --force true] - MyScript.start(args) - expect(args).to eq(%w[foo bar --force true]) - end - - it "checks unknown options" do - expect(capture(:stderr) do - MyScript.start(%w[foo bar --force true --unknown baz]) - end.strip).to eq("Unknown switches '--unknown'") - end - - it "checks unknown options except specified" do - expect(capture(:stderr) do - expect(MyScript.start(%w[with_optional NAME --omg --invalid])).to eq(["NAME", {}, %w[--omg --invalid]]) - end.strip).to be_empty - end - end - - describe "attr_*" do - it "does not add attr_reader as a command" do - expect(capture(:stderr) { MyScript.start(%w[another_attribute]) }).to match(/Could not find/) - end - - it "does not add attr_writer as a command" do - expect(capture(:stderr) { MyScript.start(%w[another_attribute= foo]) }).to match(/Could not find/) - end - - it "does not add attr_accessor as a command" do - expect(capture(:stderr) { MyScript.start(["some_attribute"]) }).to match(/Could not find/) - expect(capture(:stderr) { MyScript.start(["some_attribute=", "foo"]) }).to match(/Could not find/) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/command_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/command_spec.rb deleted file mode 100644 index b09270d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/command_spec.rb +++ /dev/null @@ -1,79 +0,0 @@ -require "helper" - -describe Thor::Command do - def command(options = {}) - options.each do |key, value| - options[key] = Thor::Option.parse(key, value) - end - - @command ||= Thor::Command.new(:can_has, "I can has cheezburger", "I can has cheezburger\nLots and lots of it", "can_has", options) - end - - describe "#formatted_usage" do - it "includes namespace within usage" do - object = Struct.new(:namespace, :arguments).new("foo", []) - expect(command(:bar => :required).formatted_usage(object)).to eq("foo:can_has --bar=BAR") - end - - it "includes subcommand name within subcommand usage" do - object = Struct.new(:namespace, :arguments).new("main:foo", []) - expect(command(:bar => :required).formatted_usage(object, false, true)).to eq("foo can_has --bar=BAR") - end - - it "removes default from namespace" do - object = Struct.new(:namespace, :arguments).new("default:foo", []) - expect(command(:bar => :required).formatted_usage(object)).to eq(":foo:can_has --bar=BAR") - end - - it "injects arguments into usage" do - options = {:required => true, :type => :string} - object = Struct.new(:namespace, :arguments).new("foo", [Thor::Argument.new(:bar, options)]) - expect(command(:foo => :required).formatted_usage(object)).to eq("foo:can_has BAR --foo=FOO") - end - end - - describe "#dynamic" do - it "creates a dynamic command with the given name" do - expect(Thor::DynamicCommand.new("command").name).to eq("command") - expect(Thor::DynamicCommand.new("command").description).to eq("A dynamically-generated command") - expect(Thor::DynamicCommand.new("command").usage).to eq("command") - expect(Thor::DynamicCommand.new("command").options).to eq({}) - end - - it "does not invoke an existing method" do - dub = double - expect(dub.class).to receive(:handle_no_command_error).with("to_s") - Thor::DynamicCommand.new("to_s").run(dub) - end - end - - describe "#dup" do - it "dup options hash" do - command = Thor::Command.new("can_has", nil, nil, nil, :foo => true, :bar => :required) - command.dup.options.delete(:foo) - expect(command.options[:foo]).to be - end - end - - describe "#run" do - it "runs a command by calling a method in the given instance" do - dub = double - expect(dub).to receive(:can_has).and_return { |*args| args } - expect(command.run(dub, [1, 2, 3])).to eq([1, 2, 3]) - end - - it "raises an error if the method to be invoked is private" do - klass = Class.new do - def self.handle_no_command_error(name) - name - end - def can_has - "fail" - end - private :can_has - end - - expect(command.run(klass.new)).to eq("can_has") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/core_ext/hash_with_indifferent_access_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/core_ext/hash_with_indifferent_access_spec.rb deleted file mode 100644 index ffeb05f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/core_ext/hash_with_indifferent_access_spec.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "helper" -require "thor/core_ext/hash_with_indifferent_access" - -describe Thor::CoreExt::HashWithIndifferentAccess do - before do - @hash = Thor::CoreExt::HashWithIndifferentAccess.new :foo => "bar", "baz" => "bee", :force => true - end - - it "has values accessible by either strings or symbols" do - expect(@hash["foo"]).to eq("bar") - expect(@hash[:foo]).to eq("bar") - - expect(@hash.values_at(:foo, :baz)).to eq(%w[bar bee]) - expect(@hash.delete(:foo)).to eq("bar") - end - - it "handles magic boolean predicates" do - expect(@hash.force?).to be true - expect(@hash.foo?).to be true - expect(@hash.nothing?).to be false - end - - it "handles magic comparisons" do - expect(@hash.foo?("bar")).to be true - expect(@hash.foo?("bee")).to be false - end - - it "maps methods to keys" do - expect(@hash.foo).to eq(@hash["foo"]) - end - - it "merges keys independent if they are symbols or strings" do - @hash.merge!("force" => false, :baz => "boom") - expect(@hash[:force]).to eq(false) - expect(@hash["baz"]).to eq("boom") - end - - it "creates a new hash by merging keys independent if they are symbols or strings" do - other = @hash.merge("force" => false, :baz => "boom") - expect(other[:force]).to eq(false) - expect(other["baz"]).to eq("boom") - end - - it "converts to a traditional hash" do - expect(@hash.to_hash.class).to eq(Hash) - expect(@hash).to eq("foo" => "bar", "baz" => "bee", "force" => true) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/core_ext/ordered_hash_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/core_ext/ordered_hash_spec.rb deleted file mode 100644 index 8cc6143..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/core_ext/ordered_hash_spec.rb +++ /dev/null @@ -1,115 +0,0 @@ -require "helper" -require "thor/core_ext/ordered_hash" - -describe Thor::CoreExt::OrderedHash do - before do - @hash = Thor::CoreExt::OrderedHash.new - end - - describe "without any items" do - it "returns nil for an undefined key" do - expect(@hash["foo"]).to be nil - end - - it "doesn't iterate through any items" do - @hash.each { fail } - end - - it "has an empty key and values list" do - expect(@hash.keys).to be_empty - expect(@hash.values).to be_empty - end - - it "must be empty" do - expect(@hash).to be_empty - end - end - - describe "with several items" do - before do - @hash[:foo] = "Foo!" - @hash[:bar] = "Bar!" - @hash[:baz] = "Baz!" - @hash[:bop] = "Bop!" - @hash[:bat] = "Bat!" - end - - it "returns nil for an undefined key" do - expect(@hash[:boom]).to be nil - end - - it "returns the value for each key" do - expect(@hash[:foo]).to eq("Foo!") - expect(@hash[:bar]).to eq("Bar!") - expect(@hash[:baz]).to eq("Baz!") - expect(@hash[:bop]).to eq("Bop!") - expect(@hash[:bat]).to eq("Bat!") - end - - it "iterates through the keys and values in order of assignment" do - arr = [] - @hash.each do |key, value| - arr << [key, value] - end - expect(arr).to eq([[:foo, "Foo!"], [:bar, "Bar!"], [:baz, "Baz!"], - [:bop, "Bop!"], [:bat, "Bat!"]]) - end - - it "returns the keys in order of insertion" do - expect(@hash.keys).to eq([:foo, :bar, :baz, :bop, :bat]) - end - - it "returns the values in order of insertion" do - expect(@hash.values).to eq(["Foo!", "Bar!", "Baz!", "Bop!", "Bat!"]) - end - - it "does not move an overwritten node to the end of the ordering" do - @hash[:baz] = "Bip!" - expect(@hash.values).to eq(["Foo!", "Bar!", "Bip!", "Bop!", "Bat!"]) - - @hash[:foo] = "Bip!" - expect(@hash.values).to eq(["Bip!", "Bar!", "Bip!", "Bop!", "Bat!"]) - - @hash[:bat] = "Bip!" - expect(@hash.values).to eq(["Bip!", "Bar!", "Bip!", "Bop!", "Bip!"]) - end - - it "appends another ordered hash while preserving ordering" do - other_hash = Thor::CoreExt::OrderedHash.new - other_hash[1] = "one" - other_hash[2] = "two" - other_hash[3] = "three" - expect(@hash.merge(other_hash).values).to eq(["Foo!", "Bar!", "Baz!", "Bop!", "Bat!", "one", "two", "three"]) - end - - it "overwrites hash keys with matching appended keys" do - other_hash = Thor::CoreExt::OrderedHash.new - other_hash[:bar] = "bar" - expect(@hash.merge(other_hash)[:bar]).to eq("bar") - expect(@hash[:bar]).to eq("Bar!") - end - - it "converts to an array" do - expect(@hash.to_a).to eq([[:foo, "Foo!"], [:bar, "Bar!"], [:baz, "Baz!"], [:bop, "Bop!"], [:bat, "Bat!"]]) - end - - it "must not be empty" do - expect(@hash).not_to be_empty - end - - it "deletes values from hash" do - expect(@hash.delete(:baz)).to eq("Baz!") - expect(@hash.values).to eq(["Foo!", "Bar!", "Bop!", "Bat!"]) - - expect(@hash.delete(:foo)).to eq("Foo!") - expect(@hash.values).to eq(["Bar!", "Bop!", "Bat!"]) - - expect(@hash.delete(:bat)).to eq("Bat!") - expect(@hash.values).to eq(["Bar!", "Bop!"]) - end - - it "returns nil if the value to be deleted can't be found" do - expect(@hash.delete(:nothing)).to be nil - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/exit_condition_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/exit_condition_spec.rb deleted file mode 100644 index 807b5af..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/exit_condition_spec.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "helper" -require "thor/base" - -describe "Exit conditions" do - it "exits 0, not bubble up EPIPE, if EPIPE is raised" do - epiped = false - - command = Class.new(Thor) do - desc "my_action", "testing EPIPE" - define_method :my_action do - epiped = true - fail Errno::EPIPE - end - end - - expect { command.start(["my_action"]) }.to raise_error(SystemExit) - expect(epiped).to eq(true) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/application.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/application.rb deleted file mode 100644 index 50d2fae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/application.rb +++ /dev/null @@ -1,2 +0,0 @@ -class Application < Base -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/app{1}/README b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/app{1}/README deleted file mode 100644 index 16374df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/app{1}/README +++ /dev/null @@ -1,3 +0,0 @@ -__start__ -README -__end__ diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/bundle/execute.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/bundle/execute.rb deleted file mode 100644 index 0530d87..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/bundle/execute.rb +++ /dev/null @@ -1,6 +0,0 @@ -class Execute < Thor - desc "ls", "Execute ls" - def ls - system "ls" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/bundle/main.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/bundle/main.thor deleted file mode 100644 index 38bdfbc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/bundle/main.thor +++ /dev/null @@ -1 +0,0 @@ -require File.join(File.dirname(__FILE__), 'execute') diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/command.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/command.thor deleted file mode 100644 index 26a0268..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/command.thor +++ /dev/null @@ -1,10 +0,0 @@ -# module: random - -class Amazing < Thor - desc "describe NAME", "say that someone is amazing" - method_options :forcefully => :boolean - def describe(name, opts) - ret = "#{name} is amazing" - puts opts["forcefully"] ? ret.upcase : ret - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/%file_name%.rb.tt b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/%file_name%.rb.tt deleted file mode 100644 index 4c4c6c0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/%file_name%.rb.tt +++ /dev/null @@ -1 +0,0 @@ -FOO = <%= "FOO" %> diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/COMMENTER b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/COMMENTER deleted file mode 100644 index 384cb3a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/COMMENTER +++ /dev/null @@ -1,11 +0,0 @@ -__start__ - # greenblue -# -# yellowblue -#yellowred - #greenred -orange - purple - ind#igo - # ind#igo -__end__ diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/README b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/README deleted file mode 100644 index 16374df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/README +++ /dev/null @@ -1,3 +0,0 @@ -__start__ -README -__end__ diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/block_helper.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/block_helper.rb deleted file mode 100644 index df59211..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/block_helper.rb +++ /dev/null @@ -1,3 +0,0 @@ -<% world do -%> -Hello -<% end -%> diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/config.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/config.rb deleted file mode 100644 index 6211739..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/config.rb +++ /dev/null @@ -1 +0,0 @@ -class <%= @klass %>; end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/config.yaml.tt b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/config.yaml.tt deleted file mode 100644 index e75615c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/config.yaml.tt +++ /dev/null @@ -1 +0,0 @@ ---- Hi from yaml diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/excluding/%file_name%.rb.tt b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/excluding/%file_name%.rb.tt deleted file mode 100644 index 6296c46..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/doc/excluding/%file_name%.rb.tt +++ /dev/null @@ -1 +0,0 @@ -BAR = <%= "BAR" %> diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/enum.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/enum.thor deleted file mode 100644 index b5a7ded..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/enum.thor +++ /dev/null @@ -1,10 +0,0 @@ -class Enum < Thor::Group - include Thor::Actions - - desc "snack" - class_option "fruit", :aliases => "-f", :type => :string, :enum => %w(apple banana) - def snack - puts options['fruit'] - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/group.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/group.thor deleted file mode 100644 index bc7e102..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/group.thor +++ /dev/null @@ -1,128 +0,0 @@ -class MyCounter < Thor::Group - include Thor::Actions - add_runtime_options! - - def self.get_from_super - from_superclass(:get_from_super, 13) - end - - source_root File.expand_path(File.dirname(__FILE__)) - source_paths << File.expand_path("broken", File.dirname(__FILE__)) - - argument :first, :type => :numeric - argument :second, :type => :numeric, :default => 2 - - class_option :third, :type => :numeric, :desc => "The third argument", :default => 3, - :banner => "THREE", :aliases => "-t" - class_option :fourth, :type => :numeric, :desc => "The fourth argument" - class_option :simple, :type => :numeric, :aliases => 'z' - class_option :symbolic, :type => :numeric, :aliases => [:y, :r] - - desc <<-FOO -Description: - This generator runs three commands: one, two and three. -FOO - - def one - first - end - - def two - second - end - - def three - options[:third] - end - - def four - options[:fourth] - end - - def five - options[:simple] - end - - def six - options[:symbolic] - end - - def self.inherited(base) - super - base.source_paths.unshift(File.expand_path(File.join(File.dirname(__FILE__), "doc"))) - end - - no_commands do - def world(&block) - result = capture(&block) - concat(result.strip + " world!") - end - end -end - -class ClearCounter < MyCounter - remove_argument :first, :second, :undefine => true - remove_class_option :third - - def self.source_root - File.expand_path(File.join(File.dirname(__FILE__), "bundle")) - end -end - -class BrokenCounter < MyCounter - namespace "app:broken:counter" - class_option :fail, :type => :boolean, :default => false - - class << self - undef_method :source_root - end - - def one - options[:first] - end - - def four - respond_to?(:fail) - end - - def five - options[:fail] ? this_method_does_not_exist : 5 - end -end - -class WhinyGenerator < Thor::Group - include Thor::Actions - - def self.source_root - File.expand_path(File.dirname(__FILE__)) - end - - def wrong_arity(required) - end -end - -class CommandConflict < Thor::Group - desc "A group with the same name as a default command" - def group - puts "group" - end -end - -class ParentGroup < Thor::Group -private - def foo - "foo" - end - - def baz(name = 'baz') - name - end -end - -class ChildGroup < ParentGroup - def bar - "bar" - end - - public_command :foo, :baz -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/invoke.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/invoke.thor deleted file mode 100644 index 0e76e98..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/invoke.thor +++ /dev/null @@ -1,131 +0,0 @@ -class A < Thor - include Thor::Actions - - desc "one", "invoke one" - def one - p 1 - invoke :two - invoke :three - end - - desc "two", "invoke two" - def two - p 2 - invoke :three - end - - desc "three", "invoke three" - def three - p 3 - end - - desc "four", "invoke four" - def four - p 4 - invoke "defined:five" - end - - desc "five N", "check if number is equal 5" - def five(number) - number == 5 - end - - desc "invoker", "invoke a b command" - def invoker(*args) - invoke :b, :one, ["Jose"] - end -end - -class B < Thor - class_option :last_name, :type => :string - - desc "one FIRST_NAME", "invoke one" - def one(first_name) - "#{options.last_name}, #{first_name}" - end - - desc "two", "invoke two" - def two - options - end - - desc "three", "invoke three" - def three - self - end - - desc "four", "invoke four" - option :defaulted_value, :type => :string, :default => 'default' - def four - options.defaulted_value - end -end - -class C < Thor::Group - include Thor::Actions - - def one - p 1 - end - - def two - p 2 - end - - def three - p 3 - end -end - -class Defined < Thor::Group - class_option :unused, :type => :boolean, :desc => "This option has no use" - - def one - p 1 - invoke "a:two" - invoke "a:three" - invoke "a:four" - invoke "defined:five" - end - - def five - p 5 - end - - def print_status - say_status :finished, :counting - end -end - -class E < Thor::Group - invoke Defined -end - -class F < Thor::Group - invoke "b:one" do |instance, klass, command| - instance.invoke klass, command, [ "Jose" ], :last_name => "Valim" - end -end - -class G < Thor::Group - class_option :invoked, :type => :string, :default => "defined" - invoke_from_option :invoked -end - -class H < Thor::Group - class_option :defined, :type => :boolean, :default => true - invoke_from_option :defined -end - -class I < Thor - desc "two", "Two" - def two - current_command_chain - end -end - -class J < Thor - desc "i", "I" - subcommand :one, I -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/path with spaces b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/path with spaces deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/preserve/script.sh b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/preserve/script.sh deleted file mode 100755 index c52d3c2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/preserve/script.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -exit 0 diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/script.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/script.thor deleted file mode 100644 index 357b6e5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/script.thor +++ /dev/null @@ -1,220 +0,0 @@ -class MyScript < Thor - check_unknown_options! :except => :with_optional - - attr_accessor :some_attribute - attr_writer :another_attribute - attr_reader :another_attribute - - private - attr_reader :private_attribute - - public - group :script - default_command :example_default_command - - map "-T" => :animal, ["-f", "--foo"] => :foo - - map "animal_prison" => "zoo" - - desc "zoo", "zoo around" - def zoo - true - end - - desc "animal TYPE", "horse around" - - no_commands do - def this_is_not_a_command - end - end - - def animal(type) - [type] - end - - map "hid" => "hidden" - - desc "hidden TYPE", "this is hidden", :hide => true - def hidden(type) - [type] - end - - map "fu" => "zoo" - - desc "foo BAR", < :boolean, :desc => "Force to do some fooing" - def foo(bar) - [bar, options] - end - - desc "example_default_command", "example!" - method_options :with => :string - def example_default_command - options.empty? ? "default command" : options - end - - desc "call_myself_with_wrong_arity", "get the right error" - def call_myself_with_wrong_arity - call_myself_with_wrong_arity(4) - end - - desc "call_unexistent_method", "Call unexistent method inside a command" - def call_unexistent_method - boom! - end - - desc "long_description", "a" * 80 - long_desc <<-D - This is a really really really long description. - Here you go. So very long. - - It even has two paragraphs. - D - def long_description - end - - desc "name-with-dashes", "Ensure normalization of command names" - def name_with_dashes - end - - method_options :all => :boolean - method_option :lazy, :lazy_default => "yes" - method_option :lazy_numeric, :type => :numeric, :lazy_default => 42 - method_option :lazy_array, :type => :array, :lazy_default => %w[eat at joes] - method_option :lazy_hash, :type => :hash, :lazy_default => {'swedish' => 'meatballs'} - desc "with_optional NAME", "invoke with optional name" - def with_optional(name=nil, *args) - [name, options, args] - end - - class AnotherScript < Thor - desc "baz", "do some bazing" - def baz - end - end - - desc "send", "send as a command name" - def send - true - end - - private - - def method_missing(meth, *args) - if meth == :boom! - super - else - [meth, args] - end - end - - desc "what", "what" - def what - end -end - -class MyChildScript < MyScript - remove_command :bar - - method_options :force => :boolean, :param => :numeric - def initialize(*args) - super - end - - desc "zoo", "zoo around" - method_options :param => :required - def zoo - options - end - - desc "animal TYPE", "horse around" - def animal(type) - [type, options] - end - method_option :other, :type => :string, :default => "method default", :for => :animal - desc "animal KIND", "fish around", :for => :animal - - desc "boom", "explodes everything" - def boom - end - - remove_command :boom, :undefine => true -end - -class Barn < Thor - desc "open [ITEM]", "open the barn door" - def open(item = nil) - if item == "shotgun" - puts "That's going to leave a mark." - else - puts "Open sesame!" - end - end - - desc "paint [COLOR]", "paint the barn" - method_option :coats, :type => :numeric, :default => 2, :desc => 'how many coats of paint' - def paint(color='red') - puts "#{options[:coats]} coats of #{color} paint" - end -end - -class PackageNameScript < Thor - package_name "Baboon" -end - -module Scripts - class MyScript < MyChildScript - argument :accessor, :type => :string - class_options :force => :boolean - method_option :new_option, :type => :string, :for => :example_default_command - - def zoo - self.accessor - end - end - - class MyDefaults < Thor - check_unknown_options! - - namespace :default - desc "cow", "prints 'moo'" - def cow - puts "moo" - end - - desc "command_conflict", "only gets called when prepended with a colon" - def command_conflict - puts "command" - end - - desc "barn", "commands to manage the barn" - subcommand "barn", Barn - end - - class ChildDefault < Thor - namespace "default:child" - end - - class Arities < Thor - desc "zero_args", "takes zero args" - def zero_args - end - - desc "one_arg ARG", "takes one arg" - def one_arg(arg) - end - - desc "two_args ARG1 ARG2", "takes two args" - def two_args(arg1, arg2) - end - - desc "optional_arg [ARG]", "takes an optional arg" - def optional_arg(arg='default') - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/subcommand.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/subcommand.thor deleted file mode 100644 index 35d0b57..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/fixtures/subcommand.thor +++ /dev/null @@ -1,17 +0,0 @@ -module TestSubcommands - - class Subcommand < Thor - desc "print_opt", "My method" - def print_opt - print options["opt"] - end - end - - class Parent < Thor - class_option "opt" - - desc "sub", "My subcommand" - subcommand "sub", Subcommand - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/group_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/group_spec.rb deleted file mode 100644 index 823318f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/group_spec.rb +++ /dev/null @@ -1,222 +0,0 @@ -require "helper" - -describe Thor::Group do - describe "command" do - it "allows to use private methods from parent class as commands" do - expect(ChildGroup.start).to eq(%w[bar foo baz]) - expect(ChildGroup.new.baz("bar")).to eq("bar") - end - end - - describe "#start" do - it "invokes all the commands under the Thor group" do - expect(MyCounter.start(%w[1 2 --third 3])).to eq([1, 2, 3, nil, nil, nil]) - end - - it "uses argument's default value" do - expect(MyCounter.start(%w[1 --third 3])).to eq([1, 2, 3, nil, nil, nil]) - end - - it "invokes all the commands in the Thor group and its parents" do - expect(BrokenCounter.start(%w[1 2 --third 3])).to eq([nil, 2, 3, false, 5, nil]) - end - - it "raises an error if a required argument is added after a non-required" do - expect do - MyCounter.argument(:foo, :type => :string) - end.to raise_error(ArgumentError, 'You cannot have "foo" as required argument after the non-required argument "second".') - end - - it "raises when an exception happens within the command call" do - expect { BrokenCounter.start(%w[1 2 --fail]) }.to raise_error - end - - it "raises an error when a Thor group command expects arguments" do - expect { WhinyGenerator.start }.to raise_error(ArgumentError, /thor wrong_arity takes 1 argument, but it should not/) - end - - it "invokes help message if any of the shortcuts are given" do - expect(MyCounter).to receive(:help) - MyCounter.start(%w[-h]) - end - end - - describe "#desc" do - it "sets the description for a given class" do - expect(MyCounter.desc).to eq("Description:\n This generator runs three commands: one, two and three.\n") - end - - it "can be inherited" do - expect(BrokenCounter.desc).to eq("Description:\n This generator runs three commands: one, two and three.\n") - end - - it "can be nil" do - expect(WhinyGenerator.desc).to be nil - end - end - - describe "#help" do - before do - @content = capture(:stdout) { MyCounter.help(Thor::Base.shell.new) } - end - - it "provides usage information" do - expect(@content).to match(/my_counter N \[N\]/) - end - - it "shows description" do - expect(@content).to match(/Description:/) - expect(@content).to match(/This generator runs three commands: one, two and three./) - end - - it "shows options information" do - expect(@content).to match(/Options/) - expect(@content).to match(/\[\-\-third=THREE\]/) - end - end - - describe "#invoke" do - before do - @content = capture(:stdout) { E.start } - end - - it "allows to invoke a class from the class binding" do - expect(@content).to match(/1\n2\n3\n4\n5\n/) - end - - it "shows invocation information to the user" do - expect(@content).to match(/invoke Defined/) - end - - it "uses padding on status generated by the invoked class" do - expect(@content).to match(/finished counting/) - end - - it "allows invocation to be configured with blocks" do - capture(:stdout) do - expect(F.start).to eq(["Valim, Jose"]) - end - end - - it "shows invoked options on help" do - content = capture(:stdout) { E.help(Thor::Base.shell.new) } - expect(content).to match(/Defined options:/) - expect(content).to match(/\[--unused\]/) - expect(content).to match(/# This option has no use/) - end - end - - describe "#invoke_from_option" do - describe "with default type" do - before do - @content = capture(:stdout) { G.start } - end - - it "allows to invoke a class from the class binding by a default option" do - expect(@content).to match(/1\n2\n3\n4\n5\n/) - end - - it "does not invoke if the option is nil" do - expect(capture(:stdout) { G.start(%w[--skip-invoked]) }).not_to match(/invoke/) - end - - it "prints a message if invocation cannot be found" do - content = capture(:stdout) { G.start(%w[--invoked unknown]) } - expect(content).to match(/error unknown \[not found\]/) - end - - it "allows to invoke a class from the class binding by the given option" do - error = nil - content = capture(:stdout) do - error = capture(:stderr) do - G.start(%w[--invoked e]) - end - end - expect(content).to match(/invoke e/) - expect(error).to match(/ERROR: "thor two" was called with arguments/) - end - - it "shows invocation information to the user" do - expect(@content).to match(/invoke defined/) - end - - it "uses padding on status generated by the invoked class" do - expect(@content).to match(/finished counting/) - end - - it "shows invoked options on help" do - content = capture(:stdout) { G.help(Thor::Base.shell.new) } - expect(content).to match(/defined options:/) - expect(content).to match(/\[--unused\]/) - expect(content).to match(/# This option has no use/) - end - end - - describe "with boolean type" do - before do - @content = capture(:stdout) { H.start } - end - - it "allows to invoke a class from the class binding by a default option" do - expect(@content).to match(/1\n2\n3\n4\n5\n/) - end - - it "does not invoke if the option is false" do - expect(capture(:stdout) { H.start(%w[--no-defined]) }).not_to match(/invoke/) - end - - it "shows invocation information to the user" do - expect(@content).to match(/invoke defined/) - end - - it "uses padding on status generated by the invoked class" do - expect(@content).to match(/finished counting/) - end - - it "shows invoked options on help" do - content = capture(:stdout) { H.help(Thor::Base.shell.new) } - expect(content).to match(/defined options:/) - expect(content).to match(/\[--unused\]/) - expect(content).to match(/# This option has no use/) - end - end - end - - describe "edge-cases" do - it "can handle boolean options followed by arguments" do - klass = Class.new(Thor::Group) do - desc "say hi to name" - argument :name, :type => :string - class_option :loud, :type => :boolean - - def hi - name.upcase! if options[:loud] - "Hi #{name}" - end - end - - expect(klass.start(%w[jose])).to eq(["Hi jose"]) - expect(klass.start(%w[jose --loud])).to eq(["Hi JOSE"]) - expect(klass.start(%w[--loud jose])).to eq(["Hi JOSE"]) - end - - it "provides extra args as `args`" do - klass = Class.new(Thor::Group) do - desc "say hi to name" - argument :name, :type => :string - class_option :loud, :type => :boolean - - def hi - name.upcase! if options[:loud] - out = "Hi #{name}" - out << ": " << args.join(", ") unless args.empty? - out - end - end - - expect(klass.start(%w[jose])).to eq(["Hi jose"]) - expect(klass.start(%w[jose --loud])).to eq(["Hi JOSE"]) - expect(klass.start(%w[--loud jose])).to eq(["Hi JOSE"]) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/helper.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/helper.rb deleted file mode 100644 index fbdb4ce..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/helper.rb +++ /dev/null @@ -1,80 +0,0 @@ -$TESTING = true - -require "simplecov" -require "coveralls" - -SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[ - SimpleCov::Formatter::HTMLFormatter, - Coveralls::SimpleCov::Formatter -] - -SimpleCov.start do - add_filter "/spec/" - minimum_coverage(92.21) -end - -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) -require "thor" -require "thor/group" -require "stringio" - -require "rdoc" -require "rspec" -require "diff/lcs" # You need diff/lcs installed to run specs (but not to run Thor). -require "fakeweb" # You need fakeweb installed to run specs (but not to run Thor). - -# Set shell to basic -$0 = "thor" -$thor_runner = true -ARGV.clear -Thor::Base.shell = Thor::Shell::Basic - -# Load fixtures -load File.join(File.dirname(__FILE__), "fixtures", "enum.thor") -load File.join(File.dirname(__FILE__), "fixtures", "group.thor") -load File.join(File.dirname(__FILE__), "fixtures", "invoke.thor") -load File.join(File.dirname(__FILE__), "fixtures", "script.thor") -load File.join(File.dirname(__FILE__), "fixtures", "subcommand.thor") -load File.join(File.dirname(__FILE__), "fixtures", "command.thor") - -RSpec.configure do |config| - config.before do - ARGV.replace [] - end - - config.expect_with :rspec do |c| - c.syntax = :expect - end - - def capture(stream) - begin - stream = stream.to_s - eval "$#{stream} = StringIO.new" - yield - result = eval("$#{stream}").string - ensure - eval("$#{stream} = #{stream.upcase}") - end - - result - end - - def source_root - File.join(File.dirname(__FILE__), "fixtures") - end - - def destination_root - File.join(File.dirname(__FILE__), "sandbox") - end - - # This code was adapted from Ruby on Rails, available under MIT-LICENSE - # Copyright (c) 2004-2013 David Heinemeier Hansson - def silence_warnings - old_verbose, $VERBOSE = $VERBOSE, nil - yield - ensure - $VERBOSE = old_verbose - end - - alias silence capture -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/invocation_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/invocation_spec.rb deleted file mode 100644 index 01160d2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/invocation_spec.rb +++ /dev/null @@ -1,120 +0,0 @@ -require "helper" -require "thor/base" - -describe Thor::Invocation do - describe "#invoke" do - it "invokes a command inside another command" do - expect(capture(:stdout) { A.new.invoke(:two) }).to eq("2\n3\n") - end - - it "invokes a command just once" do - expect(capture(:stdout) { A.new.invoke(:one) }).to eq("1\n2\n3\n") - end - - it "invokes a command just once even if they belongs to different classes" do - expect(capture(:stdout) { Defined.new.invoke(:one) }).to eq("1\n2\n3\n4\n5\n") - end - - it "invokes a command with arguments" do - expect(A.new.invoke(:five, [5])).to be true - expect(A.new.invoke(:five, [7])).to be false - end - - it "invokes the default command if none is given to a Thor class" do - content = capture(:stdout) { A.new.invoke("b") } - expect(content).to match(/Commands/) - expect(content).to match(/LAST_NAME/) - end - - it "accepts a class as argument without a command to invoke" do - content = capture(:stdout) { A.new.invoke(B) } - expect(content).to match(/Commands/) - expect(content).to match(/LAST_NAME/) - end - - it "accepts a class as argument with a command to invoke" do - base = A.new([], :last_name => "Valim") - expect(base.invoke(B, :one, %w[Jose])).to eq("Valim, Jose") - end - - it "allows customized options to be given" do - base = A.new([], :last_name => "Wrong") - expect(base.invoke(B, :one, %w[Jose], :last_name => "Valim")).to eq("Valim, Jose") - end - - it "reparses options in the new class" do - expect(A.start(%w[invoker --last-name Valim])).to eq("Valim, Jose") - end - - it "shares initialize options with invoked class" do - expect(A.new([], :foo => :bar).invoke("b:two")).to eq("foo" => :bar) - end - - it "uses default options from invoked class if no matching arguments are given" do - expect(A.new([]).invoke("b:four")).to eq("default") - end - - it "overrides default options if options are passed to the invoker" do - expect(A.new([], :defaulted_value => "not default").invoke("b:four")).to eq("not default") - end - - it "returns the command chain" do - expect(I.new.invoke("two")).to eq([:two]) - - if RUBY_VERSION < "1.9.3" - result = J.start(["one", "two" ]) - expect(result).to include(:one) - expect(result).to include(:two) - else - expect(J.start(["one", "two" ])).to eq([:one, :two]) - end - end - - it "dump configuration values to be used in the invoked class" do - base = A.new - expect(base.invoke("b:three").shell).to eq(base.shell) - end - - it "allow extra configuration values to be given" do - base, shell = A.new, Thor::Base.shell.new - expect(base.invoke("b:three", [], {}, :shell => shell).shell).to eq(shell) - end - - it "invokes a Thor::Group and all of its commands" do - expect(capture(:stdout) { A.new.invoke(:c) }).to eq("1\n2\n3\n") - end - - it "does not invoke a Thor::Group twice" do - base = A.new - silence(:stdout) { base.invoke(:c) } - expect(capture(:stdout) { base.invoke(:c) }).to be_empty - end - - it "does not invoke any of Thor::Group commands twice" do - base = A.new - silence(:stdout) { base.invoke(:c) } - expect(capture(:stdout) { base.invoke("c:one") }).to be_empty - end - - it "raises Thor::UndefinedCommandError if the command can't be found" do - expect do - A.new.invoke("foo:bar") - end.to raise_error(Thor::UndefinedCommandError) - end - - it "raises Thor::UndefinedCommandError if the command can't be found even if all commands were already executed" do - base = C.new - silence(:stdout) { base.invoke_all } - - expect do - base.invoke("foo:bar") - end.to raise_error(Thor::UndefinedCommandError) - end - - it "raises an error if a non Thor class is given" do - expect do - A.new.invoke(Object) - end.to raise_error(RuntimeError, "Expected Thor class, got Object") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor/basic_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor/basic_spec.rb deleted file mode 100644 index 0aefe8c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor/basic_spec.rb +++ /dev/null @@ -1,28 +0,0 @@ -require "helper" - -describe Thor::LineEditor::Basic do - describe ".available?" do - it "returns true" do - expect(Thor::LineEditor::Basic).to be_available - end - end - - describe "#readline" do - it "uses $stdin and $stdout to get input from the user" do - expect($stdout).to receive(:print).with("Enter your name ") - expect($stdin).to receive(:gets).and_return("George") - expect($stdin).not_to receive(:noecho) - editor = Thor::LineEditor::Basic.new("Enter your name ", {}) - expect(editor.readline).to eq("George") - end - - it "disables echo when asked to" do - expect($stdout).to receive(:print).with("Password: ") - noecho_stdin = double("noecho_stdin") - expect(noecho_stdin).to receive(:gets).and_return("secret") - expect($stdin).to receive(:noecho).and_yield(noecho_stdin) - editor = Thor::LineEditor::Basic.new("Password: ", :echo => false) - expect(editor.readline).to eq("secret") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor/readline_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor/readline_spec.rb deleted file mode 100644 index dda489c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor/readline_spec.rb +++ /dev/null @@ -1,69 +0,0 @@ -require "helper" - -describe Thor::LineEditor::Readline do - before do - unless defined? ::Readline - ::Readline = double("Readline") - allow(::Readline).to receive(:completion_append_character=).with(nil) - end - end - - describe ".available?" do - it "returns true when ::Readline exists" do - allow(Object).to receive(:const_defined?).with(:Readline).and_return(true) - expect(described_class).to be_available - end - - it "returns false when ::Readline does not exist" do - allow(Object).to receive(:const_defined?).with(:Readline).and_return(false) - expect(described_class).not_to be_available - end - end - - describe "#readline" do - it "invokes the readline library" do - expect(::Readline).to receive(:readline).with("> ", true).and_return("foo") - expect(::Readline).not_to receive(:completion_proc=) - editor = Thor::LineEditor::Readline.new("> ", {}) - expect(editor.readline).to eq("foo") - end - - it "supports the add_to_history option" do - expect(::Readline).to receive(:readline).with("> ", false).and_return("foo") - expect(::Readline).not_to receive(:completion_proc=) - editor = Thor::LineEditor::Readline.new("> ", :add_to_history => false) - expect(editor.readline).to eq("foo") - end - - it "provides tab completion when given a limited_to option" do - expect(::Readline).to receive(:readline) - expect(::Readline).to receive(:completion_proc=) do |proc| - expect(proc.call("")).to eq %w[Apples Chicken Chocolate] - expect(proc.call("Ch")).to eq %w[Chicken Chocolate] - expect(proc.call("Chi")).to eq ["Chicken"] - end - - editor = Thor::LineEditor::Readline.new("Best food: ", :limited_to => %w[Apples Chicken Chocolate]) - editor.readline - end - - it "provides path tab completion when given the path option" do - expect(::Readline).to receive(:readline) - expect(::Readline).to receive(:completion_proc=) do |proc| - expect(proc.call("../line_ed").sort).to eq ["../line_editor/", "../line_editor_spec.rb"].sort - end - - editor = Thor::LineEditor::Readline.new("Path to file: ", :path => true) - Dir.chdir(File.dirname(__FILE__)) { editor.readline } - end - - it "uses STDIN when asked not to echo input" do - expect($stdout).to receive(:print).with("Password: ") - noecho_stdin = double("noecho_stdin") - expect(noecho_stdin).to receive(:gets).and_return("secret") - expect($stdin).to receive(:noecho).and_yield(noecho_stdin) - editor = Thor::LineEditor::Readline.new("Password: ", :echo => false) - expect(editor.readline).to eq("secret") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor_spec.rb deleted file mode 100644 index 575fd33..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/line_editor_spec.rb +++ /dev/null @@ -1,43 +0,0 @@ -require "helper" - -describe Thor::LineEditor, "on a system with Readline support" do - before do - @original_readline = ::Readline if defined? ::Readline - silence_warnings { ::Readline = double("Readline") } - end - - after do - silence_warnings { ::Readline = @original_readline } - end - - describe ".readline" do - it "uses the Readline line editor" do - editor = double("Readline") - expect(Thor::LineEditor::Readline).to receive(:new).with("Enter your name ", :default => "Brian").and_return(editor) - expect(editor).to receive(:readline).and_return("George") - expect(Thor::LineEditor.readline("Enter your name ", :default => "Brian")).to eq("George") - end - end -end - -describe Thor::LineEditor, "on a system without Readline support" do - before do - if defined? ::Readline - @original_readline = ::Readline - Object.send(:remove_const, :Readline) - end - end - - after do - silence_warnings { ::Readline = @original_readline } - end - - describe ".readline" do - it "uses the Basic line editor" do - editor = double("Basic") - expect(Thor::LineEditor::Basic).to receive(:new).with("Enter your name ", :default => "Brian").and_return(editor) - expect(editor).to receive(:readline).and_return("George") - expect(Thor::LineEditor.readline("Enter your name ", :default => "Brian")).to eq("George") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/argument_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/argument_spec.rb deleted file mode 100644 index 0b1c1cc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/argument_spec.rb +++ /dev/null @@ -1,53 +0,0 @@ -require "helper" -require "thor/parser" - -describe Thor::Argument do - - def argument(name, options = {}) - @argument ||= Thor::Argument.new(name, options) - end - - describe "errors" do - it "raises an error if name is not supplied" do - expect do - argument(nil) - end.to raise_error(ArgumentError, "Argument name can't be nil.") - end - - it "raises an error if type is unknown" do - expect do - argument(:command, :type => :unknown) - end.to raise_error(ArgumentError, "Type :unknown is not valid for arguments.") - end - - it "raises an error if argument is required and has default values" do - expect do - argument(:command, :type => :string, :default => "bar", :required => true) - end.to raise_error(ArgumentError, "An argument cannot be required and have default value.") - end - - it "raises an error if enum isn't an array" do - expect do - argument(:command, :type => :string, :enum => "bar") - end.to raise_error(ArgumentError, "An argument cannot have an enum other than an array.") - end - end - - describe "#usage" do - it "returns usage for string types" do - expect(argument(:foo, :type => :string).usage).to eq("FOO") - end - - it "returns usage for numeric types" do - expect(argument(:foo, :type => :numeric).usage).to eq("N") - end - - it "returns usage for array types" do - expect(argument(:foo, :type => :array).usage).to eq("one two three") - end - - it "returns usage for hash types" do - expect(argument(:foo, :type => :hash).usage).to eq("key:value") - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/arguments_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/arguments_spec.rb deleted file mode 100644 index bb77378..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/arguments_spec.rb +++ /dev/null @@ -1,66 +0,0 @@ -require "helper" -require "thor/parser" - -describe Thor::Arguments do - def create(opts = {}) - arguments = opts.map do |type, default| - options = {:required => default.nil?, :type => type, :default => default} - Thor::Argument.new(type.to_s, options) - end - - arguments.sort! { |a, b| b.name <=> a.name } - @opt = Thor::Arguments.new(arguments) - end - - def parse(*args) - @opt.parse(args) - end - - describe "#parse" do - it "parses arguments in the given order" do - create :string => nil, :numeric => nil - expect(parse("name", "13")["string"]).to eq("name") - expect(parse("name", "13")["numeric"]).to eq(13) - end - - it "accepts hashes" do - create :string => nil, :hash => nil - expect(parse("product", "title:string", "age:integer")["string"]).to eq("product") - expect(parse("product", "title:string", "age:integer")["hash"]).to eq("title" => "string", "age" => "integer") - expect(parse("product", "url:http://www.amazon.com/gp/product/123")["hash"]).to eq("url" => "http://www.amazon.com/gp/product/123") - end - - it "accepts arrays" do - create :string => nil, :array => nil - expect(parse("product", "title", "age")["string"]).to eq("product") - expect(parse("product", "title", "age")["array"]).to eq(%w[title age]) - end - - describe "with no inputs" do - it "and no arguments returns an empty hash" do - create - expect(parse).to eq({}) - end - - it "and required arguments raises an error" do - create :string => nil, :numeric => nil - expect { parse }.to raise_error(Thor::RequiredArgumentMissingError, "No value provided for required arguments 'string', 'numeric'") - end - - it "and default arguments returns default values" do - create :string => "name", :numeric => 13 - expect(parse).to eq("string" => "name", "numeric" => 13) - end - end - - it "returns the input if it's already parsed" do - create :string => nil, :hash => nil, :array => nil, :numeric => nil - expect(parse("", 0, {}, [])).to eq("string" => "", "numeric" => 0, "hash" => {}, "array" => []) - end - - it "returns the default value if none is provided" do - create :string => "foo", :numeric => 3.0 - expect(parse("bar")).to eq("string" => "bar", "numeric" => 3.0) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/option_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/option_spec.rb deleted file mode 100644 index 29f5dc5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/option_spec.rb +++ /dev/null @@ -1,210 +0,0 @@ -require "helper" -require "thor/parser" - -describe Thor::Option do - def parse(key, value) - Thor::Option.parse(key, value) - end - - def option(name, options = {}) - @option ||= Thor::Option.new(name, options) - end - - describe "#parse" do - - describe "with value as a symbol" do - describe "and symbol is a valid type" do - it "has type equals to the symbol" do - expect(parse(:foo, :string).type).to eq(:string) - expect(parse(:foo, :numeric).type).to eq(:numeric) - end - - it "has no default value" do - expect(parse(:foo, :string).default).to be nil - expect(parse(:foo, :numeric).default).to be nil - end - end - - describe "equals to :required" do - it "has type equals to :string" do - expect(parse(:foo, :required).type).to eq(:string) - end - - it "has no default value" do - expect(parse(:foo, :required).default).to be nil - end - end - - describe "and symbol is not a reserved key" do - it "has type equal to :string" do - expect(parse(:foo, :bar).type).to eq(:string) - end - - it "has no default value" do - expect(parse(:foo, :bar).default).to be nil - end - end - end - - describe "with value as hash" do - it "has default type :hash" do - expect(parse(:foo, :a => :b).type).to eq(:hash) - end - - it "has default value equal to the hash" do - expect(parse(:foo, :a => :b).default).to eq(:a => :b) - end - end - - describe "with value as array" do - it "has default type :array" do - expect(parse(:foo, [:a, :b]).type).to eq(:array) - end - - it "has default value equal to the array" do - expect(parse(:foo, [:a, :b]).default).to eq([:a, :b]) - end - end - - describe "with value as string" do - it "has default type :string" do - expect(parse(:foo, "bar").type).to eq(:string) - end - - it "has default value equal to the string" do - expect(parse(:foo, "bar").default).to eq("bar") - end - end - - describe "with value as numeric" do - it "has default type :numeric" do - expect(parse(:foo, 2.0).type).to eq(:numeric) - end - - it "has default value equal to the numeric" do - expect(parse(:foo, 2.0).default).to eq(2.0) - end - end - - describe "with value as boolean" do - it "has default type :boolean" do - expect(parse(:foo, true).type).to eq(:boolean) - expect(parse(:foo, false).type).to eq(:boolean) - end - - it "has default value equal to the boolean" do - expect(parse(:foo, true).default).to eq(true) - expect(parse(:foo, false).default).to eq(false) - end - end - - describe "with key as a symbol" do - it "sets the name equal to the key" do - expect(parse(:foo, true).name).to eq("foo") - end - end - - describe "with key as an array" do - it "sets the first items in the array to the name" do - expect(parse([:foo, :bar, :baz], true).name).to eq("foo") - end - - it "sets all other items as aliases" do - expect(parse([:foo, :bar, :baz], true).aliases).to eq([:bar, :baz]) - end - end - end - - it "returns the switch name" do - expect(option("foo").switch_name).to eq("--foo") - expect(option("--foo").switch_name).to eq("--foo") - end - - it "returns the human name" do - expect(option("foo").human_name).to eq("foo") - expect(option("--foo").human_name).to eq("foo") - end - - it "converts underscores to dashes" do - expect(option("foo_bar").switch_name).to eq("--foo-bar") - end - - it "can be required and have default values" do - option = option("foo", :required => true, :type => :string, :default => "bar") - expect(option.default).to eq("bar") - expect(option).to be_required - end - - it "boolean options cannot be required" do - expect do - option("foo", :required => true, :type => :boolean) - end.to raise_error(ArgumentError, "An option cannot be boolean and required.") - end - - it "allows type predicates" do - expect(parse(:foo, :string)).to be_string - expect(parse(:foo, :boolean)).to be_boolean - expect(parse(:foo, :numeric)).to be_numeric - end - - it "raises an error on method missing" do - expect do - parse(:foo, :string).unknown? - end.to raise_error(NoMethodError) - end - - describe "#usage" do - - it "returns usage for string types" do - expect(parse(:foo, :string).usage).to eq("[--foo=FOO]") - end - - it "returns usage for numeric types" do - expect(parse(:foo, :numeric).usage).to eq("[--foo=N]") - end - - it "returns usage for array types" do - expect(parse(:foo, :array).usage).to eq("[--foo=one two three]") - end - - it "returns usage for hash types" do - expect(parse(:foo, :hash).usage).to eq("[--foo=key:value]") - end - - it "returns usage for boolean types" do - expect(parse(:foo, :boolean).usage).to eq("[--foo], [--no-foo]") - end - - it "does not use padding when no aliases are given" do - expect(parse(:foo, :boolean).usage).to eq("[--foo], [--no-foo]") - end - - it "documents a negative option when boolean" do - expect(parse(:foo, :boolean).usage).to include("[--no-foo]") - end - - it "uses banner when supplied" do - expect(option(:foo, :required => false, :type => :string, :banner => "BAR").usage).to eq("[--foo=BAR]") - end - - it "checks when banner is an empty string" do - expect(option(:foo, :required => false, :type => :string, :banner => "").usage).to eq("[--foo]") - end - - describe "with required values" do - it "does not show the usage between brackets" do - expect(parse(:foo, :required).usage).to eq("--foo=FOO") - end - end - - describe "with aliases" do - it "does not show the usage between brackets" do - expect(parse([:foo, "-f", "-b"], :required).usage).to eq("-f, -b, --foo=FOO") - end - - it "does not negate the aliases" do - expect(parse([:foo, "-f", "-b"], :boolean).usage).to eq("-f, -b, [--foo], [--no-foo]") - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/options_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/options_spec.rb deleted file mode 100644 index 61a86de..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/parser/options_spec.rb +++ /dev/null @@ -1,414 +0,0 @@ -require "helper" -require "thor/parser" - -describe Thor::Options do - def create(opts, defaults = {}, stop_on_unknown = false) - opts.each do |key, value| - opts[key] = Thor::Option.parse(key, value) unless value.is_a?(Thor::Option) - end - - @opt = Thor::Options.new(opts, defaults, stop_on_unknown) - end - - def parse(*args) - @opt.parse(args.flatten) - end - - def check_unknown! - @opt.check_unknown! - end - - def remaining - @opt.remaining - end - - describe "#to_switches" do - it "turns true values into a flag" do - expect(Thor::Options.to_switches(:color => true)).to eq("--color") - end - - it "ignores nil" do - expect(Thor::Options.to_switches(:color => nil)).to eq("") - end - - it "ignores false" do - expect(Thor::Options.to_switches(:color => false)).to eq("") - end - - it "writes --name value for anything else" do - expect(Thor::Options.to_switches(:format => "specdoc")).to eq('--format "specdoc"') - end - - it "joins several values" do - switches = Thor::Options.to_switches(:color => true, :foo => "bar").split(" ").sort - expect(switches).to eq(%w["bar" --color --foo]) - end - - it "accepts arrays" do - expect(Thor::Options.to_switches(:count => [1, 2, 3])).to eq("--count 1 2 3") - end - - it "accepts hashes" do - expect(Thor::Options.to_switches(:count => {:a => :b})).to eq("--count a:b") - end - - it "accepts underscored options" do - expect(Thor::Options.to_switches(:under_score_option => "foo bar")).to eq('--under_score_option "foo bar"') - end - - end - - describe "#parse" do - it "allows multiple aliases for a given switch" do - create %w[--foo --bar --baz] => :string - expect(parse("--foo", "12")["foo"]).to eq("12") - expect(parse("--bar", "12")["foo"]).to eq("12") - expect(parse("--baz", "12")["foo"]).to eq("12") - end - - it "allows custom short names" do - create "-f" => :string - expect(parse("-f", "12")).to eq("f" => "12") - end - - it "allows custom short-name aliases" do - create %w[--bar -f] => :string - expect(parse("-f", "12")).to eq("bar" => "12") - end - - it "accepts conjoined short switches" do - create %w[--foo -f] => true, %w[--bar -b] => true, %w[--app -a] => true - opts = parse("-fba") - expect(opts["foo"]).to be true - expect(opts["bar"]).to be true - expect(opts["app"]).to be true - end - - it "accepts conjoined short switches with input" do - create %w[--foo -f] => true, %w[--bar -b] => true, %w[--app -a] => :required - opts = parse "-fba", "12" - expect(opts["foo"]).to be true - expect(opts["bar"]).to be true - expect(opts["app"]).to eq("12") - end - - it "returns the default value if none is provided" do - create :foo => "baz", :bar => :required - expect(parse("--bar", "boom")["foo"]).to eq("baz") - end - - it "returns the default value from defaults hash to required arguments" do - create Hash[:bar => :required], Hash[:bar => "baz"] - expect(parse["bar"]).to eq("baz") - end - - it "gives higher priority to defaults given in the hash" do - create Hash[:bar => true], Hash[:bar => false] - expect(parse["bar"]).to eq(false) - end - - it "raises an error for unknown switches" do - create :foo => "baz", :bar => :required - parse("--bar", "baz", "--baz", "unknown") - expect { check_unknown! }.to raise_error(Thor::UnknownArgumentError, "Unknown switches '--baz'") - end - - it "skips leading non-switches" do - create(:foo => "baz") - - expect(parse("asdf", "--foo", "bar")).to eq("foo" => "bar") - end - - it "correctly recognizes things that look kind of like options, but aren't, as not options" do - create(:foo => "baz") - expect(parse("--asdf---asdf", "baz", "--foo", "--asdf---dsf--asdf")).to eq("foo" => "--asdf---dsf--asdf") - check_unknown! - end - - it "accepts underscores in commandline args hash for boolean" do - create :foo_bar => :boolean - expect(parse("--foo_bar")["foo_bar"]).to eq(true) - expect(parse("--no_foo_bar")["foo_bar"]).to eq(false) - end - - it "accepts underscores in commandline args hash for strings" do - create :foo_bar => :string, :baz_foo => :string - expect(parse("--foo_bar", "baz")["foo_bar"]).to eq("baz") - expect(parse("--baz_foo", "foo bar")["baz_foo"]).to eq("foo bar") - end - - it "interprets everything after -- as args instead of options" do - create(:foo => :string, :bar => :required) - expect(parse(%w[--bar abc moo -- --foo def -a])).to eq("bar" => "abc") - expect(remaining).to eq(%w[moo --foo def -a]) - end - - it "ignores -- when looking for single option values" do - create(:foo => :string, :bar => :required) - expect(parse(%w[--bar -- --foo def -a])).to eq("bar" => "--foo") - expect(remaining).to eq(%w[def -a]) - end - - it "ignores -- when looking for array option values" do - create(:foo => :array) - expect(parse(%w[--foo a b -- c d -e])).to eq("foo" => %w[a b c d -e]) - expect(remaining).to eq([]) - end - - it "ignores -- when looking for hash option values" do - create(:foo => :hash) - expect(parse(%w[--foo a:b -- c:d -e])).to eq("foo" => {"a" => "b", "c" => "d"}) - expect(remaining).to eq(%w[-e]) - end - - it "ignores trailing --" do - create(:foo => :string) - expect(parse(%w[--foo --])).to eq("foo" => nil) - expect(remaining).to eq([]) - end - - describe "with no input" do - it "and no switches returns an empty hash" do - create({}) - expect(parse).to eq({}) - end - - it "and several switches returns an empty hash" do - create "--foo" => :boolean, "--bar" => :string - expect(parse).to eq({}) - end - - it "and a required switch raises an error" do - create "--foo" => :required - expect { parse }.to raise_error(Thor::RequiredArgumentMissingError, "No value provided for required options '--foo'") - end - end - - describe "with one required and one optional switch" do - before do - create "--foo" => :required, "--bar" => :boolean - end - - it "raises an error if the required switch has no argument" do - expect { parse("--foo") }.to raise_error(Thor::MalformattedArgumentError) - end - - it "raises an error if the required switch isn't given" do - expect { parse("--bar") }.to raise_error(Thor::RequiredArgumentMissingError) - end - - it "raises an error if the required switch is set to nil" do - expect { parse("--no-foo") }.to raise_error(Thor::RequiredArgumentMissingError) - end - - it "does not raises an error if the required option has a default value" do - options = {:required => true, :type => :string, :default => "baz"} - create :foo => Thor::Option.new("foo", options), :bar => :boolean - expect { parse("--bar") }.not_to raise_error - end - end - - context "when stop_on_unknown is true" do - before do - create({:foo => :string, :verbose => :boolean}, {}, true) - end - - it "stops parsing on first non-option" do - expect(parse(%w[foo --verbose])).to eq({}) - expect(remaining).to eq(%w[foo --verbose]) - end - - it "stops parsing on unknown option" do - expect(parse(%w[--bar --verbose])).to eq({}) - expect(remaining).to eq(%w[--bar --verbose]) - end - - it "retains -- after it has stopped parsing" do - expect(parse(%w[--bar -- whatever])).to eq({}) - expect(remaining).to eq(%w[--bar -- whatever]) - end - - it "still accepts options that are given before non-options" do - expect(parse(%w[--verbose foo])).to eq("verbose" => true) - expect(remaining).to eq(%w[foo]) - end - - it "still accepts options that require a value" do - expect(parse(%w[--foo bar baz])).to eq("foo" => "bar") - expect(remaining).to eq(%w[baz]) - end - - it "still interprets everything after -- as args instead of options" do - expect(parse(%w[-- --verbose])).to eq({}) - expect(remaining).to eq(%w[--verbose]) - end - end - - describe "with :string type" do - before do - create %w[--foo -f] => :required - end - - it "accepts a switch assignment" do - expect(parse("--foo", "12")["foo"]).to eq("12") - end - - it "accepts a switch= assignment" do - expect(parse("-f=12")["foo"]).to eq("12") - expect(parse("--foo=12")["foo"]).to eq("12") - expect(parse("--foo=bar=baz")["foo"]).to eq("bar=baz") - end - - it "must accept underscores switch=value assignment" do - create :foo_bar => :required - expect(parse("--foo_bar=http://example.com/under_score/")["foo_bar"]).to eq("http://example.com/under_score/") - end - - it "accepts a --no-switch format" do - create "--foo" => "bar" - expect(parse("--no-foo")["foo"]).to be nil - end - - it "does not consume an argument for --no-switch format" do - create "--cheese" => :string - expect(parse("burger", "--no-cheese", "fries")["cheese"]).to be nil - end - - it "accepts a --switch format on non required types" do - create "--foo" => :string - expect(parse("--foo")["foo"]).to eq("foo") - end - - it "accepts a --switch format on non required types with default values" do - create "--baz" => :string, "--foo" => "bar" - expect(parse("--baz", "bang", "--foo")["foo"]).to eq("bar") - end - - it "overwrites earlier values with later values" do - expect(parse("--foo=bar", "--foo", "12")["foo"]).to eq("12") - expect(parse("--foo", "12", "--foo", "13")["foo"]).to eq("13") - end - - it "raises error when value isn't in enum" do - enum = %w[apple banana] - create :fruit => Thor::Option.new("fruit", :type => :string, :enum => enum) - expect { parse("--fruit", "orange") }.to raise_error(Thor::MalformattedArgumentError, - "Expected '--fruit' to be one of #{enum.join(', ')}; got orange") - end - end - - describe "with :boolean type" do - before do - create "--foo" => false - end - - it "accepts --opt assignment" do - expect(parse("--foo")["foo"]).to eq(true) - expect(parse("--foo", "--bar")["foo"]).to eq(true) - end - - it "uses the default value if no switch is given" do - expect(parse("")["foo"]).to eq(false) - end - - it "accepts --opt=value assignment" do - expect(parse("--foo=true")["foo"]).to eq(true) - expect(parse("--foo=false")["foo"]).to eq(false) - end - - it "accepts --[no-]opt variant, setting false for value" do - expect(parse("--no-foo")["foo"]).to eq(false) - end - - it "accepts --[skip-]opt variant, setting false for value" do - expect(parse("--skip-foo")["foo"]).to eq(false) - end - - it "will prefer 'no-opt' variant over inverting 'opt' if explicitly set" do - create "--no-foo" => true - expect(parse("--no-foo")["no-foo"]).to eq(true) - end - - it "will prefer 'skip-opt' variant over inverting 'opt' if explicitly set" do - create "--skip-foo" => true - expect(parse("--skip-foo")["skip-foo"]).to eq(true) - end - - it "accepts inputs in the human name format" do - create :foo_bar => :boolean - expect(parse("--foo-bar")["foo_bar"]).to eq(true) - expect(parse("--no-foo-bar")["foo_bar"]).to eq(false) - expect(parse("--skip-foo-bar")["foo_bar"]).to eq(false) - end - - it "doesn't eat the next part of the param" do - create :foo => :boolean - expect(parse("--foo", "bar")).to eq("foo" => true) - expect(@opt.remaining).to eq(%w[bar]) - end - end - - describe "with :hash type" do - before do - create "--attributes" => :hash - end - - it "accepts a switch= assignment" do - expect(parse("--attributes=name:string", "age:integer")["attributes"]).to eq("name" => "string", "age" => "integer") - end - - it "accepts a switch assignment" do - expect(parse("--attributes", "name:string", "age:integer")["attributes"]).to eq("name" => "string", "age" => "integer") - end - - it "must not mix values with other switches" do - expect(parse("--attributes", "name:string", "age:integer", "--baz", "cool")["attributes"]).to eq("name" => "string", "age" => "integer") - end - end - - describe "with :array type" do - before do - create "--attributes" => :array - end - - it "accepts a switch= assignment" do - expect(parse("--attributes=a", "b", "c")["attributes"]).to eq(%w[a b c]) - end - - it "accepts a switch assignment" do - expect(parse("--attributes", "a", "b", "c")["attributes"]).to eq(%w[a b c]) - end - - it "must not mix values with other switches" do - expect(parse("--attributes", "a", "b", "c", "--baz", "cool")["attributes"]).to eq(%w[a b c]) - end - end - - describe "with :numeric type" do - before do - create "n" => :numeric, "m" => 5 - end - - it "accepts a -nXY assignment" do - expect(parse("-n12")["n"]).to eq(12) - end - - it "converts values to numeric types" do - expect(parse("-n", "3", "-m", ".5")).to eq("n" => 3, "m" => 0.5) - end - - it "raises error when value isn't numeric" do - expect { parse("-n", "foo") }.to raise_error(Thor::MalformattedArgumentError, - "Expected numeric value for '-n'; got \"foo\"") - end - - it "raises error when value isn't in enum" do - enum = [1, 2] - create :limit => Thor::Option.new("limit", :type => :numeric, :enum => enum) - expect { parse("--limit", "3") }.to raise_error(Thor::MalformattedArgumentError, - "Expected '--limit' to be one of #{enum.join(', ')}; got 3") - end - end - - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/quality_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/quality_spec.rb deleted file mode 100644 index 94f5100..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/quality_spec.rb +++ /dev/null @@ -1,75 +0,0 @@ -if defined?(Encoding) && Encoding.default_external != "UTF-8" - Encoding.default_external = "UTF-8" -end - -describe "The library itself" do - def check_for_spec_defs_with_single_quotes(filename) - failing_lines = [] - - File.readlines(filename).each_with_index do |line,number| - failing_lines << number + 1 if line =~ /^ *(describe|it|context) {1}'{1}/ - end - - unless failing_lines.empty? - "#{filename} uses inconsistent single quotes on lines #{failing_lines.join(', ')}" - end - end - - def check_for_tab_characters(filename) - failing_lines = [] - File.readlines(filename).each_with_index do |line,number| - failing_lines << number + 1 if line =~ /\t/ - end - - unless failing_lines.empty? - "#{filename} has tab characters on lines #{failing_lines.join(', ')}" - end - end - - def check_for_extra_spaces(filename) - failing_lines = [] - File.readlines(filename).each_with_index do |line,number| - next if line =~ /^\s+#.*\s+\n$/ - failing_lines << number + 1 if line =~ /\s+\n$/ - end - - unless failing_lines.empty? - "#{filename} has spaces on the EOL on lines #{failing_lines.join(', ')}" - end - end - - RSpec::Matchers.define :be_well_formed do - failure_message_for_should do |actual| - actual.join("\n") - end - - match do |actual| - actual.empty? - end - end - - it "has no malformed whitespace" do - exempt = /\.gitmodules|\.marshal|fixtures|vendor|spec|ssl_certs|LICENSE/ - error_messages = [] - Dir.chdir(File.expand_path("../..", __FILE__)) do - `git ls-files`.split("\n").each do |filename| - next if filename =~ exempt - error_messages << check_for_tab_characters(filename) - error_messages << check_for_extra_spaces(filename) - end - end - expect(error_messages.compact).to be_well_formed - end - - it "uses double-quotes consistently in specs" do - included = /spec/ - error_messages = [] - Dir.chdir(File.expand_path("../", __FILE__)) do - `git ls-files`.split("\n").each do |filename| - next unless filename =~ included - error_messages << check_for_spec_defs_with_single_quotes(filename) - end - end - expect(error_messages.compact).to be_well_formed - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/rake_compat_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/rake_compat_spec.rb deleted file mode 100644 index fac5c9c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/rake_compat_spec.rb +++ /dev/null @@ -1,72 +0,0 @@ -require "helper" -require "thor/rake_compat" -require "rake/tasklib" - -$main = self - -class RakeTask < Rake::TaskLib - def initialize - define - end - - def define - $main.instance_eval do - desc "Say it's cool" - task :cool do - puts "COOL" - end - - namespace :hiper_mega do - task :super do - puts "HIPER MEGA SUPER" - end - end - end - end -end - -class ThorTask < Thor - include Thor::RakeCompat - RakeTask.new -end - -describe Thor::RakeCompat do - it "sets the rakefile application" do - expect(%w[rake_compat_spec.rb Thorfile]).to include(Rake.application.rakefile) - end - - it "adds rake tasks to thor classes too" do - task = ThorTask.tasks["cool"] - expect(task).to be - end - - it "uses rake tasks descriptions on thor" do - expect(ThorTask.tasks["cool"].description).to eq("Say it's cool") - end - - it "gets usage from rake tasks name" do - expect(ThorTask.tasks["cool"].usage).to eq("cool") - end - - it "uses non namespaced name as description if non is available" do - expect(ThorTask::HiperMega.tasks["super"].description).to eq("super") - end - - it "converts namespaces to classes" do - expect(ThorTask.const_get(:HiperMega)).to eq(ThorTask::HiperMega) - end - - it "does not add tasks from higher namespaces in lowers namespaces" do - expect(ThorTask.tasks["super"]).not_to be - end - - it "invoking the thor task invokes the rake task" do - expect(capture(:stdout) do - ThorTask.start %w[cool] - end).to eq("COOL\n") - - expect(capture(:stdout) do - ThorTask::HiperMega.start %w[super] - end).to eq("HIPER MEGA SUPER\n") - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/register_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/register_spec.rb deleted file mode 100644 index 2a08bae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/register_spec.rb +++ /dev/null @@ -1,227 +0,0 @@ -require "helper" - -class BoringVendorProvidedCLI < Thor - desc "boring", "do boring stuff" - def boring - puts "bored. " - end -end - -class ExcitingPluginCLI < Thor - desc "hooray", "say hooray!" - def hooray - puts "hooray!" - end - - desc "fireworks", "exciting fireworks!" - def fireworks - puts "kaboom!" - end -end - -class SuperSecretPlugin < Thor - default_command :squirrel - - desc "squirrel", "All of secret squirrel's secrets" - def squirrel - puts "I love nuts" - end -end - -class GroupPlugin < Thor::Group - desc "part one" - def part_one - puts "part one" - end - - desc "part two" - def part_two - puts "part two" - end -end - -class ClassOptionGroupPlugin < Thor::Group - class_option :who, - :type => :string, - :aliases => "-w", - :default => "zebra" -end - -class CompatibleWith19Plugin < ClassOptionGroupPlugin - desc "animal" - def animal - p options[:who] - end -end - -class PluginWithDefault < Thor - desc "say MSG", "print MSG" - def say(msg) - puts msg - end - - default_command :say -end - -class PluginWithDefaultMultipleArguments < Thor - desc "say MSG [MSG]", "print multiple messages" - def say(*args) - puts args - end - - default_command :say -end - -class PluginWithDefaultcommandAndDeclaredArgument < Thor - desc "say MSG [MSG]", "print multiple messages" - argument :msg - def say - puts msg - end - - default_command :say -end - -class SubcommandWithDefault < Thor - default_command :default - - desc "default", "default subcommand" - def default - puts "default" - end - - desc "with_args", "subcommand with arguments" - def with_args(*args) - puts "received arguments: " + args.join(",") - end -end - -BoringVendorProvidedCLI.register( - ExcitingPluginCLI, - "exciting", - "do exciting things", - "Various non-boring actions") - -BoringVendorProvidedCLI.register( - SuperSecretPlugin, - "secret", - "secret stuff", - "Nothing to see here. Move along.", - :hide => true) - -BoringVendorProvidedCLI.register( - GroupPlugin, - "groupwork", - "Do a bunch of things in a row", - "purple monkey dishwasher") - -BoringVendorProvidedCLI.register( - CompatibleWith19Plugin, - "zoo", - "zoo [-w animal]", - "Shows a provided animal or just zebra") - -BoringVendorProvidedCLI.register( - PluginWithDefault, - "say", - "say message", - "subcommands ftw") - -BoringVendorProvidedCLI.register( - PluginWithDefaultMultipleArguments, - "say_multiple", - "say message", - "subcommands ftw") - -BoringVendorProvidedCLI.register( - PluginWithDefaultcommandAndDeclaredArgument, - "say_argument", - "say message", - "subcommands ftw") - -BoringVendorProvidedCLI.register(SubcommandWithDefault, - "subcommand", "subcommand", "Run subcommands") - -describe ".register-ing a Thor subclass" do - it "registers the plugin as a subcommand" do - fireworks_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[exciting fireworks]) } - expect(fireworks_output).to eq("kaboom!\n") - end - - it "includes the plugin's usage in the help" do - help_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[help]) } - expect(help_output).to include("do exciting things") - end - - context "with a default command," do - it "invokes the default command correctly" do - output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[say hello]) } - expect(output).to include("hello") - end - - it "invokes the default command correctly with multiple args" do - output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[say_multiple hello adam]) } - expect(output).to include("hello") - expect(output).to include("adam") - end - - it "invokes the default command correctly with a declared argument" do - output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[say_argument hello]) } - expect(output).to include("hello") - end - - it "displays the subcommand's help message" do - output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[subcommand help]) } - expect(output).to include("default subcommand") - expect(output).to include("subcommand with argument") - end - - it "invokes commands with their actual args" do - output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[subcommand with_args actual_argument]) } - expect(output.strip).to eql("received arguments: actual_argument") - end - end - - context "when $thor_runner is false" do - it "includes the plugin's subcommand name in subcommand's help" do - begin - $thor_runner = false - help_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[exciting]) } - expect(help_output).to include("thor exciting_plugin_c_l_i fireworks") - ensure - $thor_runner = true - end - end - end - - context "when hidden" do - it "omits the hidden plugin's usage from the help" do - help_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[help]) } - expect(help_output).not_to include("secret stuff") - end - - it "registers the plugin as a subcommand" do - secret_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[secret squirrel]) } - expect(secret_output).to eq("I love nuts\n") - end - end -end - -describe ".register-ing a Thor::Group subclass" do - it "registers the group as a single command" do - group_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[groupwork]) } - expect(group_output).to eq("part one\npart two\n") - end -end - -describe "1.8 and 1.9 syntax compatibility" do - it "is compatible with both 1.8 and 1.9 syntax w/o command options" do - group_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[zoo]) } - expect(group_output).to match(/zebra/) - end - - it "is compatible with both 1.8 and 1.9 syntax w/command options" do - group_output = capture(:stdout) { BoringVendorProvidedCLI.start(%w[zoo -w lion]) } - expect(group_output).to match(/lion/) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/runner_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/runner_spec.rb deleted file mode 100644 index bf76885..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/runner_spec.rb +++ /dev/null @@ -1,246 +0,0 @@ -require "helper" -require "thor/runner" - -describe Thor::Runner do - def when_no_thorfiles_exist - old_dir = Dir.pwd - Dir.chdir ".." - delete = Thor::Base.subclasses.select { |e| e.namespace == "default" } - delete.each { |e| Thor::Base.subclasses.delete e } - yield - Thor::Base.subclasses.concat delete - Dir.chdir old_dir - end - - describe "#help" do - it "shows information about Thor::Runner itself" do - expect(capture(:stdout) { Thor::Runner.start(%w[help]) }).to match(/List the available thor commands/) - end - - it "shows information about a specific Thor::Runner command" do - content = capture(:stdout) { Thor::Runner.start(%w[help list]) } - expect(content).to match(/List the available thor commands/) - expect(content).not_to match(/help \[COMMAND\]/) - end - - it "shows information about a specific Thor class" do - content = capture(:stdout) { Thor::Runner.start(%w[help my_script]) } - expect(content).to match(/zoo\s+# zoo around/m) - end - - it "shows information about a specific command from a specific Thor class" do - content = capture(:stdout) { Thor::Runner.start(%w[help my_script:zoo]) } - expect(content).to match(/zoo around/) - expect(content).not_to match(/help \[COMMAND\]/) - end - - it "shows information about a specific Thor group class" do - content = capture(:stdout) { Thor::Runner.start(%w[help my_counter]) } - expect(content).to match(/my_counter N/) - end - - it "raises error if a class/command cannot be found" do - content = capture(:stderr) { Thor::Runner.start(%w[help unknown]) } - expect(content.strip).to eq('Could not find command "unknown" in "default" namespace.') - end - - it "raises error if a class/command cannot be found for a setup without thorfiles" do - when_no_thorfiles_exist do - expect(Thor::Runner).to receive :exit - content = capture(:stderr) { Thor::Runner.start(%w[help unknown]) } - expect(content.strip).to eq('Could not find command "unknown".') - end - end - end - - describe "#start" do - it "invokes a command from Thor::Runner" do - ARGV.replace %w[list] - expect(capture(:stdout) { Thor::Runner.start }).to match(/my_counter N/) - end - - it "invokes a command from a specific Thor class" do - ARGV.replace %w[my_script:zoo] - expect(Thor::Runner.start).to be true - end - - it "invokes the default command from a specific Thor class if none is specified" do - ARGV.replace %w[my_script] - expect(Thor::Runner.start).to eq("default command") - end - - it "forwards arguments to the invoked command" do - ARGV.replace %w[my_script:animal horse] - expect(Thor::Runner.start).to eq(%w[horse]) - end - - it "invokes commands through shortcuts" do - ARGV.replace %w[my_script -T horse] - expect(Thor::Runner.start).to eq(%w[horse]) - end - - it "invokes a Thor::Group" do - ARGV.replace %w[my_counter 1 2 --third 3] - expect(Thor::Runner.start).to eq([1, 2, 3, nil, nil, nil]) - end - - it "raises an error if class/command can't be found" do - ARGV.replace %w[unknown] - content = capture(:stderr) { Thor::Runner.start } - expect(content.strip).to eq('Could not find command "unknown" in "default" namespace.') - end - - it "raises an error if class/command can't be found in a setup without thorfiles" do - when_no_thorfiles_exist do - ARGV.replace %w[unknown] - expect(Thor::Runner).to receive :exit - content = capture(:stderr) { Thor::Runner.start } - expect(content.strip).to eq('Could not find command "unknown".') - end - end - - it "does not swallow NoMethodErrors that occur inside the called method" do - ARGV.replace %w[my_script:call_unexistent_method] - expect { Thor::Runner.start }.to raise_error(NoMethodError) - end - - it "does not swallow Thor::Group InvocationError" do - ARGV.replace %w[whiny_generator] - expect { Thor::Runner.start }.to raise_error(ArgumentError, /thor wrong_arity takes 1 argument, but it should not/) - end - - it "does not swallow Thor InvocationError" do - ARGV.replace %w[my_script:animal] - content = capture(:stderr) { Thor::Runner.start } - expect(content.strip).to eq(%Q(ERROR: "thor animal" was called with no arguments -Usage: "thor my_script:animal TYPE")) - end - end - - describe "commands" do - before do - @location = "#{File.dirname(__FILE__)}/fixtures/command.thor" - @original_yaml = { - "random" => { - :location => @location, - :filename => "4a33b894ffce85d7b412fc1b36f88fe0", - :namespaces => %w[amazing] - } - } - - root_file = File.join(Thor::Util.thor_root, "thor.yml") - - # Stub load and save to avoid thor.yaml from being overwritten - allow(YAML).to receive(:load_file).and_return(@original_yaml) - allow(File).to receive(:exist?).with(root_file).and_return(true) - allow(File).to receive(:open).with(root_file, "w") - end - - describe "list" do - it "gives a list of the available commands" do - ARGV.replace %w[list] - content = capture(:stdout) { Thor::Runner.start } - expect(content).to match(/amazing:describe NAME\s+# say that someone is amazing/m) - end - - it "gives a list of the available Thor::Group classes" do - ARGV.replace %w[list] - expect(capture(:stdout) { Thor::Runner.start }).to match(/my_counter N/) - end - - it "can filter a list of the available commands by --group" do - ARGV.replace %w[list --group standard] - expect(capture(:stdout) { Thor::Runner.start }).to match(/amazing:describe NAME/) - ARGV.replace [] - expect(capture(:stdout) { Thor::Runner.start }).not_to match(/my_script:animal TYPE/) - ARGV.replace %w[list --group script] - expect(capture(:stdout) { Thor::Runner.start }).to match(/my_script:animal TYPE/) - end - - it "can skip all filters to show all commands using --all" do - ARGV.replace %w[list --all] - content = capture(:stdout) { Thor::Runner.start } - expect(content).to match(/amazing:describe NAME/) - expect(content).to match(/my_script:animal TYPE/) - end - - it "doesn't list superclass commands in the subclass" do - ARGV.replace %w[list] - expect(capture(:stdout) { Thor::Runner.start }).not_to match(/amazing:help/) - end - - it "presents commands in the default namespace with an empty namespace" do - ARGV.replace %w[list] - expect(capture(:stdout) { Thor::Runner.start }).to match(/^thor :cow\s+# prints 'moo'/m) - end - - it "runs commands with an empty namespace from the default namespace" do - ARGV.replace %w[:command_conflict] - expect(capture(:stdout) { Thor::Runner.start }).to eq("command\n") - end - - it "runs groups even when there is a command with the same name" do - ARGV.replace %w[command_conflict] - expect(capture(:stdout) { Thor::Runner.start }).to eq("group\n") - end - - it "runs commands with no colon in the default namespace" do - ARGV.replace %w[cow] - expect(capture(:stdout) { Thor::Runner.start }).to eq("moo\n") - end - end - - describe "uninstall" do - before do - path = File.join(Thor::Util.thor_root, @original_yaml["random"][:filename]) - expect(FileUtils).to receive(:rm_rf).with(path) - end - - it "uninstalls existing thor modules" do - silence(:stdout) { Thor::Runner.start(%w[uninstall random]) } - end - end - - describe "installed" do - before do - expect(Dir).to receive(:[]).and_return([]) - end - - it "displays the modules installed in a pretty way" do - stdout = capture(:stdout) { Thor::Runner.start(%w[installed]) } - expect(stdout).to match(/random\s*amazing/) - expect(stdout).to match(/amazing:describe NAME\s+# say that someone is amazing/m) - end - end - - describe "install/update" do - before do - allow(FileUtils).to receive(:mkdir_p) - allow(FileUtils).to receive(:touch) - allow(Thor::LineEditor).to receive(:readline).and_return("Y") - - path = File.join(Thor::Util.thor_root, Digest::MD5.hexdigest(@location + "random")) - expect(File).to receive(:open).with(path, "w") - end - - it "updates existing thor files" do - path = File.join(Thor::Util.thor_root, @original_yaml["random"][:filename]) - if File.directory? path - expect(FileUtils).to receive(:rm_rf).with(path) - else - expect(File).to receive(:delete).with(path) - end - silence_warnings do - silence(:stdout) { Thor::Runner.start(%w[update random]) } - end - end - - it "installs thor files" do - ARGV.replace %W[install #{@location}] - silence_warnings do - silence(:stdout) { Thor::Runner.start } - end - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/application.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/application.rb deleted file mode 100644 index 50d2fae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/application.rb +++ /dev/null @@ -1,2 +0,0 @@ -class Application < Base -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/app{1}/README b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/app{1}/README deleted file mode 100644 index 16374df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/app{1}/README +++ /dev/null @@ -1,3 +0,0 @@ -__start__ -README -__end__ diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/bundle/execute.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/bundle/execute.rb deleted file mode 100644 index 0530d87..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/bundle/execute.rb +++ /dev/null @@ -1,6 +0,0 @@ -class Execute < Thor - desc "ls", "Execute ls" - def ls - system "ls" - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/bundle/main.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/bundle/main.thor deleted file mode 100644 index 38bdfbc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/bundle/main.thor +++ /dev/null @@ -1 +0,0 @@ -require File.join(File.dirname(__FILE__), 'execute') diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/command.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/command.thor deleted file mode 100644 index 26a0268..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/command.thor +++ /dev/null @@ -1,10 +0,0 @@ -# module: random - -class Amazing < Thor - desc "describe NAME", "say that someone is amazing" - method_options :forcefully => :boolean - def describe(name, opts) - ret = "#{name} is amazing" - puts opts["forcefully"] ? ret.upcase : ret - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/%file_name%.rb.tt b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/%file_name%.rb.tt deleted file mode 100644 index 4c4c6c0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/%file_name%.rb.tt +++ /dev/null @@ -1 +0,0 @@ -FOO = <%= "FOO" %> diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/COMMENTER b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/COMMENTER deleted file mode 100644 index 384cb3a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/COMMENTER +++ /dev/null @@ -1,11 +0,0 @@ -__start__ - # greenblue -# -# yellowblue -#yellowred - #greenred -orange - purple - ind#igo - # ind#igo -__end__ diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/README b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/README deleted file mode 100644 index 16374df..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/README +++ /dev/null @@ -1,3 +0,0 @@ -__start__ -README -__end__ diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/block_helper.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/block_helper.rb deleted file mode 100644 index df59211..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/block_helper.rb +++ /dev/null @@ -1,3 +0,0 @@ -<% world do -%> -Hello -<% end -%> diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/config.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/config.rb deleted file mode 100644 index 6211739..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/config.rb +++ /dev/null @@ -1 +0,0 @@ -class <%= @klass %>; end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/config.yaml.tt b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/config.yaml.tt deleted file mode 100644 index e75615c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/config.yaml.tt +++ /dev/null @@ -1 +0,0 @@ ---- Hi from yaml diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/excluding/%file_name%.rb.tt b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/excluding/%file_name%.rb.tt deleted file mode 100644 index 6296c46..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/doc/excluding/%file_name%.rb.tt +++ /dev/null @@ -1 +0,0 @@ -BAR = <%= "BAR" %> diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/enum.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/enum.thor deleted file mode 100644 index b5a7ded..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/enum.thor +++ /dev/null @@ -1,10 +0,0 @@ -class Enum < Thor::Group - include Thor::Actions - - desc "snack" - class_option "fruit", :aliases => "-f", :type => :string, :enum => %w(apple banana) - def snack - puts options['fruit'] - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/group.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/group.thor deleted file mode 100644 index bc7e102..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/group.thor +++ /dev/null @@ -1,128 +0,0 @@ -class MyCounter < Thor::Group - include Thor::Actions - add_runtime_options! - - def self.get_from_super - from_superclass(:get_from_super, 13) - end - - source_root File.expand_path(File.dirname(__FILE__)) - source_paths << File.expand_path("broken", File.dirname(__FILE__)) - - argument :first, :type => :numeric - argument :second, :type => :numeric, :default => 2 - - class_option :third, :type => :numeric, :desc => "The third argument", :default => 3, - :banner => "THREE", :aliases => "-t" - class_option :fourth, :type => :numeric, :desc => "The fourth argument" - class_option :simple, :type => :numeric, :aliases => 'z' - class_option :symbolic, :type => :numeric, :aliases => [:y, :r] - - desc <<-FOO -Description: - This generator runs three commands: one, two and three. -FOO - - def one - first - end - - def two - second - end - - def three - options[:third] - end - - def four - options[:fourth] - end - - def five - options[:simple] - end - - def six - options[:symbolic] - end - - def self.inherited(base) - super - base.source_paths.unshift(File.expand_path(File.join(File.dirname(__FILE__), "doc"))) - end - - no_commands do - def world(&block) - result = capture(&block) - concat(result.strip + " world!") - end - end -end - -class ClearCounter < MyCounter - remove_argument :first, :second, :undefine => true - remove_class_option :third - - def self.source_root - File.expand_path(File.join(File.dirname(__FILE__), "bundle")) - end -end - -class BrokenCounter < MyCounter - namespace "app:broken:counter" - class_option :fail, :type => :boolean, :default => false - - class << self - undef_method :source_root - end - - def one - options[:first] - end - - def four - respond_to?(:fail) - end - - def five - options[:fail] ? this_method_does_not_exist : 5 - end -end - -class WhinyGenerator < Thor::Group - include Thor::Actions - - def self.source_root - File.expand_path(File.dirname(__FILE__)) - end - - def wrong_arity(required) - end -end - -class CommandConflict < Thor::Group - desc "A group with the same name as a default command" - def group - puts "group" - end -end - -class ParentGroup < Thor::Group -private - def foo - "foo" - end - - def baz(name = 'baz') - name - end -end - -class ChildGroup < ParentGroup - def bar - "bar" - end - - public_command :foo, :baz -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/invoke.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/invoke.thor deleted file mode 100644 index 0e76e98..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/invoke.thor +++ /dev/null @@ -1,131 +0,0 @@ -class A < Thor - include Thor::Actions - - desc "one", "invoke one" - def one - p 1 - invoke :two - invoke :three - end - - desc "two", "invoke two" - def two - p 2 - invoke :three - end - - desc "three", "invoke three" - def three - p 3 - end - - desc "four", "invoke four" - def four - p 4 - invoke "defined:five" - end - - desc "five N", "check if number is equal 5" - def five(number) - number == 5 - end - - desc "invoker", "invoke a b command" - def invoker(*args) - invoke :b, :one, ["Jose"] - end -end - -class B < Thor - class_option :last_name, :type => :string - - desc "one FIRST_NAME", "invoke one" - def one(first_name) - "#{options.last_name}, #{first_name}" - end - - desc "two", "invoke two" - def two - options - end - - desc "three", "invoke three" - def three - self - end - - desc "four", "invoke four" - option :defaulted_value, :type => :string, :default => 'default' - def four - options.defaulted_value - end -end - -class C < Thor::Group - include Thor::Actions - - def one - p 1 - end - - def two - p 2 - end - - def three - p 3 - end -end - -class Defined < Thor::Group - class_option :unused, :type => :boolean, :desc => "This option has no use" - - def one - p 1 - invoke "a:two" - invoke "a:three" - invoke "a:four" - invoke "defined:five" - end - - def five - p 5 - end - - def print_status - say_status :finished, :counting - end -end - -class E < Thor::Group - invoke Defined -end - -class F < Thor::Group - invoke "b:one" do |instance, klass, command| - instance.invoke klass, command, [ "Jose" ], :last_name => "Valim" - end -end - -class G < Thor::Group - class_option :invoked, :type => :string, :default => "defined" - invoke_from_option :invoked -end - -class H < Thor::Group - class_option :defined, :type => :boolean, :default => true - invoke_from_option :defined -end - -class I < Thor - desc "two", "Two" - def two - current_command_chain - end -end - -class J < Thor - desc "i", "I" - subcommand :one, I -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/path with spaces b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/path with spaces deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/preserve/script.sh b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/preserve/script.sh deleted file mode 100755 index c52d3c2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/preserve/script.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/sh - -exit 0 diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/script.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/script.thor deleted file mode 100644 index 357b6e5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/script.thor +++ /dev/null @@ -1,220 +0,0 @@ -class MyScript < Thor - check_unknown_options! :except => :with_optional - - attr_accessor :some_attribute - attr_writer :another_attribute - attr_reader :another_attribute - - private - attr_reader :private_attribute - - public - group :script - default_command :example_default_command - - map "-T" => :animal, ["-f", "--foo"] => :foo - - map "animal_prison" => "zoo" - - desc "zoo", "zoo around" - def zoo - true - end - - desc "animal TYPE", "horse around" - - no_commands do - def this_is_not_a_command - end - end - - def animal(type) - [type] - end - - map "hid" => "hidden" - - desc "hidden TYPE", "this is hidden", :hide => true - def hidden(type) - [type] - end - - map "fu" => "zoo" - - desc "foo BAR", < :boolean, :desc => "Force to do some fooing" - def foo(bar) - [bar, options] - end - - desc "example_default_command", "example!" - method_options :with => :string - def example_default_command - options.empty? ? "default command" : options - end - - desc "call_myself_with_wrong_arity", "get the right error" - def call_myself_with_wrong_arity - call_myself_with_wrong_arity(4) - end - - desc "call_unexistent_method", "Call unexistent method inside a command" - def call_unexistent_method - boom! - end - - desc "long_description", "a" * 80 - long_desc <<-D - This is a really really really long description. - Here you go. So very long. - - It even has two paragraphs. - D - def long_description - end - - desc "name-with-dashes", "Ensure normalization of command names" - def name_with_dashes - end - - method_options :all => :boolean - method_option :lazy, :lazy_default => "yes" - method_option :lazy_numeric, :type => :numeric, :lazy_default => 42 - method_option :lazy_array, :type => :array, :lazy_default => %w[eat at joes] - method_option :lazy_hash, :type => :hash, :lazy_default => {'swedish' => 'meatballs'} - desc "with_optional NAME", "invoke with optional name" - def with_optional(name=nil, *args) - [name, options, args] - end - - class AnotherScript < Thor - desc "baz", "do some bazing" - def baz - end - end - - desc "send", "send as a command name" - def send - true - end - - private - - def method_missing(meth, *args) - if meth == :boom! - super - else - [meth, args] - end - end - - desc "what", "what" - def what - end -end - -class MyChildScript < MyScript - remove_command :bar - - method_options :force => :boolean, :param => :numeric - def initialize(*args) - super - end - - desc "zoo", "zoo around" - method_options :param => :required - def zoo - options - end - - desc "animal TYPE", "horse around" - def animal(type) - [type, options] - end - method_option :other, :type => :string, :default => "method default", :for => :animal - desc "animal KIND", "fish around", :for => :animal - - desc "boom", "explodes everything" - def boom - end - - remove_command :boom, :undefine => true -end - -class Barn < Thor - desc "open [ITEM]", "open the barn door" - def open(item = nil) - if item == "shotgun" - puts "That's going to leave a mark." - else - puts "Open sesame!" - end - end - - desc "paint [COLOR]", "paint the barn" - method_option :coats, :type => :numeric, :default => 2, :desc => 'how many coats of paint' - def paint(color='red') - puts "#{options[:coats]} coats of #{color} paint" - end -end - -class PackageNameScript < Thor - package_name "Baboon" -end - -module Scripts - class MyScript < MyChildScript - argument :accessor, :type => :string - class_options :force => :boolean - method_option :new_option, :type => :string, :for => :example_default_command - - def zoo - self.accessor - end - end - - class MyDefaults < Thor - check_unknown_options! - - namespace :default - desc "cow", "prints 'moo'" - def cow - puts "moo" - end - - desc "command_conflict", "only gets called when prepended with a colon" - def command_conflict - puts "command" - end - - desc "barn", "commands to manage the barn" - subcommand "barn", Barn - end - - class ChildDefault < Thor - namespace "default:child" - end - - class Arities < Thor - desc "zero_args", "takes zero args" - def zero_args - end - - desc "one_arg ARG", "takes one arg" - def one_arg(arg) - end - - desc "two_args ARG1 ARG2", "takes two args" - def two_args(arg1, arg2) - end - - desc "optional_arg [ARG]", "takes an optional arg" - def optional_arg(arg='default') - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/subcommand.thor b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/subcommand.thor deleted file mode 100644 index 35d0b57..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/sandbox/subcommand.thor +++ /dev/null @@ -1,17 +0,0 @@ -module TestSubcommands - - class Subcommand < Thor - desc "print_opt", "My method" - def print_opt - print options["opt"] - end - end - - class Parent < Thor - class_option "opt" - - desc "sub", "My subcommand" - subcommand "sub", Subcommand - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/basic_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/basic_spec.rb deleted file mode 100644 index 417f371..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/basic_spec.rb +++ /dev/null @@ -1,337 +0,0 @@ -# coding: utf-8 -require "helper" - -describe Thor::Shell::Basic do - def shell - @shell ||= Thor::Shell::Basic.new - end - - describe "#padding" do - it "cannot be set to below zero" do - shell.padding = 10 - expect(shell.padding).to eq(10) - - shell.padding = -1 - expect(shell.padding).to eq(0) - end - end - - describe "#ask" do - it "prints a message to the user and gets the response" do - expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", {}).and_return("Sure") - expect(shell.ask("Should I overwrite it?")).to eq("Sure") - end - - it "prints a message to the user prefixed with the current padding" do - expect(Thor::LineEditor).to receive(:readline).with(" Enter your name: ", {}).and_return("George") - shell.padding = 2 - shell.ask("Enter your name:") - end - - it "prints a message and returns nil if EOF is given as input" do - expect(Thor::LineEditor).to receive(:readline).with(" ", {}).and_return(nil) - expect(shell.ask("")).to eq(nil) - end - - it "prints a message to the user and does not echo stdin if the echo option is set to false" do - expect($stdout).to receive(:print).with('What\'s your password? ') - expect($stdin).to receive(:noecho).and_return("mysecretpass") - expect(shell.ask("What's your password?", :echo => false)).to eq("mysecretpass") - end - - it "prints a message to the user with the available options and determines the correctness of the answer" do - flavors = %w[strawberry chocolate vanilla] - expect(Thor::LineEditor).to receive(:readline).with('What\'s your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] ', :limited_to => flavors).and_return("chocolate") - expect(shell.ask('What\'s your favorite Neopolitan flavor?', :limited_to => flavors)).to eq("chocolate") - end - - it "prints a message to the user with the available options and reasks the question after an incorrect repsonse" do - flavors = %w[strawberry chocolate vanilla] - expect($stdout).to receive(:print).with("Your response must be one of: [strawberry, chocolate, vanilla]. Please try again.\n") - expect(Thor::LineEditor).to receive(:readline).with('What\'s your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] ', :limited_to => flavors).and_return("moose tracks", "chocolate") - expect(shell.ask('What\'s your favorite Neopolitan flavor?', :limited_to => flavors)).to eq("chocolate") - end - - it "prints a message to the user containing a default and sets the default if only enter is pressed" do - expect(Thor::LineEditor).to receive(:readline).with('What\'s your favorite Neopolitan flavor? (vanilla) ', :default => "vanilla").and_return("") - expect(shell.ask('What\'s your favorite Neopolitan flavor?', :default => "vanilla")).to eq("vanilla") - end - - it "prints a message to the user with the available options and reasks the question after an incorrect repsonse and then returns the default" do - flavors = %w[strawberry chocolate vanilla] - expect($stdout).to receive(:print).with("Your response must be one of: [strawberry, chocolate, vanilla]. Please try again.\n") - expect(Thor::LineEditor).to receive(:readline).with('What\'s your favorite Neopolitan flavor? [strawberry, chocolate, vanilla] (vanilla) ', :default => "vanilla", :limited_to => flavors).and_return("moose tracks", "") - expect(shell.ask("What's your favorite Neopolitan flavor?", :default => "vanilla", :limited_to => flavors)).to eq("vanilla") - end - end - - describe "#yes?" do - it "asks the user and returns true if the user replies yes" do - expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", :add_to_history => false).and_return("y") - expect(shell.yes?("Should I overwrite it?")).to be_true - end - - it "asks the user and returns false if the user replies no" do - expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", :add_to_history => false).and_return("n") - expect(shell.yes?("Should I overwrite it?")).not_to be_true - end - - it "asks the user and returns false if the user replies with an answer other than yes or no" do - expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", :add_to_history => false).and_return("foobar") - expect(shell.yes?("Should I overwrite it?")).to be_false - end - end - - describe "#no?" do - it "asks the user and returns true if the user replies no" do - expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", :add_to_history => false).and_return("n") - expect(shell.no?("Should I overwrite it?")).to be_true - end - - it "asks the user and returns false if the user replies yes" do - expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", :add_to_history => false).and_return("Yes") - expect(shell.no?("Should I overwrite it?")).to be_false - end - - it "asks the user and returns false if the user replies with an answer other than yes or no" do - expect(Thor::LineEditor).to receive(:readline).with("Should I overwrite it? ", :add_to_history => false).and_return("foobar") - expect(shell.no?("Should I overwrite it?")).to be_false - end - end - - describe "#say" do - it "prints a message to the user" do - expect($stdout).to receive(:print).with("Running...\n") - shell.say("Running...") - end - - it "prints a message to the user without new line if it ends with a whitespace" do - expect($stdout).to receive(:print).with("Running... ") - shell.say("Running... ") - end - - it "does not use a new line with whitespace+newline embedded" do - expect($stdout).to receive(:print).with("It's \nRunning...\n") - shell.say("It's \nRunning...") - end - - it "prints a message to the user without new line" do - expect($stdout).to receive(:print).with("Running...") - shell.say("Running...", nil, false) - end - - it "coerces everything to a string before printing" do - expect($stdout).to receive(:print).with("this_is_not_a_string\n") - shell.say(:this_is_not_a_string, nil, true) - end - end - - describe "#say_status" do - it "prints a message to the user with status" do - expect($stdout).to receive(:print).with(" create ~/.thor/command.thor\n") - shell.say_status(:create, "~/.thor/command.thor") - end - - it "always uses new line" do - expect($stdout).to receive(:print).with(" create \n") - shell.say_status(:create, "") - end - - it "does not print a message if base is muted" do - expect(shell).to receive(:mute?).and_return(true) - expect($stdout).not_to receive(:print) - - shell.mute do - shell.say_status(:created, "~/.thor/command.thor") - end - end - - it "does not print a message if base is set to quiet" do - base = MyCounter.new [1, 2] - expect(base).to receive(:options).and_return(:quiet => true) - - expect($stdout).not_to receive(:print) - shell.base = base - shell.say_status(:created, "~/.thor/command.thor") - end - - it "does not print a message if log status is set to false" do - expect($stdout).not_to receive(:print) - shell.say_status(:created, "~/.thor/command.thor", false) - end - - it "uses padding to set message's left margin" do - shell.padding = 2 - expect($stdout).to receive(:print).with(" create ~/.thor/command.thor\n") - shell.say_status(:create, "~/.thor/command.thor") - end - end - - describe "#print_in_columns" do - before do - @array = [1_234_567_890] - @array += ("a".."e").to_a - end - - it "prints in columns" do - content = capture(:stdout) { shell.print_in_columns(@array) } - expect(content.rstrip).to eq("1234567890 a b c d e") - end - end - - describe "#print_table" do - before do - @table = [] - @table << ["abc", "#123", "first three"] - @table << ["", "#0", "empty"] - @table << ["xyz", "#786", "last three"] - end - - it "prints a table" do - content = capture(:stdout) { shell.print_table(@table) } - expect(content).to eq(<<-TABLE) -abc #123 first three - #0 empty -xyz #786 last three -TABLE - end - - it "prints a table with indentation" do - content = capture(:stdout) { shell.print_table(@table, :indent => 2) } - expect(content).to eq(<<-TABLE) - abc #123 first three - #0 empty - xyz #786 last three -TABLE - end - - it "uses maximum terminal width" do - @table << ["def", "#456", "Lançam foo bar"] - @table << ["ghi", "#789", "بالله عليكم"] - expect(shell).to receive(:terminal_width).and_return(20) - content = capture(:stdout) { shell.print_table(@table, :indent => 2, :truncate => true) } - expect(content).to eq(<<-TABLE) - abc #123 firs... - #0 empty - xyz #786 last... - def #456 Lanç... - ghi #789 بالل... -TABLE - end - - it "honors the colwidth option" do - content = capture(:stdout) { shell.print_table(@table, :colwidth => 10) } - expect(content).to eq(<<-TABLE) -abc #123 first three - #0 empty -xyz #786 last three -TABLE - end - - it "prints tables with implicit columns" do - 2.times { @table.first.pop } - content = capture(:stdout) { shell.print_table(@table) } - expect(content).to eq(<<-TABLE) -abc - #0 empty -xyz #786 last three -TABLE - end - - it "prints a table with small numbers and right-aligns them" do - table = [ - ["Name", "Number", "Color"], # rubocop: disable WordArray - ["Erik", 1, "green"] - ] - content = capture(:stdout) { shell.print_table(table) } - expect(content).to eq(<<-TABLE) -Name Number Color -Erik 1 green -TABLE - end - - it "doesn't output extra spaces for right-aligned columns in the last column" do - table = [ - ["Name", "Number"], # rubocop: disable WordArray - ["Erik", 1] - ] - content = capture(:stdout) { shell.print_table(table) } - expect(content).to eq(<<-TABLE) -Name Number -Erik 1 -TABLE - end - - it "prints a table with big numbers" do - table = [ - ["Name", "Number", "Color"], # rubocop: disable WordArray - ["Erik", 1_234_567_890_123, "green"] - ] - content = capture(:stdout) { shell.print_table(table) } - expect(content).to eq(<<-TABLE) -Name Number Color -Erik 1234567890123 green -TABLE - end - end - - describe "#file_collision" do - it "shows a menu with options" do - expect(Thor::LineEditor).to receive(:readline).with('Overwrite foo? (enter "h" for help) [Ynaqh] ', :add_to_history => false).and_return("n") - shell.file_collision("foo") - end - - it "returns true if the user chooses default option" do - expect(Thor::LineEditor).to receive(:readline).and_return("") - expect(shell.file_collision("foo")).to be_true - end - - it "returns false if the user chooses no" do - expect(Thor::LineEditor).to receive(:readline).and_return("n") - expect(shell.file_collision("foo")).to be_false - end - - it "returns true if the user chooses yes" do - expect(Thor::LineEditor).to receive(:readline).and_return("y") - expect(shell.file_collision("foo")).to be_true - end - - it "shows help usage if the user chooses help" do - expect(Thor::LineEditor).to receive(:readline).and_return("h", "n") - help = capture(:stdout) { shell.file_collision("foo") } - expect(help).to match(/h \- help, show this help/) - end - - it "quits if the user chooses quit" do - expect($stdout).to receive(:print).with("Aborting...\n") - expect(Thor::LineEditor).to receive(:readline).and_return("q") - - expect do - shell.file_collision("foo") - end.to raise_error(SystemExit) - end - - it "always returns true if the user chooses always" do - expect(Thor::LineEditor).to receive(:readline).with('Overwrite foo? (enter "h" for help) [Ynaqh] ', :add_to_history => false).and_return("a") - - expect(shell.file_collision("foo")).to be true - - expect($stdout).not_to receive(:print) - expect(shell.file_collision("foo")).to be true - end - - describe "when a block is given" do - it "displays diff options to the user" do - expect(Thor::LineEditor).to receive(:readline).with('Overwrite foo? (enter "h" for help) [Ynaqdh] ', :add_to_history => false).and_return("s") - shell.file_collision("foo") {} - end - - it "invokes the diff command" do - expect(Thor::LineEditor).to receive(:readline).and_return("d") - expect(Thor::LineEditor).to receive(:readline).and_return("n") - expect(shell).to receive(:system).with(/diff -u/) - capture(:stdout) { shell.file_collision("foo") {} } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/color_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/color_spec.rb deleted file mode 100644 index 196e6b6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/color_spec.rb +++ /dev/null @@ -1,119 +0,0 @@ -require "helper" - -describe Thor::Shell::Color do - def shell - @shell ||= Thor::Shell::Color.new - end - - before do - allow($stdout).to receive(:tty?).and_return(true) - allow_any_instance_of(StringIO).to receive(:tty?).and_return(true) - end - - describe "#ask" do - it "sets the color if specified and tty?" do - expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? \e[0m", anything).and_return("yes") - shell.ask "Is this green?", :green - - expect(Thor::LineEditor).to receive(:readline).with("\e[32mIs this green? [Yes, No, Maybe] \e[0m", anything).and_return("Yes") - shell.ask "Is this green?", :green, :limited_to => %w[Yes No Maybe] - end - end - - describe "#say" do - it "set the color if specified and tty?" do - out = capture(:stdout) do - shell.say "Wow! Now we have colors!", :green - end - - expect(out.chomp).to eq("\e[32mWow! Now we have colors!\e[0m") - end - - it "does not set the color if output is not a tty" do - out = capture(:stdout) do - expect($stdout).to receive(:tty?).and_return(false) - shell.say "Wow! Now we have colors!", :green - end - - expect(out.chomp).to eq("Wow! Now we have colors!") - end - - it "does not use a new line even with colors" do - out = capture(:stdout) do - shell.say "Wow! Now we have colors! ", :green - end - - expect(out.chomp).to eq("\e[32mWow! Now we have colors! \e[0m") - end - - it "handles an Array of colors" do - out = capture(:stdout) do - shell.say "Wow! Now we have colors *and* background colors", [:green, :on_red, :bold] - end - - expect(out.chomp).to eq("\e[32m\e[41m\e[1mWow! Now we have colors *and* background colors\e[0m") - end - end - - describe "#say_status" do - it "uses color to say status" do - out = capture(:stdout) do - shell.say_status :conflict, "README", :red - end - - expect(out.chomp).to eq("\e[1m\e[31m conflict\e[0m README") - end - end - - describe "#set_color" do - it "colors a string with a foreground color" do - red = shell.set_color "hi!", :red - expect(red).to eq("\e[31mhi!\e[0m") - end - - it "colors a string with a background color" do - on_red = shell.set_color "hi!", :white, :on_red - expect(on_red).to eq("\e[37m\e[41mhi!\e[0m") - end - - it "colors a string with a bold color" do - bold = shell.set_color "hi!", :white, true - expect(bold).to eq("\e[1m\e[37mhi!\e[0m") - - bold = shell.set_color "hi!", :white, :bold - expect(bold).to eq("\e[37m\e[1mhi!\e[0m") - - bold = shell.set_color "hi!", :white, :on_red, :bold - expect(bold).to eq("\e[37m\e[41m\e[1mhi!\e[0m") - end - - it "does nothing when there are no colors" do - colorless = shell.set_color "hi!", nil - expect(colorless).to eq("hi!") - - colorless = shell.set_color "hi!" - expect(colorless).to eq("hi!") - end - - it "does nothing when the terminal does not support color" do - allow($stdout).to receive(:tty?).and_return(false) - colorless = shell.set_color "hi!", :white - expect(colorless).to eq("hi!") - end - end - - describe "#file_collision" do - describe "when a block is given" do - it "invokes the diff command" do - allow($stdout).to receive(:print) - allow($stdout).to receive(:tty?).and_return(true) - expect(Thor::LineEditor).to receive(:readline).and_return("d", "n") - - output = capture(:stdout) { shell.file_collision("spec/fixtures/doc/README") { "README\nEND\n" } } - expect(output).to match(/\e\[31m\- __start__\e\[0m/) - expect(output).to match(/^ README/) - expect(output).to match(/\e\[32m\+ END\e\[0m/) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/html_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/html_spec.rb deleted file mode 100644 index 1a6ef89..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell/html_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require "helper" - -describe Thor::Shell::HTML do - def shell - @shell ||= Thor::Shell::HTML.new - end - - describe "#say" do - it "sets the color if specified" do - out = capture(:stdout) { shell.say "Wow! Now we have colors!", :green } - expect(out.chomp).to eq('Wow! Now we have colors!') - end - - it "sets bold if specified" do - out = capture(:stdout) { shell.say "Wow! Now we have colors *and* bold!", [:green, :bold] } - expect(out.chomp).to eq('Wow! Now we have colors *and* bold!') - end - - it "does not use a new line even with colors" do - out = capture(:stdout) { shell.say "Wow! Now we have colors! ", :green } - expect(out.chomp).to eq('Wow! Now we have colors! ') - end - end - - describe "#say_status" do - it "uses color to say status" do - expect($stdout).to receive(:print).with(" conflict README\n") - shell.say_status :conflict, "README", :red - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell_spec.rb deleted file mode 100644 index 17e4d78..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/shell_spec.rb +++ /dev/null @@ -1,47 +0,0 @@ -require "helper" - -describe Thor::Shell do - def shell - @shell ||= Thor::Base.shell.new - end - - describe "#initialize" do - it "sets shell value" do - base = MyCounter.new [1, 2], {}, :shell => shell - expect(base.shell).to eq(shell) - end - - it "sets the base value on the shell if an accessor is available" do - base = MyCounter.new [1, 2], {}, :shell => shell - expect(shell.base).to eq(base) - end - end - - describe "#shell" do - it "returns the shell in use" do - expect(MyCounter.new([1, 2]).shell).to be_kind_of(Thor::Base.shell) - end - - it "uses $THOR_SHELL" do - class Thor::Shell::TestShell < Thor::Shell::Basic; end - - expect(Thor::Base.shell).to eq(shell.class) - ENV["THOR_SHELL"] = "TestShell" - Thor::Base.shell = nil - expect(Thor::Base.shell).to eq(Thor::Shell::TestShell) - ENV["THOR_SHELL"] = "" - Thor::Base.shell = shell.class - expect(Thor::Base.shell).to eq(shell.class) - end - end - - describe "with_padding" do - it "uses padding for inside block outputs" do - base = MyCounter.new([1, 2]) - base.with_padding do - expect(capture(:stdout) { base.say_status :padding, "cool" }.strip).to eq("padding cool") - end - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/subcommand_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/subcommand_spec.rb deleted file mode 100644 index f189f21..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/subcommand_spec.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "helper" - -describe Thor do - - describe "#subcommand" do - - it "maps a given subcommand to another Thor subclass" do - barn_help = capture(:stdout) { Scripts::MyDefaults.start(%w[barn]) } - expect(barn_help).to include("barn help [COMMAND] # Describe subcommands or one specific subcommand") - end - - it "passes commands to subcommand classes" do - expect(capture(:stdout) { Scripts::MyDefaults.start(%w[barn open]) }.strip).to eq("Open sesame!") - end - - it "passes arguments to subcommand classes" do - expect(capture(:stdout) { Scripts::MyDefaults.start(%w[barn open shotgun]) }.strip).to eq("That's going to leave a mark.") - end - - it "ignores unknown options (the subcommand class will handle them)" do - expect(capture(:stdout) { Scripts::MyDefaults.start(%w[barn paint blue --coats 4]) }.strip).to eq("4 coats of blue paint") - end - - it "passes parsed options to subcommands" do - output = capture(:stdout) { TestSubcommands::Parent.start(%w[sub print_opt --opt output]) } - expect(output).to eq("output") - end - - it "accepts the help switch and calls the help command on the subcommand" do - output = capture(:stdout) { TestSubcommands::Parent.start(%w[sub print_opt --help]) } - sub_help = capture(:stdout) { TestSubcommands::Parent.start(%w[sub help print_opt]) } - expect(output).to eq(sub_help) - end - - it "accepts the help short switch and calls the help command on the subcommand" do - output = capture(:stdout) { TestSubcommands::Parent.start(%w[sub print_opt -h]) } - sub_help = capture(:stdout) { TestSubcommands::Parent.start(%w[sub help print_opt]) } - expect(output).to eq(sub_help) - end - - it "the help command on the subcommand and after it should result in the same output" do - output = capture(:stdout) { TestSubcommands::Parent.start(%w[sub help])} - sub_help = capture(:stdout) { TestSubcommands::Parent.start(%w[help sub])} - expect(output).to eq(sub_help) - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/thor_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/thor_spec.rb deleted file mode 100644 index 55450dc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/thor_spec.rb +++ /dev/null @@ -1,505 +0,0 @@ -require "helper" - -describe Thor do - describe "#method_option" do - it "sets options to the next method to be invoked" do - args = %w[foo bar --force] - _, options = MyScript.start(args) - expect(options).to eq("force" => true) - end - - describe ":lazy_default" do - it "is absent when option is not specified" do - _, options = MyScript.start(%w[with_optional]) - expect(options).to eq({}) - end - - it "sets a default that can be overridden for strings" do - _, options = MyScript.start(%w[with_optional --lazy]) - expect(options).to eq("lazy" => "yes") - - _, options = MyScript.start(%w[with_optional --lazy yesyes!]) - expect(options).to eq("lazy" => "yesyes!") - end - - it "sets a default that can be overridden for numerics" do - _, options = MyScript.start(%w[with_optional --lazy-numeric]) - expect(options).to eq("lazy_numeric" => 42) - - _, options = MyScript.start(%w[with_optional --lazy-numeric 20000]) - expect(options).to eq("lazy_numeric" => 20_000) - end - - it "sets a default that can be overridden for arrays" do - _, options = MyScript.start(%w[with_optional --lazy-array]) - expect(options).to eq("lazy_array" => %w[eat at joes]) - - _, options = MyScript.start(%w[with_optional --lazy-array hello there]) - expect(options).to eq("lazy_array" => %w[hello there]) - end - - it "sets a default that can be overridden for hashes" do - _, options = MyScript.start(%w[with_optional --lazy-hash]) - expect(options).to eq("lazy_hash" => {"swedish" => "meatballs"}) - - _, options = MyScript.start(%w[with_optional --lazy-hash polish:sausage]) - expect(options).to eq("lazy_hash" => {"polish" => "sausage"}) - end - end - - describe "when :for is supplied" do - it "updates an already defined command" do - _, options = MyChildScript.start(%w[animal horse --other=fish]) - expect(options[:other]).to eq("fish") - end - - describe "and the target is on the parent class" do - it "updates an already defined command" do - args = %w[example_default_command my_param --new-option=verified] - options = Scripts::MyScript.start(args) - expect(options[:new_option]).to eq("verified") - end - - it "adds a command to the command list if the updated command is on the parent class" do - expect(Scripts::MyScript.commands["example_default_command"]).to be - end - - it "clones the parent command" do - expect(Scripts::MyScript.commands["example_default_command"]).not_to eq(MyChildScript.commands["example_default_command"]) - end - end - end - end - - describe "#default_command" do - it "sets a default command" do - expect(MyScript.default_command).to eq("example_default_command") - end - - it "invokes the default command if no command is specified" do - expect(MyScript.start([])).to eq("default command") - end - - it "invokes the default command if no command is specified even if switches are given" do - expect(MyScript.start(%w[--with option])).to eq("with" => "option") - end - - it "inherits the default command from parent" do - expect(MyChildScript.default_command).to eq("example_default_command") - end - end - - describe "#stop_on_unknown_option!" do - my_script = Class.new(Thor) do - class_option "verbose", :type => :boolean - class_option "mode", :type => :string - - stop_on_unknown_option! :exec - - desc "exec", "Run a command" - def exec(*args) - [options, args] - end - - desc "boring", "An ordinary command" - def boring(*args) - [options, args] - end - end - - it "passes remaining args to command when it encounters a non-option" do - expect(my_script.start(%w[exec command --verbose])).to eq [{}, %w[command --verbose]] - end - - it "passes remaining args to command when it encounters an unknown option" do - expect(my_script.start(%w[exec --foo command --bar])).to eq [{}, %w[--foo command --bar]] - end - - it "still accepts options that are given before non-options" do - expect(my_script.start(%w[exec --verbose command --foo])).to eq [{"verbose" => true}, %w[command --foo]] - end - - it "still accepts options that require a value" do - expect(my_script.start(%w[exec --mode rashly command])).to eq [{"mode" => "rashly"}, %w[command]] - end - - it "still passes everything after -- to command" do - expect(my_script.start(%w[exec -- --verbose])).to eq [{}, %w[--verbose]] - end - - it "does not affect ordinary commands" do - expect(my_script.start(%w[boring command --verbose])).to eq [{"verbose" => true}, %w[command]] - end - - context "when provided with multiple command names" do - klass = Class.new(Thor) do - stop_on_unknown_option! :foo, :bar - end - it "affects all specified commands" do - expect(klass.stop_on_unknown_option?(double(:name => "foo"))).to be true - expect(klass.stop_on_unknown_option?(double(:name => "bar"))).to be true - expect(klass.stop_on_unknown_option?(double(:name => "baz"))).to be false - end - end - - context "when invoked several times" do - klass = Class.new(Thor) do - stop_on_unknown_option! :foo - stop_on_unknown_option! :bar - end - it "affects all specified commands" do - expect(klass.stop_on_unknown_option?(double(:name => "foo"))).to be true - expect(klass.stop_on_unknown_option?(double(:name => "bar"))).to be true - expect(klass.stop_on_unknown_option?(double(:name => "baz"))).to be false - end - end - - it "doesn't break new" do - expect(my_script.new).to be_a(Thor) - end - end - - describe "#map" do - it "calls the alias of a method if one is provided" do - expect(MyScript.start(%w[-T fish])).to eq(%w[fish]) - end - - it "calls the alias of a method if several are provided via #map" do - expect(MyScript.start(%w[-f fish])).to eq(["fish", {}]) - expect(MyScript.start(%w[--foo fish])).to eq(["fish", {}]) - end - - it "inherits all mappings from parent" do - expect(MyChildScript.default_command).to eq("example_default_command") - end - end - - describe "#package_name" do - it "provides a proper description for a command when the package_name is assigned" do - content = capture(:stdout) { PackageNameScript.start(%w[help]) } - expect(content).to match(/Baboon commands:/m) - end - - # TODO: remove this, might be redundant, just wanted to prove full coverage - it "provides a proper description for a command when the package_name is NOT assigned" do - content = capture(:stdout) { MyScript.start(%w[help]) } - expect(content).to match(/Commands:/m) - end - end - - describe "#desc" do - it "provides description for a command" do - content = capture(:stdout) { MyScript.start(%w[help]) } - expect(content).to match(/thor my_script:zoo\s+# zoo around/m) - end - - it "provides no namespace if $thor_runner is false" do - begin - $thor_runner = false - content = capture(:stdout) { MyScript.start(%w[help]) } - expect(content).to match(/thor zoo\s+# zoo around/m) - ensure - $thor_runner = true - end - end - - describe "when :for is supplied" do - it "overwrites a previous defined command" do - expect(capture(:stdout) { MyChildScript.start(%w[help]) }).to match(/animal KIND \s+# fish around/m) - end - end - - describe "when :hide is supplied" do - it "does not show the command in help" do - expect(capture(:stdout) { MyScript.start(%w[help]) }).not_to match(/this is hidden/m) - end - - it "but the command is still invokable, does not show the command in help" do - expect(MyScript.start(%w[hidden yesyes])).to eq(%w[yesyes]) - end - end - end - - describe "#method_options" do - it "sets default options if called before an initializer" do - options = MyChildScript.class_options - expect(options[:force].type).to eq(:boolean) - expect(options[:param].type).to eq(:numeric) - end - - it "overwrites default options if called on the method scope" do - args = %w[zoo --force --param feathers] - options = MyChildScript.start(args) - expect(options).to eq("force" => true, "param" => "feathers") - end - - it "allows default options to be merged with method options" do - args = %w[animal bird --force --param 1.0 --other tweets] - arg, options = MyChildScript.start(args) - expect(arg).to eq("bird") - expect(options).to eq("force" => true, "param" => 1.0, "other" => "tweets") - end - end - - describe "#start" do - it "calls a no-param method when no params are passed" do - expect(MyScript.start(%w[zoo])).to eq(true) - end - - it "calls a single-param method when a single param is passed" do - expect(MyScript.start(%w[animal fish])).to eq(%w[fish]) - end - - it "does not set options in attributes" do - expect(MyScript.start(%w[with_optional --all])).to eq([nil, {"all" => true}, []]) - end - - it "raises an error if the wrong number of params are provided" do - arity_asserter = lambda do |args, msg| - stderr = capture(:stderr) { Scripts::Arities.start(args) } - expect(stderr.strip).to eq(msg) - end - arity_asserter.call %w[zero_args one], %Q(ERROR: "thor zero_args" was called with arguments ["one"] -Usage: "thor scripts:arities:zero_args") - arity_asserter.call %w[one_arg], %Q(ERROR: "thor one_arg" was called with no arguments -Usage: "thor scripts:arities:one_arg ARG") - arity_asserter.call %w[one_arg one two], %Q(ERROR: "thor one_arg" was called with arguments ["one", "two"] -Usage: "thor scripts:arities:one_arg ARG") - arity_asserter.call %w[one_arg one two], %Q(ERROR: "thor one_arg" was called with arguments ["one", "two"] -Usage: "thor scripts:arities:one_arg ARG") - arity_asserter.call %w[two_args one], %Q(ERROR: "thor two_args" was called with arguments ["one"] -Usage: "thor scripts:arities:two_args ARG1 ARG2") - arity_asserter.call %w[optional_arg one two], %Q(ERROR: "thor optional_arg" was called with arguments ["one", "two"] -Usage: "thor scripts:arities:optional_arg [ARG]") - end - - it "raises an error if the invoked command does not exist" do - expect(capture(:stderr) { Amazing.start(%w[animal]) }.strip).to eq('Could not find command "animal" in "amazing" namespace.') - end - - it "calls method_missing if an unknown method is passed in" do - expect(MyScript.start(%w[unk hello])).to eq([:unk, %w[hello]]) - end - - it "does not call a private method no matter what" do - expect(capture(:stderr) { MyScript.start(%w[what]) }.strip).to eq('Could not find command "what" in "my_script" namespace.') - end - - it "uses command default options" do - options = MyChildScript.start(%w[animal fish]).last - expect(options).to eq("other" => "method default") - end - - it "raises when an exception happens within the command call" do - expect { MyScript.start(%w[call_myself_with_wrong_arity]) }.to raise_error(ArgumentError) - end - - context "when the user enters an unambiguous substring of a command" do - it "invokes a command" do - expect(MyScript.start(%w[z])).to eq(MyScript.start(%w[zoo])) - end - - it "invokes a command, even when there's an alias it resolves to the same command" do - expect(MyScript.start(%w[hi arg])).to eq(MyScript.start(%w[hidden arg])) - end - - it "invokes an alias" do - expect(MyScript.start(%w[animal_pri])).to eq(MyScript.start(%w[zoo])) - end - end - - context "when the user enters an ambiguous substring of a command" do - it "raises an exception and displays a message that explains the ambiguity" do - shell = Thor::Base.shell.new - expect(shell).to receive(:error).with("Ambiguous command call matches [call_myself_with_wrong_arity, call_unexistent_method]") - MyScript.start(%w[call], :shell => shell) - end - - it "raises an exception when there is an alias" do - shell = Thor::Base.shell.new - expect(shell).to receive(:error).with("Ambiguous command f matches [foo, fu]") - MyScript.start(%w[f], :shell => shell) - end - end - - end - - describe "#help" do - def shell - @shell ||= Thor::Base.shell.new - end - - describe "on general" do - before do - @content = capture(:stdout) { MyScript.help(shell) } - end - - it "provides useful help info for the help method itself" do - expect(@content).to match(/help \[COMMAND\]\s+# Describe available commands/) - end - - it "provides useful help info for a method with params" do - expect(@content).to match(/animal TYPE\s+# horse around/) - end - - it "uses the maximum terminal size to show commands" do - expect(@shell).to receive(:terminal_width).and_return(80) - content = capture(:stdout) { MyScript.help(shell) } - expect(content).to match(/aaa\.\.\.$/) - end - - it "provides description for commands from classes in the same namespace" do - expect(@content).to match(/baz\s+# do some bazing/) - end - - it "shows superclass commands" do - content = capture(:stdout) { MyChildScript.help(shell) } - expect(content).to match(/foo BAR \s+# do some fooing/) - end - - it "shows class options information" do - content = capture(:stdout) { MyChildScript.help(shell) } - expect(content).to match(/Options\:/) - expect(content).to match(/\[\-\-param=N\]/) - end - - it "injects class arguments into default usage" do - content = capture(:stdout) { Scripts::MyScript.help(shell) } - expect(content).to match(/zoo ACCESSOR \-\-param\=PARAM/) - end - end - - describe "for a specific command" do - it "provides full help info when talking about a specific command" do - expect(capture(:stdout) { MyScript.command_help(shell, "foo") }).to eq(<<-END) -Usage: - thor my_script:foo BAR - -Options: - [--force] # Force to do some fooing - -do some fooing - This is more info! - Everyone likes more info! -END - end - - it "raises an error if the command can't be found" do - expect do - MyScript.command_help(shell, "unknown") - end.to raise_error(Thor::UndefinedCommandError, 'Could not find command "unknown" in "my_script" namespace.') - end - - it "normalizes names before claiming they don't exist" do - expect(capture(:stdout) { MyScript.command_help(shell, "name-with-dashes") }).to match(/thor my_script:name-with-dashes/) - end - - it "uses the long description if it exists" do - expect(capture(:stdout) { MyScript.command_help(shell, "long_description") }).to eq(<<-HELP) -Usage: - thor my_script:long_description - -Description: - This is a really really really long description. Here you go. So very long. - - It even has two paragraphs. -HELP - end - - it "doesn't assign the long description to the next command without one" do - expect(capture(:stdout) do - MyScript.command_help(shell, "name_with_dashes") - end).not_to match(/so very long/i) - end - end - - describe "instance method" do - it "calls the class method" do - expect(capture(:stdout) { MyScript.start(%w[help]) }).to match(/Commands:/) - end - - it "calls the class method" do - expect(capture(:stdout) { MyScript.start(%w[help foo]) }).to match(/Usage:/) - end - end - end - - describe "when creating commands" do - it "prints a warning if a public method is created without description or usage" do - expect(capture(:stdout) do - klass = Class.new(Thor) - klass.class_eval "def hello_from_thor; end" - end).to match(/\[WARNING\] Attempted to create command "hello_from_thor" without usage or description/) - end - - it "does not print if overwriting a previous command" do - expect(capture(:stdout) do - klass = Class.new(Thor) - klass.class_eval "def help; end" - end).to be_empty - end - end - - describe "edge-cases" do - it "can handle boolean options followed by arguments" do - klass = Class.new(Thor) do - method_option :loud, :type => :boolean - desc "hi NAME", "say hi to name" - def hi(name) - name.upcase! if options[:loud] - "Hi #{name}" - end - end - - expect(klass.start(%w[hi jose])).to eq("Hi jose") - expect(klass.start(%w[hi jose --loud])).to eq("Hi JOSE") - expect(klass.start(%w[hi --loud jose])).to eq("Hi JOSE") - end - - it "passes through unknown options" do - klass = Class.new(Thor) do - desc "unknown", "passing unknown options" - def unknown(*args) - args - end - end - - expect(klass.start(%w[unknown foo --bar baz bat --bam])).to eq(%w[foo --bar baz bat --bam]) - expect(klass.start(%w[unknown --bar baz])).to eq(%w[--bar baz]) - end - - it "does not pass through unknown options with strict args" do - klass = Class.new(Thor) do - strict_args_position! - - desc "unknown", "passing unknown options" - def unknown(*args) - args - end - end - - expect(klass.start(%w[unknown --bar baz])).to eq([]) - expect(klass.start(%w[unknown foo --bar baz])).to eq(%w[foo]) - end - - it "strict args works in the inheritance chain" do - parent = Class.new(Thor) do - strict_args_position! - end - - klass = Class.new(parent) do - desc "unknown", "passing unknown options" - def unknown(*args) - args - end - end - - expect(klass.start(%w[unknown --bar baz])).to eq([]) - expect(klass.start(%w[unknown foo --bar baz])).to eq(%w[foo]) - end - - it "send as a command name" do - expect(MyScript.start(%w[send])).to eq(true) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/util_spec.rb b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/util_spec.rb deleted file mode 100644 index 9fe213c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/spec/util_spec.rb +++ /dev/null @@ -1,196 +0,0 @@ -require "helper" - -module Thor::Util - def self.clear_user_home! - @@user_home = nil - end -end - -describe Thor::Util do - describe "#find_by_namespace" do - it "returns 'default' if no namespace is given" do - expect(Thor::Util.find_by_namespace("")).to eq(Scripts::MyDefaults) - end - - it "adds 'default' if namespace starts with :" do - expect(Thor::Util.find_by_namespace(":child")).to eq(Scripts::ChildDefault) - end - - it "returns nil if the namespace can't be found" do - expect(Thor::Util.find_by_namespace("thor:core_ext:ordered_hash")).to be nil - end - - it "returns a class if it matches the namespace" do - expect(Thor::Util.find_by_namespace("app:broken:counter")).to eq(BrokenCounter) - end - - it "matches classes default namespace" do - expect(Thor::Util.find_by_namespace("scripts:my_script")).to eq(Scripts::MyScript) - end - end - - describe "#namespace_from_thor_class" do - it "replaces constant nesting with command namespacing" do - expect(Thor::Util.namespace_from_thor_class("Foo::Bar::Baz")).to eq("foo:bar:baz") - end - - it "snake-cases component strings" do - expect(Thor::Util.namespace_from_thor_class("FooBar::BarBaz::BazBoom")).to eq("foo_bar:bar_baz:baz_boom") - end - - it "accepts class and module objects" do - expect(Thor::Util.namespace_from_thor_class(Thor::CoreExt::OrderedHash)).to eq("thor:core_ext:ordered_hash") - expect(Thor::Util.namespace_from_thor_class(Thor::Util)).to eq("thor:util") - end - - it "removes Thor::Sandbox namespace" do - expect(Thor::Util.namespace_from_thor_class("Thor::Sandbox::Package")).to eq("package") - end - end - - describe "#namespaces_in_content" do - it "returns an array of names of constants defined in the string" do - list = Thor::Util.namespaces_in_content("class Foo; class Bar < Thor; end; end; class Baz; class Bat; end; end") - expect(list).to include("foo:bar") - expect(list).not_to include("bar:bat") - end - - it "doesn't put the newly-defined constants in the enclosing namespace" do - Thor::Util.namespaces_in_content("class Blat; end") - expect(defined?(Blat)).not_to be - expect(defined?(Thor::Sandbox::Blat)).to be - end - end - - describe "#snake_case" do - it "preserves no-cap strings" do - expect(Thor::Util.snake_case("foo")).to eq("foo") - expect(Thor::Util.snake_case("foo_bar")).to eq("foo_bar") - end - - it "downcases all-caps strings" do - expect(Thor::Util.snake_case("FOO")).to eq("foo") - expect(Thor::Util.snake_case("FOO_BAR")).to eq("foo_bar") - end - - it "downcases initial-cap strings" do - expect(Thor::Util.snake_case("Foo")).to eq("foo") - end - - it "replaces camel-casing with underscores" do - expect(Thor::Util.snake_case("FooBarBaz")).to eq("foo_bar_baz") - expect(Thor::Util.snake_case("Foo_BarBaz")).to eq("foo_bar_baz") - end - - it "places underscores between multiple capitals" do - expect(Thor::Util.snake_case("ABClass")).to eq("a_b_class") - end - end - - describe "#find_class_and_command_by_namespace" do - it "returns a Thor::Group class if full namespace matches" do - expect(Thor::Util.find_class_and_command_by_namespace("my_counter")).to eq([MyCounter, nil]) - end - - it "returns a Thor class if full namespace matches" do - expect(Thor::Util.find_class_and_command_by_namespace("thor")).to eq([Thor, nil]) - end - - it "returns a Thor class and the command name" do - expect(Thor::Util.find_class_and_command_by_namespace("thor:help")).to eq([Thor, "help"]) - end - - it "falls back in the namespace:command look up even if a full namespace does not match" do - Thor.const_set(:Help, Module.new) - expect(Thor::Util.find_class_and_command_by_namespace("thor:help")).to eq([Thor, "help"]) - Thor.send :remove_const, :Help - end - - it "falls back on the default namespace class if nothing else matches" do - expect(Thor::Util.find_class_and_command_by_namespace("test")).to eq([Scripts::MyDefaults, "test"]) - end - end - - describe "#thor_classes_in" do - it "returns thor classes inside the given class" do - expect(Thor::Util.thor_classes_in(MyScript)).to eq([MyScript::AnotherScript]) - expect(Thor::Util.thor_classes_in(MyScript::AnotherScript)).to be_empty - end - end - - describe "#user_home" do - before do - allow(ENV).to receive(:[]) - Thor::Util.clear_user_home! - end - - it "returns the user path if no variable is set on the environment" do - expect(Thor::Util.user_home).to eq(File.expand_path("~")) - end - - it "returns the *nix system path if file cannot be expanded and separator does not exist" do - expect(File).to receive(:expand_path).with("~").and_raise(RuntimeError) - previous_value = File::ALT_SEPARATOR - capture(:stderr) { File.const_set(:ALT_SEPARATOR, false) } # rubocop:disable SymbolName - expect(Thor::Util.user_home).to eq("/") - capture(:stderr) { File.const_set(:ALT_SEPARATOR, previous_value) } # rubocop:disable SymbolName - end - - it "returns the windows system path if file cannot be expanded and a separator exists" do - expect(File).to receive(:expand_path).with("~").and_raise(RuntimeError) - previous_value = File::ALT_SEPARATOR - capture(:stderr) { File.const_set(:ALT_SEPARATOR, true) } # rubocop:disable SymbolName - expect(Thor::Util.user_home).to eq("C:/") - capture(:stderr) { File.const_set(:ALT_SEPARATOR, previous_value) } # rubocop:disable SymbolName - end - - it "returns HOME/.thor if set" do - allow(ENV).to receive(:[]).with("HOME").and_return("/home/user/") - expect(Thor::Util.user_home).to eq("/home/user/") - end - - it "returns path with HOMEDRIVE and HOMEPATH if set" do - allow(ENV).to receive(:[]).with("HOMEDRIVE").and_return("D:/") - allow(ENV).to receive(:[]).with("HOMEPATH").and_return("Documents and Settings/James") - expect(Thor::Util.user_home).to eq("D:/Documents and Settings/James") - end - - it "returns APPDATA/.thor if set" do - allow(ENV).to receive(:[]).with("APPDATA").and_return("/home/user/") - expect(Thor::Util.user_home).to eq("/home/user/") - end - end - - describe "#thor_root_glob" do - before do - allow(ENV).to receive(:[]) - Thor::Util.clear_user_home! - end - - it "escapes globs in path" do - allow(ENV).to receive(:[]).with("HOME").and_return("/home/user{1}/") - expect(Dir).to receive(:[]).with('/home/user\\{1\\}/.thor/*').and_return([]) - expect(Thor::Util.thor_root_glob).to eq([]) - end - end - - describe "#globs_for" do - it "escapes globs in path" do - expect(Thor::Util.globs_for("/home/apps{1}")).to eq([ - '/home/apps\\{1\\}/Thorfile', - '/home/apps\\{1\\}/*.thor', - '/home/apps\\{1\\}/tasks/*.thor', - '/home/apps\\{1\\}/lib/tasks/*.thor' - ]) - end - end - - describe "#escape_globs" do - it "escapes ? * { } [ ] glob characters" do - expect(Thor::Util.escape_globs("apps?")).to eq('apps\\?') - expect(Thor::Util.escape_globs("apps*")).to eq('apps\\*') - expect(Thor::Util.escape_globs("apps {1}")).to eq('apps \\{1\\}') - expect(Thor::Util.escape_globs("apps [1]")).to eq('apps \\[1\\]') - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/thor.gemspec b/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/thor.gemspec deleted file mode 100644 index 74fe55a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/thor-0.19.1/thor.gemspec +++ /dev/null @@ -1,24 +0,0 @@ -# coding: utf-8 -lib = File.expand_path("../lib/", __FILE__) -$LOAD_PATH.unshift lib unless $LOAD_PATH.include?(lib) -require "thor/version" - -Gem::Specification.new do |spec| - spec.add_development_dependency "bundler", "~> 1.0" - spec.authors = ["Yehuda Katz", "José Valim"] - spec.description = %q(Thor is a toolkit for building powerful command-line interfaces.) - spec.email = "ruby-thor@googlegroups.com" - spec.executables = %w[thor] - spec.files = %w[.document CHANGELOG.md LICENSE.md README.md Thorfile thor.gemspec] - spec.files += Dir.glob("bin/**/*") - spec.files += Dir.glob("lib/**/*.rb") - spec.files += Dir.glob("spec/**/*") - spec.homepage = "http://whatisthor.com/" - spec.licenses = %w[MIT] - spec.name = "thor" - spec.require_paths = %w[lib] - spec.required_rubygems_version = ">= 1.3.5" - spec.summary = spec.description - spec.test_files = Dir.glob("spec/**/*") - spec.version = Thor::VERSION -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/CHANGELOG.md b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/CHANGELOG.md deleted file mode 100644 index 23f3fdb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/CHANGELOG.md +++ /dev/null @@ -1,44 +0,0 @@ -## master - -## 1.4.1 (2013-05-08) - -* Support Arrays in pre/postambles (#193, jbwiv) - -## 1.4.0 (2013-05-01) - -* Better encoding support - -## 1.3.7 (2013-04-09) - -* Erubis: Check for the correct constant (#183, mattwildig) -* Don't fail when BasicObject is defined in 1.8 (#182, technobrat, judofyr) - -## 1.3.6 (2013-03-17) - -* Accept Hash that implements #path as options (#180, lawso017) -* Changed extension for CsvTemplate from '.csv' to '.rcsv' (#177, alexgb) - -## 1.3.5 (2013-03-06) - -* Fixed extension for PlainTemplate (judofyr) -* Improved local variables regexp (#174, razorinc) -* Added CHANGELOG.md - -## 1.3.4 (2013-02-28) - -* Support RDoc 4.0 (#168, judofyr) -* Add mention of Org-Mode support (#165, aslakknutsen) -* Add AsciiDoctorTemplate (#163, #164, aslakknutsen) -* Add PlainTextTemplate (nathanaeljones) -* Restrict locals to valid variable names (#158, thinkerbot) -* ERB: Improve trim mode support (#156, ssimeonov) -* Add CSVTemplate (#153, alexgb) -* Remove special case for 1.9.1 (#147, guilleiguaran) -* Add allows\_script? method to Template (#143, bhollis) -* Default to using Redcarpet2 (#139, DAddYE) -* Allow File/Tempfile as filenames (#134, jamesotron) -* Add EtanniTemplate (#131, manveru) -* Support RDoc 3.10 (#112, timfel) -* Always compile templates; remove old source evaluator (rtomayko) -* Less: Options are now being passed to the parser (#106, cowboyd) - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/COPYING b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/COPYING deleted file mode 100644 index 2f99dc1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/COPYING +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2010 Ryan Tomayko - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL -THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/Gemfile b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/Gemfile deleted file mode 100644 index dd73064..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/Gemfile +++ /dev/null @@ -1,32 +0,0 @@ -source "http://rubygems.org" - -gem 'rake' -gem 'asciidoctor', '>= 0.1.0' -gem 'builder' -gem 'coffee-script' -gem 'contest' -gem 'creole' -gem 'erubis' -gem 'haml', '>= 2.2.11', '< 4' -gem 'kramdown' -gem 'less' -gem 'liquid' -gem 'markaby' -gem 'maruku' -gem 'nokogiri' -gem 'radius' -gem 'sass' -gem 'wikicloth' -gem 'rdoc', (ENV['RDOC_VERSION'] || '> 0') - -platform :ruby do - gem 'yajl-ruby' - gem 'redcarpet' - gem 'rdiscount' if RUBY_VERSION != '1.9.2' - gem 'RedCloth' -end - -platform :mri do - gem 'therubyracer' - gem 'bluecloth' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/HACKING b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/HACKING deleted file mode 100644 index 46e35f6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/HACKING +++ /dev/null @@ -1,16 +0,0 @@ -Clone: - - git clone git://github.com/rtomayko/tilt.git - cd tilt - -Install needed packages under ./vendor and run tests (requires bundler): - - rake - -Run tests under your current gem environment. Do not install anything: - - rake test - -Only install needed packages under ./vendor: - - rake setup diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/README.md b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/README.md deleted file mode 100644 index 19a89ac..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/README.md +++ /dev/null @@ -1,232 +0,0 @@ -Tilt [![Build Status](https://secure.travis-ci.org/rtomayko/tilt.png)](http://travis-ci.org/rtomayko/tilt) [![Dependency Status](https://gemnasium.com/rtomayko/tilt.png)](https://gemnasium.com/rtomayko/tilt) -==== - -Tilt is a thin interface over a bunch of different Ruby template engines in -an attempt to make their usage as generic possible. This is useful for web -frameworks, static site generators, and other systems that support multiple -template engines but don't want to code for each of them individually. - -The following features are supported for all template engines (assuming the -feature is relevant to the engine): - - * Custom template evaluation scopes / bindings - * Ability to pass locals to template evaluation - * Support for passing a block to template evaluation for "yield" - * Backtraces with correct filenames and line numbers - * Template file caching and reloading - * Fast, method-based template source compilation - -The primary goal is to get all of the things listed above right for all -template engines included in the distribution. - -Support for these template engines is included with the package: - - ENGINE FILE EXTENSIONS REQUIRED LIBRARIES - -------------------------- ----------------------- ---------------------------- - Asciidoctor .ad, .adoc, .asciidoc asciidoctor (>= 0.1.0) - ERB .erb, .rhtml none (included ruby stdlib) - Interpolated String .str none (included ruby core) - Erubis .erb, .rhtml, .erubis erubis - Haml .haml haml - Sass .sass haml (< 3.1) or sass (>= 3.1) - Scss .scss haml (< 3.1) or sass (>= 3.1) - Less CSS .less less - Builder .builder builder - Liquid .liquid liquid - RDiscount .markdown, .mkd, .md rdiscount - Redcarpet .markdown, .mkd, .md redcarpet - BlueCloth .markdown, .mkd, .md bluecloth - Kramdown .markdown, .mkd, .md kramdown - Maruku .markdown, .mkd, .md maruku - RedCloth .textile redcloth - RDoc .rdoc rdoc - Radius .radius radius - Markaby .mab markaby - Nokogiri .nokogiri nokogiri - CoffeeScript .coffee coffee-script (+ javascript) - Creole (Wiki markup) .wiki, .creole creole - WikiCloth (Wiki markup) .wiki, .mediawiki, .mw wikicloth - Yajl .yajl yajl-ruby - CSV .rcsv none (Ruby >= 1.9), fastercsv (Ruby < 1.9) - -These template engines ship with their own Tilt integration: - - ENGINE FILE EXTENSIONS REQUIRED LIBRARIES - -------------------------- ----------------- ---------------------------- - Slim .slim slim (>= 0.7) - Embedded JavaScript sprockets - Embedded CoffeeScript sprockets - JST sprockets - Org-mode .org org-ruby (>= 0.6.2) - -See [TEMPLATES.md][t] for detailed information on template engine -options and supported features. - -[t]: http://github.com/rtomayko/tilt/blob/master/TEMPLATES.md - "Tilt Template Engine Documentation" - -Basic Usage ------------ - -Instant gratification: - - require 'erb' - require 'tilt' - template = Tilt.new('templates/foo.erb') - => # - output = template.render - => "Hello world!" - -It's recommended that calling programs explicitly require template engine -libraries (like 'erb' above) at load time. Tilt attempts to lazy require the -template engine library the first time a template is created but this is -prone to error in threaded environments. - -The `Tilt` module contains generic implementation classes for all supported -template engines. Each template class adheres to the same interface for -creation and rendering. In the instant gratification example, we let Tilt -determine the template implementation class based on the filename, but -`Tilt::Template` implementations can also be used directly: - - template = Tilt::HamlTemplate.new('templates/foo.haml') - output = template.render - -The `render` method takes an optional evaluation scope and locals hash -arguments. Here, the template is evaluated within the context of the -`Person` object with locals `x` and `y`: - - template = Tilt::ERBTemplate.new('templates/foo.erb') - joe = Person.find('joe') - output = template.render(joe, :x => 35, :y => 42) - -If no scope is provided, the template is evaluated within the context of an -object created with `Object.new`. - -A single `Template` instance's `render` method may be called multiple times -with different scope and locals arguments. Continuing the previous example, -we render the same compiled template but this time in jane's scope: - - jane = Person.find('jane') - output = template.render(jane, :x => 22, :y => nil) - -Blocks can be passed to `render` for templates that support running -arbitrary ruby code (usually with some form of `yield`). For instance, -assuming the following in `foo.erb`: - - Hey <%= yield %>! - -The block passed to `render` is called on `yield`: - - template = Tilt::ERBTemplate.new('foo.erb') - template.render { 'Joe' } - # => "Hey Joe!" - -Template Mappings ------------------ - -The `Tilt` module includes methods for associating template implementation -classes with filename patterns and for locating/instantiating template -classes based on those associations. - -The `Tilt::register` method associates a filename pattern with a specific -template implementation. To use ERB for files ending in a `.bar` extension: - - >> Tilt.register Tilt::ERBTemplate, 'bar' - >> Tilt.new('views/foo.bar') - => # - -Retrieving the template class for a file or file extension: - - >> Tilt['foo.bar'] - => Tilt::ERBTemplate - >> Tilt['haml'] - => Tilt::HamlTemplate - -It's also possible to register template file mappings that are more specific -than a file extension. To use Erubis for `bar.erb` but ERB for all other `.erb` -files: - - >> Tilt.register Tilt::ErubisTemplate, 'bar.erb' - >> Tilt.new('views/foo.erb') - => Tilt::ERBTemplate - >> Tilt.new('views/bar.erb') - => Tilt::ErubisTemplate - -The template class is determined by searching for a series of decreasingly -specific name patterns. When creating a new template with -`Tilt.new('views/foo.html.erb')`, we check for the following template -mappings: - - 1. `views/foo.html.erb` - 2. `foo.html.erb` - 3. `html.erb` - 4. `erb` - -### Fallback mode - -If there are more than one template class registered for a file extension, Tilt -will automatically try to load the version that works on your machine: - - 1. If any of the template engines has been loaded already: Use that one. - 2. If not, it will try to initialize each of the classes with an empty template. - 3. Tilt will use the first that doesn't raise an exception. - 4. If however *all* of them failed, Tilt will raise the exception of the first - template engine, since that was the most preferred one. - -Template classes that were registered *last* would be tried first. Because the -Markdown extensions are registered like this: - - Tilt.register Tilt::BlueClothTemplate, 'md' - Tilt.register Tilt::RDiscountTemplate, 'md' - -Tilt will first try RDiscount and then BlueCloth. You could say that RDiscount -has a *higher priority* than BlueCloth. - -The fallback mode works nicely when you just need to render an ERB or Markdown -template, but if you depend on a specific implementation, you should use #prefer: - - # Prefer BlueCloth for all its registered extensions (markdown, mkd, md) - Tilt.prefer Tilt::BlueClothTemplate - - # Prefer Erubis for .erb only: - Tilt.prefer Tilt::ErubisTemplate, 'erb' - -When a file extension has a preferred template class, Tilt will *always* use -that class, even if it raises an exception. - -Encodings ---------- - -Tilt needs to know the encoding of the template in order to work properly: - -Tilt will use `Encoding.default_external` as the encoding when reading external -files. If you're mostly working with one encoding (e.g. UTF-8) we *highly* -recommend setting this option. When providing a custom reader block (`Tilt.new -{ custom_string }`) you'll have ensure the string is properly encoded yourself. - -Most of the template engines in Tilt also allows you to override the encoding -using the `:default_encoding`-option: - -```ruby -tmpl = Tilt.new('hello.erb', :default_encoding => 'Big5') -``` - -Ultimately it's up to the template engine how to handle the encoding: It might -respect `:default_encoding`, it might always assume it's UTF-8 (like -CoffeScript), or it can do its own encoding detection. - -Template Compilation --------------------- - -Tilt compiles generated Ruby source code produced by template engines and reuses -it on subsequent template invocations. Benchmarks show this yields a 5x-10x -performance increase over evaluating the Ruby source on each invocation. - -Template compilation is currently supported for these template engines: -StringTemplate, ERB, Erubis, Haml, Nokogiri, Builder and Yajl. - -LICENSE -------- - -Tilt is Copyright (c) 2010 [Ryan Tomayko](http://tomayko.com/about) and -distributed under the MIT license. See the `COPYING` file for more info. diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/Rakefile b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/Rakefile deleted file mode 100644 index 4228b1b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/Rakefile +++ /dev/null @@ -1,104 +0,0 @@ -require 'rbconfig' -require 'rake/testtask' -task :default => [:setup, :test] - -# set GEM_HOME to use local ./vendor dir for tests -vendor_dir = './vendor' -ruby_version = RbConfig::CONFIG['ruby_version'] -ruby_engine = (defined?(RUBY_ENGINE) && RUBY_ENGINE) || 'ruby' -gem_home = ENV['GEM_HOME'] = "#{vendor_dir}/#{ruby_engine}/#{ruby_version}" - -# Write the current version. -task :version do - puts "#{ruby_engine} #{RUBY_VERSION} (#{gem_home})" -end - -desc "Install gems to #{ENV['GEM_HOME']}" -task :setup do - verbose false do - sh " - bundle check >/dev/null || { - echo 'Updating #{gem_home}' && - bundle install --path='#{vendor_dir}'; } - " - end -end - -# SPECS ===================================================================== - -desc 'Generate test coverage report' -task :rcov do - sh "rcov -Ilib:test test/*_test.rb" -end - -desc 'Run tests (default)' -Rake::TestTask.new(:test) do |t| - t.test_files = FileList['test/*_test.rb'] - t.ruby_opts = ['-Itest'] - t.ruby_opts << '-rubygems' if defined? Gem -end -task :test => :version - -# PACKAGING ================================================================= - -begin - require 'rubygems' -rescue LoadError -end - -if defined?(Gem) - SPEC = eval(File.read('tilt.gemspec')) - - def package(ext='') - "pkg/tilt-#{SPEC.version}" + ext - end - - desc 'Build packages' - task :package => %w[.gem .tar.gz].map {|e| package(e)} - - desc 'Build and install as local gem' - task :install => package('.gem') do - sh "gem install #{package('.gem')}" - end - - directory 'pkg/' - - file package('.gem') => %w[pkg/ tilt.gemspec] + SPEC.files do |f| - sh "gem build tilt.gemspec" - mv File.basename(f.name), f.name - end - - file package('.tar.gz') => %w[pkg/] + SPEC.files do |f| - sh "git archive --format=tar HEAD | gzip > #{f.name}" - end - - desc 'Upload gem and tar.gz distributables to rubyforge' - task :release => [package('.gem'), package('.tar.gz')] do |t| - sh <<-SH - rubyforge add_release sinatra tilt #{SPEC.version} #{package('.gem')} && - rubyforge add_file sinatra tilt #{SPEC.version} #{package('.tar.gz')} - SH - end -end - -# GEMSPEC =================================================================== - -file 'tilt.gemspec' => FileList['{lib,test}/**','Rakefile'] do |f| - # read version from tilt.rb - version = File.read('lib/tilt.rb')[/VERSION = '(.*)'/] && $1 - # read spec file and split out manifest section - spec = File. - read(f.name). - sub(/s\.version\s*=\s*'.*'/, "s.version = '#{version}'") - parts = spec.split(" # = MANIFEST =\n") - # determine file list from git ls-files - files = `git ls-files`. - split("\n").sort.reject{ |file| file =~ /^\./ }. - map{ |file| " #{file}" }.join("\n") - # piece file back together and write... - parts[1] = " s.files = %w[\n#{files}\n ]\n" - spec = parts.join(" # = MANIFEST =\n") - spec.sub!(/s.date = '.*'/, "s.date = '#{Time.now.strftime("%Y-%m-%d")}'") - File.open(f.name, 'w') { |io| io.write(spec) } - puts "updated #{f.name}" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/TEMPLATES.md b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/TEMPLATES.md deleted file mode 100644 index ac5b583..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/TEMPLATES.md +++ /dev/null @@ -1,516 +0,0 @@ -Tilt Templates -============== - -(See for a rendered, -HTML-version of this file). - -While all Tilt templates use the same basic interface for template loading and -evaluation, each varies in its capabilities and available options. Detailed -documentation on each supported template engine is provided below. - -There are also some file extensions that have several implementations -(currently ERB and Markdown). These template classes have certain features -which are guaranteed to work across all the implementations. If you wish to be -compatible with all of these template classes, you should only depend on the -cross-implementation features. - - * [ERB](#erb) - Generic ERB implementation (backed by erb.rb or Erubis) - * [erb.rb](#erbrb) - `Tilt::ERBTemplate` - * [Erubis](#erubis) - `Tilt::ErubisTemplate` - * [Haml](#haml) - `Tilt::HamlTemplate` - * [Liquid](#liquid) - `Tilt::LiquidTemplate` - * Nokogiri - `Tilt::NokogiriTemplate` - * Builder - `Tilt::BuilderTemplate` - * Markaby - `Tilt::MarkabyTemplate` - * [Radius](#radius) - `Tilt::RadiusTemplate` - -Tilt also includes support for CSS processors like [LessCSS][lesscss] and -[Sass][sass], [CoffeeScript][coffee-script] and some simple text formats. - - * Less - `Tilt::LessTemplate` - * Sass - `Tilt::SassTemplate` - * Scss - `Tilt::ScssTemplate` - * CoffeeScript - `Tilt::CoffeeScriptTemplate` - * [Textile](#redcloth) - `Tilt::RedClothTemplate` - * Creole - `Tilt::CreoleTemplate` - * [RDoc](#rdoc) - `Tilt::RDocTemplate` - -Tilt has extensive support for Markdown, backed by one of four different -implementations (depending on which are available on your system): - - * [Markdown](#markdown) - Generic Markdown implementation - * [RDiscount](#rdiscount) - `Tilt::RDiscountTemplate` - * Redcarpet - `Tilt::RedcarpetTemplate` - * BlueCloth - `Tilt::BlueClothTemplate` - * Kramdown - `Tilt::KramdownTemplate` - * Maruku - `Tilt::MarukuTemplate` - - -ERB (`erb`, `rhtml`) --------------------- - -ERB is a simple but powerful template languge for Ruby. In Tilt it's backed by -[Erubis](#erubis) (if installed on your system) or by [erb.rb](#erbrb) (which -is included in Ruby's standard library). This documentation applies to both -implementations. - -### Example - - Hello <%= world %>! - -### Usage - -ERB templates support custom evaluation scopes and locals: - - >> require 'erb' - >> template = Tilt.new('hello.html.erb') - >> template.render(self, :world => 'World!') - => "Hello World!" - -Or, use `Tilt['erb']` directly to process strings: - - template = Tilt['erb'].new { "Hello <%= world %>!" } - template.render(self, :world => 'World!') - -### Options - -#### `:trim => trim` - -Omits newlines and spaces around certain lines (usually those that starts with -`<%` and ends with `%>`). There isn't a specification for how trimming in ERB -should work, so if you need more control over the whitespace, you should use -[erb.rb](#erbrb) or [Erubis](#erubis) directly. - - -#### `:outvar => '_erbout'` - -The name of the variable used to accumulate template output. This can be -any valid Ruby expression but must be assignable. By default a local -variable named `_erbout` is used. - - -erb.rb (`erb`, `rhtml`) ------------------------ - -[ERB](#erb) implementation available in Ruby's standard library. - -All the documentation of [ERB](#erb) applies in addition to the following: - -### Usage - -The `Tilt::ERBTemplate` class is registered for all files ending in `.erb` or -`.rhtml` by default, but with a *lower* priority than ErubisTemplate. If you -specifically want to use ERB, it's recommended to use `#prefer`: - - Tilt.prefer Tilt::ERBTemplate - -__NOTE:__ It's suggested that your program `require 'erb'` at load time when -using this template engine within a threaded environment. - -### Options - -#### `:trim => true` - -The ERB trim mode flags. This is a string consisting of any combination of the -following characters: - - * `'>'` omits newlines for lines ending in `>` - * `'<>'` omits newlines for lines starting with `<%` and ending in `%>` - * `'%'` enables processing of lines beginning with `%` - * `true` is an alias of `<>` - -#### `:safe => nil` - -The `$SAFE` level; when set, ERB code will be run in a -separate thread with `$SAFE` set to the provided level. - -#### `:outvar => '_erbout'` - -The name of the variable used to accumulate template output. This can be -any valid Ruby expression but must be assignable. By default a local -variable named `_erbout` is used. - -### See also - - * [ERB documentation](http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html) - - - -Erubis (`erb`, `rhtml`, `erubis`) ---------------------------------- - -[Erubis][erubis] is a fast, secure, and very extensible implementation of [ERB](#erb). - -All the documentation of [ERB](#erb) applies in addition to the following: - -### Usage - -The `Tilt::ErubisTemplate` class is registered for all files ending in `.erb` or -`.rhtml` by default, but with a *higher* priority than `ERBTemplate`. If you -specifically want to use Erubis, it's recommended to use `#prefer`: - - Tilt.prefer Tilt::ErubisTemplate - -__NOTE:__ It's suggested that your program `require 'erubis'` at load time when -using this template engine within a threaded environment. - -### Options - -#### `:engine_class => Erubis::Eruby` - -Allows you to specify a custom engine class to use instead of the -default which is `Erubis::Eruby`. - -#### `:escape_html => false` - -When `true`, `Erubis::EscapedEruby` will be used as the engine class -instead of the default. All content within `<%= %>` blocks will be -automatically html escaped. - -#### `:outvar => '_erbout'` - -The name of the variable used to accumulate template output. This can be -any valid Ruby expression but must be assignable. By default a local -variable named `_erbout` is used. - -#### `:pattern => '<% %>'` - -Set pattern for embedded Ruby code. - -#### `:trim => true` - -Delete spaces around `<% %>`. (But, spaces around `<%= %>` are preserved.) - -### See also - - * [Erubis Home][erubis] - * [Erubis User's Guide](http://www.kuwata-lab.com/erubis/users-guide.html) - - - -Haml (`haml`) -------------- - -[Haml][haml] is a markup language that’s used to cleanly and simply describe -the HTML of any web document without the use of inline code. Haml functions as -a replacement for inline page templating systems such as PHP, ASP, and ERB, the -templating language used in most Ruby on Rails applications. However, Haml -avoids the need for explicitly coding HTML into the template, because it itself -is a description of the HTML, with some code to generate dynamic content. -([more](http://haml.info/about.html)) - - -### Example - - %html - %head - %title= @title - %body - %h1 - Hello - = world + '!' - -### Usage - -The `Tilt::HamlTemplate` class is registered for all files ending in `.haml` -by default. Haml templates support custom evaluation scopes and locals: - - >> require 'haml' - >> template = Tilt.new('hello.haml') - => # - >> @title = "Hello Haml!" - >> template.render(self, :world => 'Haml!') - => " - - - Hello Haml! - - -

Hello Haml!

- - " - -Or, use the `Tilt::HamlTemplate` class directly to process strings: - - >> require 'haml' - >> template = Tilt::HamlTemplate.new { "%h1= 'Hello Haml!'" } - => # - >> template.render - => "

Hello Haml!

" - -__NOTE:__ It's suggested that your program `require 'haml'` at load time when -using this template engine within a threaded environment. - -### Options - -Please see the [Haml Reference](http://haml.info/docs/yardoc/file.HAML_REFERENCE.html#options) for all available options. - -### See also - - * [#haml.docs](http://haml.info/docs.html) - * [Haml Tutorial](http://haml.info/tutorial.html) - * [Haml Reference](http://haml.info/docs/yardoc/file.HAML_REFERENCE.html) - - - -Liquid (`liquid`) ------------------ - -[Liquid][liquid] is for rendering safe templates which cannot affect the -security of the server they are rendered on. - -### Example - - - - {{ title }} - - -

Hello {{ world }}!

- - - -### Usage - -`Tilt::LiquidTemplate` is registered for all files ending in `.liquid` by -default. Liquid templates support locals and objects that respond to -`#to_h` as scopes: - - >> require 'liquid' - >> require 'tilt' - >> template = Tilt.new('hello.liquid') - => # - >> scope = { :title => "Hello Liquid Templates" } - >> template.render(nil, :world => "Liquid") - => " - - - Hello Liquid Templates - - -

Hello Liquid!

- - " - -Or, use `Tilt::LiquidTemplate` directly to process strings: - - >> require 'liquid' - >> template = Tilt::LiquidTemplate.new { "

Hello Liquid!

" } - => # - >> template.render - => "

Hello Liquid!

" - -__NOTE:__ It's suggested that your program `require 'liquid'` at load -time when using this template engine within a threaded environment. - -### See also - - * [Liquid for Programmers](https://wiki.github.com/Shopify/liquid/liquid-for-programmers) - * [Liquid Docs](http://liquid.rubyforge.org/) - * GitHub: [Shopify/liquid](https://github.com/Shopify/liquid/) - - - -Radius (`radius`) ------------------ - -[Radius][radius] is the template language used by [Radiant CMS][radiant]. It is -a tag language designed to be valid XML/HTML. - -### Example - - - -

-
    - -
  • !
  • -
    -
- - - - -### Usage - -To render a template such as the one above. - - scope = OpenStruct.new - scope.title = "Radius Example" - scope.hello = "Hello, World!" - - require 'radius' - template = Tilt::RadiusTemplate.new('example.radius', :tag_prefix=>'r') - template.render(scope, :type=>'hlist'){ "Jackpot!" } - -The result will be: - - - -

Radius Example

-
    -
  • Hello, World!
  • -
  • Hello, World!
  • -
  • Hello, World!
  • -
- Jackpot! - - - -### See also - - * [Radius][radius] - * [Radiant CMS][radiant] - - - -Textile (`textile`) -------------------- - -Textile is a lightweight markup language originally developed by Dean Allen and -billed as a "humane Web text generator". Textile converts its marked-up text -input to valid, well-formed XHTML and also inserts character entity references -for apostrophes, opening and closing single and double quotation marks, -ellipses and em dashes. - -Textile formatted texts are converted to HTML with the [RedCloth][redcloth] -engine, which is a Ruby extension written in C. - -### Example - - h1. Hello Textile Templates - - Hello World. This is a paragraph. - -### Usage - -__NOTE:__ It's suggested that your program `require 'redcloth'` at load time -when using this template engine in a threaded environment. - -### See Also - - * [RedCloth][redcloth] - - - -RDoc (`rdoc`) -------------- - -[RDoc][rdoc] is the simple text markup system that comes with Ruby's standard -library. - -### Example - - = Hello RDoc Templates - - Hello World. This is a paragraph. - -### Usage - -__NOTE:__ It's suggested that your program `require 'rdoc'`, -`require 'rdoc/markup'`, and `require 'rdoc/markup/to_html'` at load time -when using this template engine in a threaded environment. - -### See also - - * [RDoc][rdoc] - - - -Markdown (`markdown`, `md`, `mkd`) ----------------------------------- - -[Markdown][markdown] is a lightweight markup language, created by John Gruber -and Aaron Swartz. For any markup that is not covered by Markdown’s syntax, HTML -is used. Marking up plain text with Markdown markup is easy and Markdown -formatted texts are readable. - -Markdown formatted texts are converted to HTML with one of these libraries: - - * [RDiscount](#rdiscount) - `Tilt::RDiscountTemplate` - * Redcarpet - `Tilt::RedcarpetTemplate` - * BlueCloth - `Tilt::BlueClothTemplate` - * Kramdown - `Tilt::KramdownTemplate` - * Maruku - `Tilt::MarukuTemplate` - -Tilt will use fallback mode (as documented in the README) for determining which -library to use. RDiscount has highest priority - Maruku has lowest. - -### Example - - Hello Markdown Templates - ======================== - - Hello World. This is a paragraph. - -### Usage - -To wrap a Markdown formatted document with a layout: - - layout = Tilt['erb'].new do - "<%= yield %>" - end - data = Tilt['md'].new { "# hello tilt" } - layout.render { data.render } - # => "

hello tilt

\n" - -### Options - -Every implementation of Markdown *should* support these options, but there are -some known problems with the Kramdown and Maruku engines. - -#### `:smartypants => true|false` - -Set `true` to enable [Smarty Pants][smartypants] -style punctuation replacement. - -#### `:escape_html => true|false` - -Set `true` disallow raw HTML in Markdown contents. HTML is converted to -literal text by escaping `<` characters. - -### See also - - * [Markdown Syntax Documentation](http://daringfireball.net/projects/markdown/syntax/) - - -RDiscount (`markdown`, `md`, `mkd`) ------------------------------------ - -[Discount][discount] is an implementation of the Markdown markup language in C. -[RDiscount][rdiscount] is a Ruby wrapper around Discount. - -All the documentation of [Markdown](#markdown) applies in addition to the following: - -### Usage - -The `Tilt::RDiscountTemplate` class is registered for all files ending in -`.markdown`, `.md` or `.mkd` by default with the highest priority. If you -specifically want to use RDiscount, it's recommended to use `#prefer`: - - Tilt.prefer Tilt::RDiscountTemplate - -__NOTE:__ It's suggested that your program `require 'erubis'` at load time when -using this template engine within a threaded environment. - -### See also - - * [Discount][discount] - * [RDiscount][rdiscount] - * GitHub: [rtomayko/rdiscount][rdiscount] - - -[lesscss]: http://lesscss.org/ "Less CSS" -[sass]: http://sass-lang.com/ "Sass" -[coffee-script]: http://jashkenas.github.com/coffee-script/ "Coffee Script" -[erubis]: http://www.kuwata-lab.com/erubis/ "Erubis" -[haml]: http://haml.info/ "Haml" -[liquid]: http://www.liquidmarkup.org/ "Liquid" -[radius]: http://radius.rubyforge.org/ "Radius" -[radiant]: http://radiantcms.org/ "Radiant CMS" -[redcloth]: http://redcloth.org/ "RedCloth" -[rdoc]: http://rdoc.rubyforge.org/ "RDoc" -[discount]: http://www.pell.portland.or.us/~orc/Code/discount/ "Discount" -[rdiscount]: http://github.com/rtomayko/rdiscount/ "RDiscount" -[smartypants]: http://daringfireball.net/projects/smartypants/ "Smarty Pants" - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/bin/tilt b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/bin/tilt deleted file mode 100755 index 91ca399..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/bin/tilt +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env ruby -require 'ostruct' -require 'optparse' -require 'tilt' - -usage = < -Process template and write output to stdout. With no or -when is '-', read template from stdin and use the --type option -to determine the template's type. - -Options - -l, --list List template engines + file patterns and exit - -t, --type= Use this template engine; required if no - -y, --layout= Use as a layout template - - -D= Define variable as - --vars= Evaluate to Hash and use for variables - - -h, --help Show this help message - -Convert markdown to HTML: - $ tilt foo.markdown > foo.html - -Process ERB template: - $ echo "Answer: <%= 2 + 2 %>" | tilt -t erb - Answer: 4 - -Define variables: - $ echo "Answer: <%= 2 + n %>" | tilt -t erb --vars="{:n=>40}" - Answer: 42 - $ echo "Answer: <%= 2 + n.to_i %>" | tilt -t erb -Dn=40 - Answer: 42 -USAGE - -script_name = File.basename($0) -pattern = nil -layout = nil -locals = {} - -ARGV.options do |o| - o.program_name = script_name - - # list all available template engines - o.on("-l", "--list") do - groups = {} - Tilt.mappings.each do |pattern,engines| - engines.each do |engine| - key = engine.name.split('::').last.sub(/Template$/, '') - (groups[key] ||= []) << pattern - end - end - groups.sort { |(k1,v1),(k2,v2)| k1 <=> k2 }.each do |engine,files| - printf "%-15s %s\n", engine, files.sort.join(', ') - end - exit - end - - # the template type / pattern - o.on("-t", "--type=PATTERN", String) do |val| - abort "unknown template type: #{val}" if Tilt[val].nil? - pattern = val - end - - # pass template output into the specified layout template - o.on("-y", "--layout=FILE", String) do |file| - paths = [file, "~/.tilt/#{file}", "/etc/tilt/#{file}"] - layout = paths. - map { |p| File.expand_path(p) }. - find { |p| File.exist?(p) } - abort "no such layout: #{file}" if layout.nil? - end - - # define a local variable - o.on("-D", "--define=PAIR", String) do |pair| - key, value = pair.split(/[=:]/, 2) - locals[key.to_sym] = value - end - - # define local variables using a Ruby hash - o.on("--vars=RUBY") do |ruby| - hash = eval(ruby) - abort "vars must be a Hash, not #{hash.inspect}" if !hash.is_a?(Hash) - hash.each { |key, value| locals[key.to_sym] = value } - end - - o.on_tail("-h", "--help") { puts usage; exit } - - o.parse! -end - -file = ARGV.first || '-' -pattern = file if pattern.nil? -abort "template type not given. see: #{$0} --help" if ['-', ''].include?(pattern) - -engine = Tilt[pattern] -abort "template engine not found for: #{pattern}" if engine.nil? - -template = - engine.new(file) { - if file == '-' - $stdin.read - else - File.read(file) - end - } -output = template.render(self, locals) - -# process layout -output = Tilt.new(layout).render(self, locals) { output } if layout - -$stdout.write(output) diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt.rb deleted file mode 100644 index 52756db..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt.rb +++ /dev/null @@ -1,204 +0,0 @@ -module Tilt - VERSION = '1.4.1' - - @preferred_mappings = Hash.new - @template_mappings = Hash.new { |h, k| h[k] = [] } - - # Hash of template path pattern => template implementation class mappings. - def self.mappings - @template_mappings - end - - def self.normalize(ext) - ext.to_s.downcase.sub(/^\./, '') - end - - # Register a template implementation by file extension. - def self.register(template_class, *extensions) - if template_class.respond_to?(:to_str) - # Support register(ext, template_class) too - extensions, template_class = [template_class], extensions[0] - end - - extensions.each do |ext| - ext = normalize(ext) - mappings[ext].unshift(template_class).uniq! - end - end - - # Makes a template class preferred for the given file extensions. If you - # don't provide any extensions, it will be preferred for all its already - # registered extensions: - # - # # Prefer RDiscount for its registered file extensions: - # Tilt.prefer(Tilt::RDiscountTemplate) - # - # # Prefer RDiscount only for the .md extensions: - # Tilt.prefer(Tilt::RDiscountTemplate, '.md') - def self.prefer(template_class, *extensions) - if extensions.empty? - mappings.each do |ext, klasses| - @preferred_mappings[ext] = template_class if klasses.include? template_class - end - else - extensions.each do |ext| - ext = normalize(ext) - register(template_class, ext) - @preferred_mappings[ext] = template_class - end - end - end - - # Returns true when a template exists on an exact match of the provided file extension - def self.registered?(ext) - mappings.key?(ext.downcase) && !mappings[ext.downcase].empty? - end - - # Create a new template for the given file using the file's extension - # to determine the the template mapping. - def self.new(file, line=nil, options={}, &block) - if template_class = self[file] - template_class.new(file, line, options, &block) - else - fail "No template engine registered for #{File.basename(file)}" - end - end - - # Lookup a template class for the given filename or file - # extension. Return nil when no implementation is found. - def self.[](file) - pattern = file.to_s.downcase - until pattern.empty? || registered?(pattern) - pattern = File.basename(pattern) - pattern.sub!(/^[^.]*\.?/, '') - end - - # Try to find a preferred engine. - preferred_klass = @preferred_mappings[pattern] - return preferred_klass if preferred_klass - - # Fall back to the general list of mappings. - klasses = @template_mappings[pattern] - - # Try to find an engine which is already loaded. - template = klasses.detect do |klass| - if klass.respond_to?(:engine_initialized?) - klass.engine_initialized? - end - end - - return template if template - - # Try each of the classes until one succeeds. If all of them fails, - # we'll raise the error of the first class. - first_failure = nil - - klasses.each do |klass| - begin - klass.new { '' } - rescue Exception => ex - first_failure ||= ex - next - else - return klass - end - end - - raise first_failure if first_failure - end - - # Deprecated module. - module CompileSite - end - - # Extremely simple template cache implementation. Calling applications - # create a Tilt::Cache instance and use #fetch with any set of hashable - # arguments (such as those to Tilt.new): - # cache = Tilt::Cache.new - # cache.fetch(path, line, options) { Tilt.new(path, line, options) } - # - # Subsequent invocations return the already loaded template object. - class Cache - def initialize - @cache = {} - end - - def fetch(*key) - @cache[key] ||= yield - end - - def clear - @cache = {} - end - end - - - # Template Implementations ================================================ - - require 'tilt/string' - register StringTemplate, 'str' - - require 'tilt/erb' - register ERBTemplate, 'erb', 'rhtml' - register ErubisTemplate, 'erb', 'rhtml', 'erubis' - - require 'tilt/etanni' - register EtanniTemplate, 'etn', 'etanni' - - require 'tilt/haml' - register HamlTemplate, 'haml' - - require 'tilt/css' - register SassTemplate, 'sass' - register ScssTemplate, 'scss' - register LessTemplate, 'less' - - require 'tilt/csv' - register CSVTemplate, 'rcsv' - - require 'tilt/coffee' - register CoffeeScriptTemplate, 'coffee' - - require 'tilt/nokogiri' - register NokogiriTemplate, 'nokogiri' - - require 'tilt/builder' - register BuilderTemplate, 'builder' - - require 'tilt/markaby' - register MarkabyTemplate, 'mab' - - require 'tilt/liquid' - register LiquidTemplate, 'liquid' - - require 'tilt/radius' - register RadiusTemplate, 'radius' - - require 'tilt/markdown' - register MarukuTemplate, 'markdown', 'mkd', 'md' - register KramdownTemplate, 'markdown', 'mkd', 'md' - register BlueClothTemplate, 'markdown', 'mkd', 'md' - register RDiscountTemplate, 'markdown', 'mkd', 'md' - register RedcarpetTemplate::Redcarpet1, 'markdown', 'mkd', 'md' - register RedcarpetTemplate::Redcarpet2, 'markdown', 'mkd', 'md' - register RedcarpetTemplate, 'markdown', 'mkd', 'md' - - require 'tilt/textile' - register RedClothTemplate, 'textile' - - require 'tilt/rdoc' - register RDocTemplate, 'rdoc' - - require 'tilt/wiki' - register CreoleTemplate, 'wiki', 'creole' - register WikiClothTemplate, 'wiki', 'mediawiki', 'mw' - - require 'tilt/yajl' - register YajlTemplate, 'yajl' - - require 'tilt/asciidoc' - register AsciidoctorTemplate, 'ad', 'adoc', 'asciidoc' - - require 'tilt/plain' - register PlainTemplate, 'html' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/asciidoc.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/asciidoc.rb deleted file mode 100644 index 6e3029c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/asciidoc.rb +++ /dev/null @@ -1,34 +0,0 @@ -require 'tilt/template' - -# AsciiDoc see: http://asciidoc.org/ -module Tilt - # Asciidoctor implementation for AsciiDoc see: - # http://asciidoctor.github.com/ - # - # Asciidoctor is an open source, pure-Ruby processor for - # converting AsciiDoc documents or strings into HTML 5, - # DocBook 4.5 and other formats. - class AsciidoctorTemplate < Template - self.default_mime_type = 'text/html' - - def self.engine_initialized? - defined? ::Asciidoctor::Document - end - - def initialize_engine - require_template_library 'asciidoctor' - end - - def prepare - options[:header_footer] = false if options[:header_footer].nil? - end - - def evaluate(scope, locals, &block) - @output ||= Asciidoctor.render(data, options, &block) - end - - def allows_script? - false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/builder.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/builder.rb deleted file mode 100644 index f928952..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/builder.rb +++ /dev/null @@ -1,40 +0,0 @@ -require 'tilt/template' - -module Tilt - # Builder template implementation. See: - # http://builder.rubyforge.org/ - class BuilderTemplate < Template - self.default_mime_type = 'text/xml' - - def self.engine_initialized? - defined? ::Builder - end - - def initialize_engine - require_template_library 'builder' - end - - def prepare; end - - def evaluate(scope, locals, &block) - return super(scope, locals, &block) if data.respond_to?(:to_str) - xml = ::Builder::XmlMarkup.new(:indent => 2) - data.call(xml) - xml.target! - end - - def precompiled_preamble(locals) - return super if locals.include? :xml - "xml = ::Builder::XmlMarkup.new(:indent => 2)\n#{super}" - end - - def precompiled_postamble(locals) - "xml.target!" - end - - def precompiled_template(locals) - data.to_str - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/coffee.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/coffee.rb deleted file mode 100644 index fafaac8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/coffee.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'tilt/template' - -module Tilt - # CoffeeScript template implementation. See: - # http://coffeescript.org/ - # - # CoffeeScript templates do not support object scopes, locals, or yield. - class CoffeeScriptTemplate < Template - self.default_mime_type = 'application/javascript' - - @@default_bare = false - - def self.default_bare - @@default_bare - end - - def self.default_bare=(value) - @@default_bare = value - end - - # DEPRECATED - def self.default_no_wrap - @@default_bare - end - - # DEPRECATED - def self.default_no_wrap=(value) - @@default_bare = value - end - - def self.engine_initialized? - defined? ::CoffeeScript - end - - def initialize_engine - require_template_library 'coffee_script' - end - - def prepare - if !options.key?(:bare) and !options.key?(:no_wrap) - options[:bare] = self.class.default_bare - end - end - - def evaluate(scope, locals, &block) - @output ||= CoffeeScript.compile(data, options) - end - - def allows_script? - false - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/css.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/css.rb deleted file mode 100644 index b237de9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/css.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'tilt/template' - -module Tilt - # Sass template implementation. See: - # http://haml.hamptoncatlin.com/ - # - # Sass templates do not support object scopes, locals, or yield. - class SassTemplate < Template - self.default_mime_type = 'text/css' - - def self.engine_initialized? - defined? ::Sass::Engine - end - - def initialize_engine - require_template_library 'sass' - end - - def prepare - @engine = ::Sass::Engine.new(data, sass_options) - end - - def evaluate(scope, locals, &block) - @output ||= @engine.render - end - - def allows_script? - false - end - - private - def sass_options - options.merge(:filename => eval_file, :line => line, :syntax => :sass) - end - end - - # Sass's new .scss type template implementation. - class ScssTemplate < SassTemplate - self.default_mime_type = 'text/css' - - private - def sass_options - options.merge(:filename => eval_file, :line => line, :syntax => :scss) - end - end - - # Lessscss template implementation. See: - # http://lesscss.org/ - # - # Less templates do not support object scopes, locals, or yield. - class LessTemplate < Template - self.default_mime_type = 'text/css' - - def self.engine_initialized? - defined? ::Less - end - - def initialize_engine - require_template_library 'less' - end - - def prepare - if ::Less.const_defined? :Engine - @engine = ::Less::Engine.new(data) - else - parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line) - @engine = parser.parse(data) - end - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_css(options) - end - - def allows_script? - false - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/csv.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/csv.rb deleted file mode 100644 index 31214fa..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/csv.rb +++ /dev/null @@ -1,71 +0,0 @@ -require 'tilt/template' - -module Tilt - - # CSV Template implementation. See: - # http://ruby-doc.org/stdlib/libdoc/csv/rdoc/CSV.html - # - # == Example - # - # # Example of csv template - # tpl = <<-EOS - # # header - # csv << ['NAME', 'ID'] - # - # # data rows - # @people.each do |person| - # csv << [person[:name], person[:id]] - # end - # EOS - # - # @people = [ - # {:name => "Joshua Peek", :id => 1}, - # {:name => "Ryan Tomayko", :id => 2}, - # {:name => "Simone Carletti", :id => 3} - # ] - # - # template = Tilt::CSVTemplate.new { tpl } - # template.render(self) - # - class CSVTemplate < Template - self.default_mime_type = 'text/csv' - - def self.engine_initialized? - engine - end - - def self.engine - if RUBY_VERSION >= '1.9.0' && defined? ::CSV - ::CSV - elsif defined? ::FasterCSV - ::FasterCSV - end - end - - def initialize_engine - if RUBY_VERSION >= '1.9.0' - require_template_library 'csv' - else - require_template_library 'fastercsv' - end - end - - def prepare - @code =<<-RUBY - #{self.class.engine}.generate do |csv| - #{data} - end - RUBY - end - - def precompiled_template(locals) - @code - end - - def precompiled(locals) - source, offset = super - [source, offset + 1] - end - - end -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/erb.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/erb.rb deleted file mode 100644 index 513ac70..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/erb.rb +++ /dev/null @@ -1,110 +0,0 @@ -require 'tilt/template' - -module Tilt - # ERB template implementation. See: - # http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html - class ERBTemplate < Template - @@default_output_variable = '_erbout' - - def self.default_output_variable - @@default_output_variable - end - - def self.default_output_variable=(name) - @@default_output_variable = name - end - - def self.engine_initialized? - defined? ::ERB - end - - def initialize_engine - require_template_library 'erb' - end - - def prepare - @outvar = options[:outvar] || self.class.default_output_variable - options[:trim] = '<>' if !(options[:trim] == false) && (options[:trim].nil? || options[:trim] == true) - @engine = ::ERB.new(data, options[:safe], options[:trim], @outvar) - end - - def precompiled_template(locals) - source = @engine.src - source - end - - def precompiled_preamble(locals) - <<-RUBY - begin - __original_outvar = #{@outvar} if defined?(#{@outvar}) - #{super} - RUBY - end - - def precompiled_postamble(locals) - <<-RUBY - #{super} - ensure - #{@outvar} = __original_outvar - end - RUBY - end - - # ERB generates a line to specify the character coding of the generated - # source in 1.9. Account for this in the line offset. - if RUBY_VERSION >= '1.9.0' - def precompiled(locals) - source, offset = super - [source, offset + 1] - end - end - end - - # Erubis template implementation. See: - # http://www.kuwata-lab.com/erubis/ - # - # ErubisTemplate supports the following additional options, which are not - # passed down to the Erubis engine: - # - # :engine_class allows you to specify a custom engine class to use - # instead of the default (which is ::Erubis::Eruby). - # - # :escape_html when true, ::Erubis::EscapedEruby will be used as - # the engine class instead of the default. All content - # within <%= %> blocks will be automatically html escaped. - class ErubisTemplate < ERBTemplate - def self.engine_initialized? - defined? ::Erubis::Eruby - end - - def initialize_engine - require_template_library 'erubis' - end - - def prepare - @outvar = options.delete(:outvar) || self.class.default_output_variable - @options.merge!(:preamble => false, :postamble => false, :bufvar => @outvar) - engine_class = options.delete(:engine_class) - engine_class = ::Erubis::EscapedEruby if options.delete(:escape_html) - @engine = (engine_class || ::Erubis::Eruby).new(data, options) - end - - def precompiled_preamble(locals) - [super, "#{@outvar} = _buf = ''"].join("\n") - end - - def precompiled_postamble(locals) - [@outvar, super].join("\n") - end - - # Erubis doesn't have ERB's line-off-by-one under 1.9 problem. - # Override and adjust back. - if RUBY_VERSION >= '1.9.0' - def precompiled(locals) - source, offset = super - [source, offset - 1] - end - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/etanni.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/etanni.rb deleted file mode 100644 index e598ced..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/etanni.rb +++ /dev/null @@ -1,27 +0,0 @@ -require 'tilt/template' - -module Tilt - class EtanniTemplate < Template - def prepare - separator = data.hash.abs - chomp = "<<#{separator}.chomp!" - start = "\n_out_ << #{chomp}\n" - stop = "\n#{separator}\n" - replacement = "#{stop}\\1#{start}" - - temp = data.strip - temp.gsub!(/<\?r\s+(.*?)\s+\?>/m, replacement) - - @code = "_out_ = [<<#{separator}.chomp!]\n#{temp}#{stop}_out_.join" - end - - def precompiled_template(locals) - @code - end - - def precompiled(locals) - source, offset = super - [source, offset + 1] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/haml.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/haml.rb deleted file mode 100644 index 6312206..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/haml.rb +++ /dev/null @@ -1,64 +0,0 @@ -require 'tilt/template' - -module Tilt - # Haml template implementation. See: - # http://haml.hamptoncatlin.com/ - class HamlTemplate < Template - self.default_mime_type = 'text/html' - - def self.engine_initialized? - defined? ::Haml::Engine - end - - def initialize_engine - require_template_library 'haml' - end - - def prepare - options = @options.merge(:filename => eval_file, :line => line) - @engine = ::Haml::Engine.new(data, options) - end - - def evaluate(scope, locals, &block) - if @engine.respond_to?(:precompiled_method_return_value, true) - super - else - @engine.render(scope, locals, &block) - end - end - - # Precompiled Haml source. Taken from the precompiled_with_ambles - # method in Haml::Precompiler: - # http://github.com/nex3/haml/blob/master/lib/haml/precompiler.rb#L111-126 - def precompiled_template(locals) - @engine.precompiled - end - - def precompiled_preamble(locals) - local_assigns = super - @engine.instance_eval do - <<-RUBY - begin - extend Haml::Helpers - _hamlout = @haml_buffer = Haml::Buffer.new(@haml_buffer, #{options_for_buffer.inspect}) - _erbout = _hamlout.buffer - __in_erb_template = true - _haml_locals = locals - #{local_assigns} - RUBY - end - end - - def precompiled_postamble(locals) - @engine.instance_eval do - <<-RUBY - #{precompiled_method_return_value} - ensure - @haml_buffer = @haml_buffer.upper - end - RUBY - end - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/liquid.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/liquid.rb deleted file mode 100644 index 3364911..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/liquid.rb +++ /dev/null @@ -1,45 +0,0 @@ -require 'tilt/template' - -module Tilt - # Liquid template implementation. See: - # http://liquid.rubyforge.org/ - # - # Liquid is designed to be a *safe* template system and threfore - # does not provide direct access to execuatable scopes. In order to - # support a +scope+, the +scope+ must be able to represent itself - # as a hash by responding to #to_h. If the +scope+ does not respond - # to #to_h it will be ignored. - # - # LiquidTemplate does not support yield blocks. - # - # It's suggested that your program require 'liquid' at load - # time when using this template engine. - class LiquidTemplate < Template - def self.engine_initialized? - defined? ::Liquid::Template - end - - def initialize_engine - require_template_library 'liquid' - end - - def prepare - @engine = ::Liquid::Template.parse(data) - end - - def evaluate(scope, locals, &block) - locals = locals.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } - if scope.respond_to?(:to_h) - scope = scope.to_h.inject({}){ |h,(k,v)| h[k.to_s] = v ; h } - locals = scope.merge(locals) - end - locals['yield'] = block.nil? ? '' : yield - locals['content'] = locals['yield'] - @engine.render(locals) - end - - def allows_script? - false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/markaby.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/markaby.rb deleted file mode 100644 index 3271e14..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/markaby.rb +++ /dev/null @@ -1,52 +0,0 @@ -require 'tilt/template' - -module Tilt - # Markaby - # http://github.com/markaby/markaby - class MarkabyTemplate < Template - def self.builder_class - @builder_class ||= Class.new(Markaby::Builder) do - def __capture_markaby_tilt__(&block) - __run_markaby_tilt__ do - text capture(&block) - end - end - end - end - - def self.engine_initialized? - defined? ::Markaby - end - - def initialize_engine - require_template_library 'markaby' - end - - def prepare - end - - def evaluate(scope, locals, &block) - builder = self.class.builder_class.new({}, scope) - builder.locals = locals - - if data.kind_of? Proc - (class << builder; self end).send(:define_method, :__run_markaby_tilt__, &data) - else - builder.instance_eval <<-CODE, __FILE__, __LINE__ - def __run_markaby_tilt__ - #{data} - end - CODE - end - - if block - builder.__capture_markaby_tilt__(&block) - else - builder.__run_markaby_tilt__ - end - - builder.to_s - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/markdown.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/markdown.rb deleted file mode 100644 index 0d089f1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/markdown.rb +++ /dev/null @@ -1,214 +0,0 @@ -require 'tilt/template' - -module Tilt - # Discount Markdown implementation. See: - # http://github.com/rtomayko/rdiscount - # - # RDiscount is a simple text filter. It does not support +scope+ or - # +locals+. The +:smart+ and +:filter_html+ options may be set true - # to enable those flags on the underlying RDiscount object. - class RDiscountTemplate < Template - self.default_mime_type = 'text/html' - - ALIAS = { - :escape_html => :filter_html, - :smartypants => :smart - } - - FLAGS = [:smart, :filter_html, :smartypants, :escape_html] - - def flags - FLAGS.select { |flag| options[flag] }.map { |flag| ALIAS[flag] || flag } - end - - def self.engine_initialized? - defined? ::RDiscount - end - - def initialize_engine - require_template_library 'rdiscount' - end - - def prepare - @engine = RDiscount.new(data, *flags) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_html - end - - def allows_script? - false - end - end - - # Upskirt Markdown implementation. See: - # https://github.com/tanoku/redcarpet - # - # Supports both Redcarpet 1.x and 2.x - class RedcarpetTemplate < Template - def self.engine_initialized? - defined? ::Redcarpet - end - - def initialize_engine - require_template_library 'redcarpet' - end - - def prepare - klass = [Redcarpet2, Redcarpet1].detect { |e| e.engine_initialized? } - @engine = klass.new(file, line, options) { data } - end - - def evaluate(scope, locals, &block) - @engine.evaluate(scope, locals, &block) - end - - def allows_script? - false - end - - # Compatibility mode for Redcarpet 1.x - class Redcarpet1 < RDiscountTemplate - self.default_mime_type = 'text/html' - - def self.engine_initialized? - defined? ::RedcarpetCompat - end - - def prepare - @engine = RedcarpetCompat.new(data, *flags) - @output = nil - end - end - - # Future proof mode for Redcarpet 2.x (not yet released) - class Redcarpet2 < Template - self.default_mime_type = 'text/html' - - def self.engine_initialized? - defined? ::Redcarpet::Render and defined? ::Redcarpet::Markdown - end - - def generate_renderer - renderer = options.delete(:renderer) || ::Redcarpet::Render::HTML - return renderer unless options.delete(:smartypants) - return renderer if renderer.is_a?(Class) && renderer <= ::Redcarpet::Render::SmartyPants - - if renderer == ::Redcarpet::Render::XHTML - ::Redcarpet::Render::SmartyHTML.new(:xhtml => true) - elsif renderer == ::Redcarpet::Render::HTML - ::Redcarpet::Render::SmartyHTML - elsif renderer.is_a? Class - Class.new(renderer) { include ::Redcarpet::Render::SmartyPants } - else - renderer.extend ::Redcarpet::Render::SmartyPants - end - end - - def prepare - # try to support the same aliases - RDiscountTemplate::ALIAS.each do |opt, aka| - next if options.key? opt or not options.key? aka - options[opt] = options.delete(aka) - end - - # only raise an exception if someone is trying to enable :escape_html - options.delete(:escape_html) unless options[:escape_html] - - @engine = ::Redcarpet::Markdown.new(generate_renderer, options) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.render(data) - end - - def allows_script? - false - end - end - end - - # BlueCloth Markdown implementation. See: - # http://deveiate.org/projects/BlueCloth/ - class BlueClothTemplate < Template - self.default_mime_type = 'text/html' - - def self.engine_initialized? - defined? ::BlueCloth - end - - def initialize_engine - require_template_library 'bluecloth' - end - - def prepare - @engine = BlueCloth.new(data, options) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_html - end - - def allows_script? - false - end - end - - # Maruku markdown implementation. See: - # http://maruku.rubyforge.org/ - class MarukuTemplate < Template - def self.engine_initialized? - defined? ::Maruku - end - - def initialize_engine - require_template_library 'maruku' - end - - def prepare - @engine = Maruku.new(data, options) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_html - end - - def allows_script? - false - end - end - - # Kramdown Markdown implementation. See: - # http://kramdown.rubyforge.org/ - class KramdownTemplate < Template - DUMB_QUOTES = [39, 39, 34, 34] - - def self.engine_initialized? - defined? ::Kramdown - end - - def initialize_engine - require_template_library 'kramdown' - end - - def prepare - options[:smart_quotes] = DUMB_QUOTES unless options[:smartypants] - @engine = Kramdown::Document.new(data, options) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_html - end - - def allows_script? - false - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/nokogiri.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/nokogiri.rb deleted file mode 100644 index 556c284..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/nokogiri.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'tilt/template' - -module Tilt - # Nokogiri template implementation. See: - # http://nokogiri.org/ - class NokogiriTemplate < Template - DOCUMENT_HEADER = /^<\?xml version=\"1\.0\"\?>\n?/ - self.default_mime_type = 'text/xml' - - def self.engine_initialized? - defined? ::Nokogiri - end - - def initialize_engine - require_template_library 'nokogiri' - end - - def prepare; end - - def evaluate(scope, locals) - if data.respond_to?(:to_str) - wrapper = proc { yield.sub(DOCUMENT_HEADER, "") } if block_given? - super(scope, locals, &wrapper) - else - ::Nokogiri::XML::Builder.new.tap(&data).to_xml - end - end - - def precompiled_preamble(locals) - return super if locals.include? :xml - "xml = ::Nokogiri::XML::Builder.new { |xml| }\n#{super}" - end - - def precompiled_postamble(locals) - "xml.to_xml" - end - - def precompiled_template(locals) - data.to_str - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/plain.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/plain.rb deleted file mode 100644 index 4c08052..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/plain.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'tilt/template' - - -module Tilt - # Raw text (no template functionality). - class PlainTemplate < Template - self.default_mime_type = 'text/html' - - def self.engine_initialized? - true - end - - def prepare - end - - def evaluate(scope, locals, &block) - @output ||= data - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/radius.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/radius.rb deleted file mode 100644 index 64ec908..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/radius.rb +++ /dev/null @@ -1,55 +0,0 @@ -require 'tilt/template' - -module Tilt - # Radius Template - # http://github.com/jlong/radius/ - class RadiusTemplate < Template - def self.engine_initialized? - defined? ::Radius - end - - def self.context_class - @context_class ||= Class.new(Radius::Context) do - attr_accessor :tilt_scope - - def tag_missing(name, attributes) - tilt_scope.__send__(name) - end - - def dup - i = super - i.tilt_scope = tilt_scope - i - end - end - end - - def initialize_engine - require_template_library 'radius' - end - - def prepare - end - - def evaluate(scope, locals, &block) - context = self.class.context_class.new - context.tilt_scope = scope - context.define_tag("yield") do - block.call - end - locals.each do |tag, value| - context.define_tag(tag) do - value - end - end - - options = {:tag_prefix => 'r'}.merge(@options) - parser = Radius::Parser.new(context, options) - parser.parse(data) - end - - def allows_script? - false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/rdoc.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/rdoc.rb deleted file mode 100644 index 91f0dce..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/rdoc.rb +++ /dev/null @@ -1,47 +0,0 @@ -require 'tilt/template' - -module Tilt - # RDoc template. See: - # http://rdoc.rubyforge.org/ - # - # It's suggested that your program `require 'rdoc/markup'` and - # `require 'rdoc/markup/to_html'` at load time when using this template - # engine in a threaded environment. - class RDocTemplate < Template - self.default_mime_type = 'text/html' - - def self.engine_initialized? - defined? ::RDoc::Markup::ToHtml - end - - def initialize_engine - require_template_library 'rdoc' - require_template_library 'rdoc/markup' - require_template_library 'rdoc/markup/to_html' - end - - def markup - begin - # RDoc 4.0 - require 'rdoc/options' - RDoc::Markup::ToHtml.new(RDoc::Options.new, nil) - rescue ArgumentError - # RDoc < 4.0 - RDoc::Markup::ToHtml.new - end - end - - def prepare - @engine = markup.convert(data) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_s - end - - def allows_script? - false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/string.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/string.rb deleted file mode 100644 index 5bc6958..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/string.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'tilt/template' - -module Tilt - # The template source is evaluated as a Ruby string. The #{} interpolation - # syntax can be used to generated dynamic output. - class StringTemplate < Template - def prepare - hash = "TILT#{data.hash.abs}" - @code = "<<#{hash}.chomp\n#{data}\n#{hash}" - end - - def precompiled_template(locals) - @code - end - - def precompiled(locals) - source, offset = super - [source, offset + 1] - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/template.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/template.rb deleted file mode 100644 index 9b52237..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/template.rb +++ /dev/null @@ -1,292 +0,0 @@ -module Tilt - TOPOBJECT = Object.superclass || Object - - # Base class for template implementations. Subclasses must implement - # the #prepare method and one of the #evaluate or #precompiled_template - # methods. - class Template - # Template source; loaded from a file or given directly. - attr_reader :data - - # The name of the file where the template data was loaded from. - attr_reader :file - - # The line number in #file where template data was loaded from. - attr_reader :line - - # A Hash of template engine specific options. This is passed directly - # to the underlying engine and is not used by the generic template - # interface. - attr_reader :options - - # Used to determine if this class's initialize_engine method has - # been called yet. - @engine_initialized = false - class << self - attr_accessor :engine_initialized - alias engine_initialized? engine_initialized - - attr_accessor :default_mime_type - end - - # Create a new template with the file, line, and options specified. By - # default, template data is read from the file. When a block is given, - # it should read template data and return as a String. When file is nil, - # a block is required. - # - # All arguments are optional. - def initialize(file=nil, line=1, options={}, &block) - @file, @line, @options = nil, 1, {} - - [options, line, file].compact.each do |arg| - case - when arg.respond_to?(:to_str) ; @file = arg.to_str - when arg.respond_to?(:to_int) ; @line = arg.to_int - when arg.respond_to?(:to_hash) ; @options = arg.to_hash.dup - when arg.respond_to?(:path) ; @file = arg.path - else raise TypeError - end - end - - raise ArgumentError, "file or block required" if (@file || block).nil? - - # call the initialize_engine method if this is the very first time - # an instance of this class has been created. - if !self.class.engine_initialized? - initialize_engine - self.class.engine_initialized = true - end - - # used to hold compiled template methods - @compiled_method = {} - - # used on 1.9 to set the encoding if it is not set elsewhere (like a magic comment) - # currently only used if template compiles to ruby - @default_encoding = @options.delete :default_encoding - - # load template data and prepare (uses binread to avoid encoding issues) - @reader = block || lambda { |t| read_template_file } - @data = @reader.call(self) - - if @data.respond_to?(:force_encoding) - @data.force_encoding(default_encoding) if default_encoding - - if !@data.valid_encoding? - raise Encoding::InvalidByteSequenceError, "#{eval_file} is not valid #{@data.encoding}" - end - end - - prepare - end - - # The encoding of the source data. Defaults to the - # default_encoding-option if present. You may override this method - # in your template class if you have a better hint of the data's - # encoding. - def default_encoding - @default_encoding - end - - def read_template_file - data = File.open(file, 'rb') { |io| io.read } - if data.respond_to?(:force_encoding) - # Set it to the default external (without verifying) - data.force_encoding(Encoding.default_external) if Encoding.default_external - end - data - end - - # Render the template in the given scope with the locals specified. If a - # block is given, it is typically available within the template via - # +yield+. - def render(scope=Object.new, locals={}, &block) - evaluate scope, locals || {}, &block - end - - # The basename of the template file. - def basename(suffix='') - File.basename(file, suffix) if file - end - - # The template file's basename with all extensions chomped off. - def name - basename.split('.', 2).first if basename - end - - # The filename used in backtraces to describe the template. - def eval_file - file || '(__TEMPLATE__)' - end - - # Whether or not this template engine allows executing Ruby script - # within the template. If this is false, +scope+ and +locals+ will - # generally not be used, nor will the provided block be avaiable - # via +yield+. - # This should be overridden by template subclasses. - def allows_script? - true - end - - protected - # Called once and only once for each template subclass the first time - # the template class is initialized. This should be used to require the - # underlying template library and perform any initial setup. - def initialize_engine - end - - # Like Kernel#require but issues a warning urging a manual require when - # running under a threaded environment. - def require_template_library(name) - if Thread.list.size > 1 - warn "WARN: tilt autoloading '#{name}' in a non thread-safe way; " + - "explicit require '#{name}' suggested." - end - require name - end - - # Do whatever preparation is necessary to setup the underlying template - # engine. Called immediately after template data is loaded. Instance - # variables set in this method are available when #evaluate is called. - # - # Subclasses must provide an implementation of this method. - def prepare - if respond_to?(:compile!) - # backward compat with tilt < 0.6; just in case - warn 'Tilt::Template#compile! is deprecated; implement #prepare instead.' - compile! - else - raise NotImplementedError - end - end - - # Execute the compiled template and return the result string. Template - # evaluation is guaranteed to be performed in the scope object with the - # locals specified and with support for yielding to the block. - # - # This method is only used by source generating templates. Subclasses that - # override render() may not support all features. - def evaluate(scope, locals, &block) - method = compiled_method(locals.keys) - method.bind(scope).call(locals, &block) - end - - # Generates all template source by combining the preamble, template, and - # postamble and returns a two-tuple of the form: [source, offset], where - # source is the string containing (Ruby) source code for the template and - # offset is the integer line offset where line reporting should begin. - # - # Template subclasses may override this method when they need complete - # control over source generation or want to adjust the default line - # offset. In most cases, overriding the #precompiled_template method is - # easier and more appropriate. - def precompiled(locals) - preamble = precompiled_preamble(locals) - template = precompiled_template(locals) - postamble = precompiled_postamble(locals) - source = '' - - # Ensure that our generated source code has the same encoding as the - # the source code generated by the template engine. - if source.respond_to?(:force_encoding) - template_encoding = extract_encoding(template) - - source.force_encoding(template_encoding) - template.force_encoding(template_encoding) - end - - # https://github.com/rtomayko/tilt/issues/193 - warn "precompiled_preamble should return String (not Array)" if preamble.is_a?(Array) - warn "precompiled_postamble should return String (not Array)" if postamble.is_a?(Array) - source << [preamble, template, postamble].join("\n") - - [source, preamble.count("\n")+1] - end - - # A string containing the (Ruby) source code for the template. The - # default Template#evaluate implementation requires either this - # method or the #precompiled method be overridden. When defined, - # the base Template guarantees correct file/line handling, locals - # support, custom scopes, proper encoding, and support for template - # compilation. - def precompiled_template(locals) - raise NotImplementedError - end - - # Generates preamble code for initializing template state, and performing - # locals assignment. The default implementation performs locals - # assignment only. Lines included in the preamble are subtracted from the - # source line offset, so adding code to the preamble does not effect line - # reporting in Kernel::caller and backtraces. - def precompiled_preamble(locals) - locals.map do |k,v| - if k.to_s =~ /\A[a-z_][a-zA-Z_0-9]*\z/ - "#{k} = locals[#{k.inspect}]" - else - raise "invalid locals key: #{k.inspect} (keys must be variable names)" - end - end.join("\n") - end - - # Generates postamble code for the precompiled template source. The - # string returned from this method is appended to the precompiled - # template source. - def precompiled_postamble(locals) - '' - end - - # The compiled method for the locals keys provided. - def compiled_method(locals_keys) - @compiled_method[locals_keys] ||= - compile_template_method(locals_keys) - end - - private - def compile_template_method(locals) - source, offset = precompiled(locals) - method_name = "__tilt_#{Thread.current.object_id.abs}" - method_source = "" - - if method_source.respond_to?(:force_encoding) - method_source.force_encoding(source.encoding) - end - - method_source << <<-RUBY - TOPOBJECT.class_eval do - def #{method_name}(locals) - Thread.current[:tilt_vars] = [self, locals] - class << self - this, locals = Thread.current[:tilt_vars] - this.instance_eval do - RUBY - offset += method_source.count("\n") - method_source << source - method_source << "\nend;end;end;end" - Object.class_eval method_source, eval_file, line - offset - unbind_compiled_method(method_name) - end - - def unbind_compiled_method(method_name) - method = TOPOBJECT.instance_method(method_name) - TOPOBJECT.class_eval { remove_method(method_name) } - method - end - - def extract_encoding(script) - extract_magic_comment(script) || script.encoding - end - - def extract_magic_comment(script) - binary script do - script[/\A[ \t]*\#.*coding\s*[=:]\s*([[:alnum:]\-_]+).*$/n, 1] - end - end - - def binary(string) - original_encoding = string.encoding - string.force_encoding(Encoding::BINARY) - yield - ensure - string.force_encoding(original_encoding) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/textile.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/textile.rb deleted file mode 100644 index 9135598..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/textile.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'tilt/template' - -module Tilt - # RedCloth implementation. See: - # http://redcloth.org/ - class RedClothTemplate < Template - def self.engine_initialized? - defined? ::RedCloth - end - - def initialize_engine - require_template_library 'redcloth' - end - - def prepare - @engine = RedCloth.new(data) - options.each {|k, v| @engine.send("#{k}=", v) if @engine.respond_to? "#{k}="} - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_html - end - - def allows_script? - false - end - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/wiki.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/wiki.rb deleted file mode 100644 index 1349eb2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/wiki.rb +++ /dev/null @@ -1,58 +0,0 @@ -require 'tilt/template' - -module Tilt - # Creole implementation. See: - # http://www.wikicreole.org/ - class CreoleTemplate < Template - def self.engine_initialized? - defined? ::Creole - end - - def initialize_engine - require_template_library 'creole' - end - - def prepare - opts = {} - [:allowed_schemes, :extensions, :no_escape].each do |k| - opts[k] = options[k] if options[k] - end - @engine = Creole::Parser.new(data, opts) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_html - end - - def allows_script? - false - end - end - - # WikiCloth implementation. See: - # http://redcloth.org/ - class WikiClothTemplate < Template - def self.engine_initialized? - defined? ::WikiCloth::Parser - end - - def initialize_engine - require_template_library 'wikicloth' - end - - def prepare - @parser = options.delete(:parser) || WikiCloth::Parser - @engine = @parser.new options.merge(:data => data) - @output = nil - end - - def evaluate(scope, locals, &block) - @output ||= @engine.to_html - end - - def allows_script? - false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/yajl.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/yajl.rb deleted file mode 100644 index 0b9b702..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/lib/tilt/yajl.rb +++ /dev/null @@ -1,94 +0,0 @@ -require 'tilt/template' - -module Tilt - - # Yajl Template implementation - # - # Yajl is a fast JSON parsing and encoding library for Ruby - # See https://github.com/brianmario/yajl-ruby - # - # The template source is evaluated as a Ruby string, - # and the result is converted #to_json. - # - # == Example - # - # # This is a template example. - # # The template can contain any Ruby statement. - # tpl <<-EOS - # @counter = 0 - # - # # The json variable represents the buffer - # # and holds the data to be serialized into json. - # # It defaults to an empty hash, but you can override it at any time. - # json = { - # :"user#{@counter += 1}" => { :name => "Joshua Peek", :id => @counter }, - # :"user#{@counter += 1}" => { :name => "Ryan Tomayko", :id => @counter }, - # :"user#{@counter += 1}" => { :name => "Simone Carletti", :id => @counter }, - # } - # - # # Since the json variable is a Hash, - # # you can use conditional statements or any other Ruby statement - # # to populate it. - # json[:"user#{@counter += 1}"] = { :name => "Unknown" } if 1 == 2 - # - # # The last line doesn't affect the returned value. - # nil - # EOS - # - # template = Tilt::YajlTemplate.new { tpl } - # template.render(self) - # - class YajlTemplate < Template - - self.default_mime_type = 'application/json' - - def self.engine_initialized? - defined? ::Yajl - end - - def initialize_engine - require_template_library 'yajl' - end - - def prepare - end - - def evaluate(scope, locals, &block) - decorate super(scope, locals, &block) - end - - def precompiled_preamble(locals) - return super if locals.include? :json - "json = {}\n#{super}" - end - - def precompiled_postamble(locals) - "Yajl::Encoder.new.encode(json)" - end - - def precompiled_template(locals) - data.to_str - end - - - # Decorates the +json+ input according to given +options+. - # - # json - The json String to decorate. - # options - The option Hash to customize the behavior. - # - # Returns the decorated String. - def decorate(json) - callback, variable = options[:callback], options[:variable] - if callback && variable - "var #{variable} = #{json}; #{callback}(#{variable});" - elsif variable - "var #{variable} = #{json};" - elsif callback - "#{callback}(#{json});" - else - json - end - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/contest.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/contest.rb deleted file mode 100644 index 075f941..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/contest.rb +++ /dev/null @@ -1,68 +0,0 @@ -require "test/unit" - -# Test::Unit loads a default test if the suite is empty, whose purpose is to -# fail. Since having empty contexts is a common practice, we decided to -# overwrite TestSuite#empty? in order to allow them. Having a failure when no -# tests have been defined seems counter-intuitive. -class Test::Unit::TestSuite - def empty? - false - end -end - -# Contest adds +teardown+, +test+ and +context+ as class methods, and the -# instance methods +setup+ and +teardown+ now iterate on the corresponding -# blocks. Note that all setup and teardown blocks must be defined with the -# block syntax. Adding setup or teardown instance methods defeats the purpose -# of this library. -class Test::Unit::TestCase - def self.setup(&block) - define_method :setup do - super(&block) - instance_eval(&block) - end - end - - def self.teardown(&block) - define_method :teardown do - instance_eval(&block) - super(&block) - end - end - - def self.context(name, &block) - subclass = Class.new(self) - remove_tests(subclass) - subclass.class_eval(&block) if block_given? - const_set(context_name(name), subclass) - end - - def self.test(name, &block) - define_method(test_name(name), &block) - end - - class << self - alias_method :should, :test - alias_method :describe, :context - end - -private - - def self.context_name(name) - "Test#{sanitize_name(name).gsub(/(^| )(\w)/) { $2.upcase }}".to_sym - end - - def self.test_name(name) - "test_#{sanitize_name(name).gsub(/\s+/,'_')}".to_sym - end - - def self.sanitize_name(name) - name.gsub(/\W+/, ' ').strip - end - - def self.remove_tests(subclass) - subclass.public_instance_methods.grep(/^test_/).each do |meth| - subclass.send(:undef_method, meth.to_sym) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/locals.mab b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/locals.mab deleted file mode 100644 index 36e29e6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/locals.mab +++ /dev/null @@ -1 +0,0 @@ -li foo diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/markaby.mab b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/markaby.mab deleted file mode 100644 index 45f3fe4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/markaby.mab +++ /dev/null @@ -1 +0,0 @@ -text "hello from markaby!" diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/markaby_other_static.mab b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/markaby_other_static.mab deleted file mode 100644 index 75c03fd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/markaby_other_static.mab +++ /dev/null @@ -1 +0,0 @@ -text "_why?" diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/render_twice.mab b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/render_twice.mab deleted file mode 100644 index f350322..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/render_twice.mab +++ /dev/null @@ -1 +0,0 @@ -text "foo" diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/scope.mab b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/scope.mab deleted file mode 100644 index 36e29e6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/scope.mab +++ /dev/null @@ -1 +0,0 @@ -li foo diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/yielding.mab b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/yielding.mab deleted file mode 100644 index 6e95a1b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/markaby/yielding.mab +++ /dev/null @@ -1,2 +0,0 @@ -text("Hey ") -yield diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_asciidoctor_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_asciidoctor_test.rb deleted file mode 100644 index 27fccdc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_asciidoctor_test.rb +++ /dev/null @@ -1,44 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'asciidoctor' - - class AsciidoctorTemplateTest < Test::Unit::TestCase - HTML5_OUTPUT = "

Hello World!

" - DOCBOOK_OUTPUT = "
Hello World!
" - - def strip_space(str) - str.gsub(/>\s+<').strip - end - - test "registered for '.ad' files" do - assert Tilt.mappings['ad'].include?(Tilt::AsciidoctorTemplate) - end - - test "registered for '.adoc' files" do - assert Tilt.mappings['adoc'].include?(Tilt::AsciidoctorTemplate) - end - - test "registered for '.asciidoc' files" do - assert Tilt.mappings['asciidoc'].include?(Tilt::AsciidoctorTemplate) - end - - test "preparing and evaluating html5 templates on #render" do - template = Tilt::AsciidoctorTemplate.new(:attributes => {"backend" => 'html5'}) { |t| "== Hello World!" } - assert_equal HTML5_OUTPUT, strip_space(template.render) - end - - test "preparing and evaluating docbook templates on #render" do - template = Tilt::AsciidoctorTemplate.new(:attributes => {"backend" => 'docbook'}) { |t| "== Hello World!" } - assert_equal DOCBOOK_OUTPUT, strip_space(template.render) - end - - test "can be rendered more than once" do - template = Tilt::AsciidoctorTemplate.new(:attributes => {"backend" => 'html5'}) { |t| "== Hello World!" } - 3.times { assert_equal HTML5_OUTPUT, strip_space(template.render) } - end - end -rescue LoadError => boom - warn "Tilt::AsciidoctorTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_blueclothtemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_blueclothtemplate_test.rb deleted file mode 100644 index 1952ef9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_blueclothtemplate_test.rb +++ /dev/null @@ -1,45 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'bluecloth' - - class BlueClothTemplateTest < Test::Unit::TestCase - test "registered for '.md' files" do - assert Tilt.mappings['md'].include?(Tilt::BlueClothTemplate) - end - - test "registered for '.mkd' files" do - assert Tilt.mappings['mkd'].include?(Tilt::BlueClothTemplate) - end - - test "registered for '.markdown' files" do - assert Tilt.mappings['markdown'].include?(Tilt::BlueClothTemplate) - end - - test "preparing and evaluating templates on #render" do - template = Tilt::BlueClothTemplate.new { |t| "# Hello World!" } - assert_equal "

Hello World!

", template.render - end - - test "can be rendered more than once" do - template = Tilt::BlueClothTemplate.new { |t| "# Hello World!" } - 3.times { assert_equal "

Hello World!

", template.render } - end - - test "smartypants when :smart is set" do - template = Tilt::BlueClothTemplate.new(:smartypants => true) { |t| - "OKAY -- 'Smarty Pants'" } - assert_equal "

OKAY — ‘Smarty Pants’

", - template.render - end - - test "stripping HTML when :filter_html is set" do - template = Tilt::BlueClothTemplate.new(:escape_html => true) { |t| - "HELLO WORLD" } - assert_equal "

HELLO <blink>WORLD</blink>

", template.render - end - end -rescue LoadError => boom - warn "Tilt::BlueClothTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_buildertemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_buildertemplate_test.rb deleted file mode 100644 index 44d8deb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_buildertemplate_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'builder' - class BuilderTemplateTest < Test::Unit::TestCase - test "registered for '.builder' files" do - assert_equal Tilt::BuilderTemplate, Tilt['test.builder'] - assert_equal Tilt::BuilderTemplate, Tilt['test.xml.builder'] - end - - test "preparing and evaluating the template on #render" do - template = Tilt::BuilderTemplate.new { |t| "xml.em 'Hello World!'" } - assert_equal "Hello World!\n", template.render - end - - test "can be rendered more than once" do - template = Tilt::BuilderTemplate.new { |t| "xml.em 'Hello World!'" } - 3.times { assert_equal "Hello World!\n", template.render } - end - - test "passing locals" do - template = Tilt::BuilderTemplate.new { "xml.em('Hey ' + name + '!')" } - assert_equal "Hey Joe!\n", template.render(Object.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::BuilderTemplate.new { "xml.em('Hey ' + @name + '!')" } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!\n", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::BuilderTemplate.new { "xml.em('Hey ' + yield + '!')" } - 3.times { assert_equal "Hey Joe!\n", template.render { 'Joe' }} - end - - test "block style templates" do - template = - Tilt::BuilderTemplate.new do |t| - lambda { |xml| xml.em('Hey Joe!') } - end - assert_equal "Hey Joe!\n", template.render - end - - test "allows nesting raw XML" do - subtemplate = Tilt::BuilderTemplate.new { "xml.em 'Hello World!'" } - template = Tilt::BuilderTemplate.new { "xml.strong { xml << yield }" } - 3.times do - options = { :xml => Builder::XmlMarkup.new } - assert_equal "\nHello World!\n\n", - template.render(options) { subtemplate.render(options) } - end - end - end -rescue LoadError - warn "Tilt::BuilderTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_cache_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_cache_test.rb deleted file mode 100644 index 8c8e050..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_cache_test.rb +++ /dev/null @@ -1,32 +0,0 @@ -require 'contest' -require 'tilt' - -class TiltCacheTest < Test::Unit::TestCase - setup { @cache = Tilt::Cache.new } - - test "caching with single simple argument to #fetch" do - template = nil - result = @cache.fetch('hello') { template = Tilt::StringTemplate.new {''} } - assert_same template, result - result = @cache.fetch('hello') { fail 'should be cached' } - assert_same template, result - end - - test "caching with multiple complex arguments to #fetch" do - template = nil - result = @cache.fetch('hello', {:foo => 'bar', :baz => 'bizzle'}) { template = Tilt::StringTemplate.new {''} } - assert_same template, result - result = @cache.fetch('hello', {:foo => 'bar', :baz => 'bizzle'}) { fail 'should be cached' } - assert_same template, result - end - - test "clearing the cache with #clear" do - template, other = nil - result = @cache.fetch('hello') { template = Tilt::StringTemplate.new {''} } - assert_same template, result - - @cache.clear - result = @cache.fetch('hello') { other = Tilt::StringTemplate.new {''} } - assert_same other, result - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_coffeescripttemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_coffeescripttemplate_test.rb deleted file mode 100644 index 377b6f7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_coffeescripttemplate_test.rb +++ /dev/null @@ -1,114 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'coffee_script' - - class CoffeeScriptTemplateTest < Test::Unit::TestCase - - unless method_defined?(:assert_not_match) - # assert_not_match is missing on 1.8.7, which uses assert_no_match - def assert_not_match(a, b) - unless a.kind_of?(Regexp) - a = Regexp.new(Regexp.escape(a)) - end - assert_no_match(a,b) - end - end - - test "is registered for '.coffee' files" do - assert_equal Tilt::CoffeeScriptTemplate, Tilt['test.coffee'] - end - - test "bare is disabled by default" do - assert_equal false, Tilt::CoffeeScriptTemplate.default_bare - end - - test "compiles and evaluates the template on #render" do - template = Tilt::CoffeeScriptTemplate.new { |t| "puts 'Hello, World!'\n" } - assert_match "puts('Hello, World!');", template.render - end - - test "can be rendered more than once" do - template = Tilt::CoffeeScriptTemplate.new { |t| "puts 'Hello, World!'\n" } - 3.times { assert_match "puts('Hello, World!');", template.render } - end - - test "disabling coffee-script wrapper" do - str = 'name = "Josh"; puts "Hello #{name}"' - - template = Tilt::CoffeeScriptTemplate.new { str } - assert_match "(function() {", template.render - assert_match "puts(\"Hello \" + name);\n", template.render - - template = Tilt::CoffeeScriptTemplate.new(:bare => true) { str } - assert_not_match "(function() {", template.render - assert_equal "var name;\n\nname = \"Josh\";\n\nputs(\"Hello \" + name);\n", template.render - - template2 = Tilt::CoffeeScriptTemplate.new(:no_wrap => true) { str} - assert_not_match "(function() {", template.render - assert_equal "var name;\n\nname = \"Josh\";\n\nputs(\"Hello \" + name);\n", template.render - end - - context "wrapper globally enabled" do - setup do - @bare = Tilt::CoffeeScriptTemplate.default_bare - Tilt::CoffeeScriptTemplate.default_bare = false - end - - teardown do - Tilt::CoffeeScriptTemplate.default_bare = @bare - end - - test "no options" do - template = Tilt::CoffeeScriptTemplate.new { |t| 'name = "Josh"; puts "Hello, #{name}"' } - assert_match "puts(\"Hello, \" + name);", template.render - assert_match "(function() {", template.render - end - - test "overridden by :bare" do - template = Tilt::CoffeeScriptTemplate.new(:bare => true) { |t| 'name = "Josh"; puts "Hello, #{name}"' } - assert_match "puts(\"Hello, \" + name);", template.render - assert_not_match "(function() {", template.render - end - - test "overridden by :no_wrap" do - template = Tilt::CoffeeScriptTemplate.new(:no_wrap => true) { |t| 'name = "Josh"; puts "Hello, #{name}"' } - assert_match "puts(\"Hello, \" + name);", template.render - assert_not_match "(function() {", template.render - end - end - - context "wrapper globally disabled" do - setup do - @bare = Tilt::CoffeeScriptTemplate.default_bare - Tilt::CoffeeScriptTemplate.default_bare = true - end - - teardown do - Tilt::CoffeeScriptTemplate.default_bare = @bare - end - - test "no options" do - template = Tilt::CoffeeScriptTemplate.new { |t| 'name = "Josh"; puts "Hello, #{name}"' } - assert_match "puts(\"Hello, \" + name);", template.render - assert_not_match "(function() {", template.render - end - - test "overridden by :bare" do - template = Tilt::CoffeeScriptTemplate.new(:bare => false) { |t| 'name = "Josh"; puts "Hello, #{name}"' } - assert_match "puts(\"Hello, \" + name);", template.render - assert_match "(function() {", template.render - end - - test "overridden by :no_wrap" do - template = Tilt::CoffeeScriptTemplate.new(:no_wrap => false) { |t| 'name = "Josh"; puts "Hello, #{name}"' } - assert_match "puts(\"Hello, \" + name);", template.render - assert_match "(function() {", template.render - end - end - end - -rescue LoadError => boom - warn "Tilt::CoffeeScriptTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_compilesite_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_compilesite_test.rb deleted file mode 100644 index 2944c84..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_compilesite_test.rb +++ /dev/null @@ -1,51 +0,0 @@ -require 'contest' -require 'tilt' -require 'thread' - -class CompileSiteTest < Test::Unit::TestCase - def setup - GC.start - end - - class CompilingTemplate < Tilt::Template - def prepare - end - - def precompiled_template(locals) - @data.inspect - end - end - - class Scope - end - - test "compiling template source to a method" do - template = CompilingTemplate.new { |t| "Hello World!" } - template.render(Scope.new) - method = template.send(:compiled_method, []) - assert_kind_of UnboundMethod, method - end - - # This test attempts to surface issues with compiling templates from - # multiple threads. - test "using compiled templates from multiple threads" do - template = CompilingTemplate.new { 'template' } - main_thread = Thread.current - 10.times do |i| - threads = - (1..50).map do |j| - Thread.new { - begin - locals = { "local#{i}" => 'value' } - res = template.render(self, locals) - thread_id = Thread.current.object_id - res = template.render(self, "local#{thread_id.abs.to_s}" => 'value') - rescue => boom - main_thread.raise(boom) - end - } - end - threads.each { |t| t.join } - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_creoletemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_creoletemplate_test.rb deleted file mode 100644 index b4e8098..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_creoletemplate_test.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'creole' - - class CreoleTemplateTest < Test::Unit::TestCase - test "is registered for '.creole' files" do - assert_equal Tilt::CreoleTemplate, Tilt['test.creole'] - end - - test "registered for '.wiki' files" do - assert Tilt.mappings['wiki'].include?(Tilt::CreoleTemplate) - end - - test "compiles and evaluates the template on #render" do - template = Tilt::CreoleTemplate.new { |t| "= Hello World!" } - assert_equal "

Hello World!

", template.render - end - - test "can be rendered more than once" do - template = Tilt::CreoleTemplate.new { |t| "= Hello World!" } - 3.times { assert_equal "

Hello World!

", template.render } - end - end -rescue LoadError => boom - warn "Tilt::CreoleTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_csv_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_csv_test.rb deleted file mode 100644 index c11ce03..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_csv_test.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'contest' -require 'tilt' - -begin - if RUBY_VERSION >= '1.9.0' - require 'csv' - else - require 'fastercsv' - end - - class CSVTemplateTest < Test::Unit::TestCase - - test "registered for '.rcsv' files" do - assert Tilt.mappings['rcsv'].include?(Tilt::CSVTemplate) - end - - test "compiles and evaluates the template on #render" do - template = Tilt::CSVTemplate.new { "csv << ['hello', 'world']" } - assert_equal "hello,world\n", template.render - end - - test "can be rendered more than once" do - template = Tilt::CSVTemplate.new { "csv << [1,2,3]" } - 3.times { assert_equal "1,2,3\n", template.render } - end - - test "can pass locals" do - template = Tilt::CSVTemplate.new { 'csv << [1, name]' } - assert_equal "1,Joe\n", template.render(Object.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::CSVTemplate.new { 'csv << [1, @name]' } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "1,Joe\n", template.render(scope) - end - - test "backtrace file and line reporting" do - data = File.read(__FILE__).split("\n__END__\n").last - template = Tilt::CSVTemplate.new('test.csv') { data } - begin - template.render - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.csv:/).first - assert line, "Backtrace didn't contain test.csv" - file, line, meth = line.split(":") - assert_equal '4', line - end - end - - end - -rescue LoadError => boom - warn "Tilt::CSVTemplate (disabled) please install 'fastercsv' if using ruby 1.8.x" -end - - -__END__ -# header -csv << ['Type', 'Age'] - -raise NameError - -# rows -csv << ['Frog', 2] -csv << ['Cat', 5] \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_erbtemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_erbtemplate_test.rb deleted file mode 100644 index 5faffcb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_erbtemplate_test.rb +++ /dev/null @@ -1,239 +0,0 @@ -# coding: utf-8 -require 'contest' -require 'tilt' -require 'erb' -require 'tempfile' - -class ERBTemplateTest < Test::Unit::TestCase - test "registered for '.erb' files" do - assert Tilt.mappings['erb'].include?(Tilt::ERBTemplate) - end - - test "registered for '.rhtml' files" do - assert Tilt.mappings['rhtml'].include?(Tilt::ERBTemplate) - end - - test "loading and evaluating templates on #render" do - template = Tilt::ERBTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render - end - - test "can be rendered more than once" do - template = Tilt::ERBTemplate.new { |t| "Hello World!" } - 3.times { assert_equal "Hello World!", template.render } - end - - test "passing locals" do - template = Tilt::ERBTemplate.new { 'Hey <%= name %>!' } - assert_equal "Hey Joe!", template.render(Object.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::ERBTemplate.new { 'Hey <%= @name %>!' } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - end - - class MockOutputVariableScope - attr_accessor :exposed_buffer - end - - test "exposing the buffer to the template by default" do - begin - Tilt::ERBTemplate.default_output_variable = '@_out_buf' - template = Tilt::ERBTemplate.new { '<% self.exposed_buffer = @_out_buf %>hey' } - scope = MockOutputVariableScope.new - template.render(scope) - assert_not_nil scope.exposed_buffer - assert_equal scope.exposed_buffer, 'hey' - ensure - Tilt::ERBTemplate.default_output_variable = '_erbout' - end - end - - test "passing a block for yield" do - template = Tilt::ERBTemplate.new { 'Hey <%= yield %>!' } - assert_equal "Hey Joe!", template.render { 'Joe' } - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::ERBTemplate.new('test.erb', 11) { data } - begin - template.render - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.erb:/).first - assert line, "Backtrace didn't contain test.erb" - file, line, meth = line.split(":") - assert_equal '13', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::ERBTemplate.new('test.erb', 1) { data } - begin - template.render(nil, :name => 'Joe', :foo => 'bar') - fail 'should have raised an exception' - rescue => boom - assert_kind_of RuntimeError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.erb', file - assert_equal '6', line - end - end - - test "explicit disabling of trim mode" do - template = Tilt::ERBTemplate.new('test.erb', 1, :trim => false) { "\n<%= 1 + 1 %>\n" } - assert_equal "\n2\n", template.render - end - - test "default stripping trim mode" do - template = Tilt::ERBTemplate.new('test.erb', 1) { "\n<%= 1 + 1 %>\n" } - assert_equal "\n2", template.render - end - - test "stripping trim mode" do - template = Tilt::ERBTemplate.new('test.erb', 1, :trim => '-') { "\n<%= 1 + 1 -%>\n" } - assert_equal "\n2", template.render - end - - test "shorthand whole line syntax trim mode" do - template = Tilt::ERBTemplate.new('test.erb', :trim => '%') { "\n% if true\nhello\n%end\n" } - assert_equal "\nhello\n", template.render - end - - test "using an instance variable as the outvar" do - template = Tilt::ERBTemplate.new(nil, :outvar => '@buf') { "<%= 1 + 1 %>" } - scope = Object.new - scope.instance_variable_set(:@buf, 'original value') - assert_equal '2', template.render(scope) - assert_equal 'original value', scope.instance_variable_get(:@buf) - end -end - -class CompiledERBTemplateTest < Test::Unit::TestCase - def teardown - GC.start - end - - class Scope - end - - test "compiling template source to a method" do - template = Tilt::ERBTemplate.new { |t| "Hello World!" } - template.render(Scope.new) - method = template.send(:compiled_method, []) - assert_kind_of UnboundMethod, method - end - - test "loading and evaluating templates on #render" do - template = Tilt::ERBTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render(Scope.new) - assert_equal "Hello World!", template.render(Scope.new) - end - - test "passing locals" do - template = Tilt::ERBTemplate.new { 'Hey <%= name %>!' } - assert_equal "Hey Joe!", template.render(Scope.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::ERBTemplate.new { 'Hey <%= @name %>!' } - scope = Scope.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - scope.instance_variable_set :@name, 'Jane' - assert_equal "Hey Jane!", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::ERBTemplate.new { 'Hey <%= yield %>!' } - assert_equal "Hey Joe!", template.render(Scope.new) { 'Joe' } - assert_equal "Hey Jane!", template.render(Scope.new) { 'Jane' } - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::ERBTemplate.new('test.erb', 11) { data } - begin - template.render(Scope.new) - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.erb:/).first - assert line, "Backtrace didn't contain test.erb" - file, line, meth = line.split(":") - assert_equal '13', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::ERBTemplate.new('test.erb') { data } - begin - template.render(Scope.new, :name => 'Joe', :foo => 'bar') - fail 'should have raised an exception' - rescue => boom - assert_kind_of RuntimeError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.erb', file - assert_equal '6', line - end - end - - test "default stripping trim mode" do - template = Tilt::ERBTemplate.new('test.erb') { "\n<%= 1 + 1 %>\n" } - assert_equal "\n2", template.render(Scope.new) - end - - test "stripping trim mode" do - template = Tilt::ERBTemplate.new('test.erb', :trim => '-') { "\n<%= 1 + 1 -%>\n" } - assert_equal "\n2", template.render(Scope.new) - end - - test "shorthand whole line syntax trim mode" do - template = Tilt::ERBTemplate.new('test.erb', :trim => '%') { "\n% if true\nhello\n%end\n" } - assert_equal "\nhello\n", template.render(Scope.new) - end - - test "encoding with magic comment" do - f = Tempfile.open("template") - f.puts('<%# coding: UTF-8 %>') - f.puts('ふが <%= @hoge %>') - f.close() - @hoge = "ほげ" - erb = Tilt::ERBTemplate.new(f.path) - 3.times { erb.render(self) } - f.delete - end - - test "encoding with :default_encoding" do - f = Tempfile.open("template") - f.puts('ふが <%= @hoge %>') - f.close() - @hoge = "ほげ" - erb = Tilt::ERBTemplate.new(f.path, :default_encoding => 'UTF-8') - 3.times { erb.render(self) } - f.delete - end -end - -__END__ - - -

Hey <%= name %>!

- - -

<% fail %>

- - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_erubistemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_erubistemplate_test.rb deleted file mode 100644 index f908c0f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_erubistemplate_test.rb +++ /dev/null @@ -1,151 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'erubis' - class ErubisTemplateTest < Test::Unit::TestCase - test "registered for '.erubis' files" do - assert_equal Tilt::ErubisTemplate, Tilt['test.erubis'] - assert_equal Tilt::ErubisTemplate, Tilt['test.html.erubis'] - end - - test "registered above ERB" do - %w[erb rhtml].each do |ext| - mappings = Tilt.mappings[ext] - erubis_idx = mappings.index(Tilt::ErubisTemplate) - erb_idx = mappings.index(Tilt::ERBTemplate) - assert erubis_idx < erb_idx, - "#{erubis_idx} should be lower than #{erb_idx}" - end - end - - test "preparing and evaluating templates on #render" do - template = Tilt::ErubisTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render - end - - test "can be rendered more than once" do - template = Tilt::ErubisTemplate.new { |t| "Hello World!" } - 3.times { assert_equal "Hello World!", template.render } - end - - test "passing locals" do - template = Tilt::ErubisTemplate.new { 'Hey <%= name %>!' } - assert_equal "Hey Joe!", template.render(Object.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::ErubisTemplate.new { 'Hey <%= @name %>!' } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - end - - class MockOutputVariableScope - attr_accessor :exposed_buffer - end - - test "exposing the buffer to the template by default" do - begin - Tilt::ErubisTemplate.default_output_variable = '@_out_buf' - template = Tilt::ErubisTemplate.new { '<% self.exposed_buffer = @_out_buf %>hey' } - scope = MockOutputVariableScope.new - template.render(scope) - assert_not_nil scope.exposed_buffer - assert_equal scope.exposed_buffer, 'hey' - ensure - Tilt::ErubisTemplate.default_output_variable = '_erbout' - end - end - - test "passing a block for yield" do - template = Tilt::ErubisTemplate.new { 'Hey <%= yield %>!' } - assert_equal "Hey Joe!", template.render { 'Joe' } - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::ErubisTemplate.new('test.erubis', 11) { data } - begin - template.render - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.erubis:/).first - assert line, "Backtrace didn't contain test.erubis" - file, line, meth = line.split(":") - assert_equal '13', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::ErubisTemplate.new('test.erubis', 1) { data } - begin - template.render(nil, :name => 'Joe', :foo => 'bar') - fail 'should have raised an exception' - rescue => boom - assert_kind_of RuntimeError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.erubis', file - assert_equal '6', line - end - end - - test "erubis template options" do - template = Tilt::ErubisTemplate.new(nil, :pattern => '\{% %\}') { 'Hey {%= @name %}!' } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - end - - test "using an instance variable as the outvar" do - template = Tilt::ErubisTemplate.new(nil, :outvar => '@buf') { "<%= 1 + 1 %>" } - scope = Object.new - scope.instance_variable_set(:@buf, 'original value') - assert_equal '2', template.render(scope) - assert_equal 'original value', scope.instance_variable_get(:@buf) - end - - test "using Erubis::EscapedEruby subclass via :engine_class option" do - template = Tilt::ErubisTemplate.new(nil, :engine_class => ::Erubis::EscapedEruby) { |t| %(<%= "

Hello World!

" %>) } - assert_equal "<p>Hello World!</p>", template.render - end - - test "using :escape_html => true option" do - template = Tilt::ErubisTemplate.new(nil, :escape_html => true) { |t| %(<%= "

Hello World!

" %>) } - assert_equal "<p>Hello World!</p>", template.render - end - - test "using :escape_html => false option" do - template = Tilt::ErubisTemplate.new(nil, :escape_html => false) { |t| %(<%= "

Hello World!

" %>) } - assert_equal "

Hello World!

", template.render - end - - test "erubis default does not escape html" do - template = Tilt::ErubisTemplate.new { |t| %(<%= "

Hello World!

" %>) } - assert_equal "

Hello World!

", template.render - end - - test "does not modify options argument" do - options_hash = {:escape_html => true} - template = Tilt::ErubisTemplate.new(nil, options_hash) { |t| "Hello World!" } - assert_equal({:escape_html => true}, options_hash) - end - end -rescue LoadError => boom - warn "Tilt::ErubisTemplate (disabled)" -end - -__END__ - - -

Hey <%= name %>!

- - -

<% fail %>

- - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_etannitemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_etannitemplate_test.rb deleted file mode 100644 index 32c81e8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_etannitemplate_test.rb +++ /dev/null @@ -1,173 +0,0 @@ -require 'contest' -require 'tilt' - -class EtanniTemplateTest < Test::Unit::TestCase - test "registered for '.etn' files" do - assert_equal Tilt::EtanniTemplate, Tilt['test.etn'] - end - - test "registered for '.etanni' files" do - assert_equal Tilt::EtanniTemplate, Tilt['test.etanni'] - end - - test "loading and evaluating templates on #render" do - template = Tilt::EtanniTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render - end - - test "can be rendered more than once" do - template = Tilt::EtanniTemplate.new { |t| "Hello World!" } - 3.times { assert_equal "Hello World!", template.render } - end - - test "passing locals" do - template = Tilt::EtanniTemplate.new { 'Hey #{name}!' } - assert_equal "Hey Joe!", template.render(Object.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::EtanniTemplate.new { 'Hey #{@name}!' } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::EtanniTemplate.new { 'Hey #{yield}!' } - assert_equal "Hey Joe!", template.render { 'Joe' } - assert_equal "Hey Moe!", template.render { 'Moe' } - end - - test "multiline templates" do - template = Tilt::EtanniTemplate.new { "Hello\nWorld!\n" } - assert_equal "Hello\nWorld!", template.render - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::EtanniTemplate.new('test.etn', 11) { data } - begin - template.render - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.etn:/).first - assert line, "Backtrace didn't contain test.etn" - file, line, meth = line.split(":") - assert_equal '13', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::EtanniTemplate.new('test.etn', 1) { data } - begin - template.render(nil, :name => 'Joe', :foo => 'bar') - fail 'should have raised an exception' - rescue => boom - assert_kind_of RuntimeError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.etn', file - assert_equal '6', line - end - end -end - - -class CompiledEtanniTemplateTest < Test::Unit::TestCase - def teardown - GC.start - end - - class Scope - end - - test "compiling template source to a method" do - template = Tilt::EtanniTemplate.new { |t| "Hello World!" } - template.render(Scope.new) - method = template.send(:compiled_method, []) - assert_kind_of UnboundMethod, method - end - - test "loading and evaluating templates on #render" do - template = Tilt::EtanniTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render(Scope.new) - end - - test "passing locals" do - template = Tilt::EtanniTemplate.new { 'Hey #{name}!' } - assert_equal "Hey Joe!", template.render(Scope.new, :name => 'Joe') - assert_equal "Hey Moe!", template.render(Scope.new, :name => 'Moe') - end - - test "evaluating in an object scope" do - template = Tilt::EtanniTemplate.new { 'Hey #{@name}!' } - scope = Scope.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - scope.instance_variable_set :@name, 'Moe' - assert_equal "Hey Moe!", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::EtanniTemplate.new { 'Hey #{yield}!' } - assert_equal "Hey Joe!", template.render(Scope.new) { 'Joe' } - assert_equal "Hey Moe!", template.render(Scope.new) { 'Moe' } - end - - test "multiline templates" do - template = Tilt::EtanniTemplate.new { "Hello\nWorld!\n" } - assert_equal "Hello\nWorld!", template.render(Scope.new) - end - - test "template with '}'" do - template = Tilt::EtanniTemplate.new { "Hello }" } - assert_equal "Hello }", template.render - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::EtanniTemplate.new('test.etn', 11) { data } - begin - template.render(Scope.new) - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.first - line = boom.backtrace.grep(/^test\.etn:/).first - assert line, "Backtrace didn't contain test.etn" - file, line, meth = line.split(":") - assert_equal '13', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::EtanniTemplate.new('test.etn') { data } - begin - template.render(Scope.new, :name => 'Joe', :foo => 'bar') - fail 'should have raised an exception' - rescue => boom - assert_kind_of RuntimeError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.etn', file - assert_equal '6', line - end - end -end - -__END__ - - -

Hey #{name}!

- - -

#{fail}

- - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_fallback_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_fallback_test.rb deleted file mode 100644 index 067fae1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_fallback_test.rb +++ /dev/null @@ -1,122 +0,0 @@ -require 'contest' -require 'tilt' - -class TiltFallbackTest < Test::Unit::TestCase - class FailTemplate < Tilt::Template - def self.engine_initialized?; false end - def prepare; end - - def initialize_engine - raise LoadError, "can't load #{self.class}" - end - end - - class WinTemplate < Tilt::Template - def self.engine_initialized?; true end - def prepare; end - end - - FailTemplate2 = Class.new(FailTemplate) - WinTemplate2 = Class.new(WinTemplate) - - def set_ivar(obj, name, value) - obj.instance_variable_set("@#{name}", value) - end - - def clear_ivar(obj, name) - ivar = "@#{name}" - value = obj.instance_variable_get(ivar) - ensure - obj.instance_variable_set(ivar, value.dup.clear) - end - - setup do - # Make sure every test have no mappings. - @p = clear_ivar(Tilt, :preferred_mappings) - @t = clear_ivar(Tilt, :template_mappings) - end - - teardown do - set_ivar(Tilt, :preferred_mappings, @p) - set_ivar(Tilt, :template_mappings, @t) - end - - test "returns nil on unregistered extensions" do - template = Tilt["md"] - assert_equal nil, template - end - - test "returns the last registered template" do - Tilt.register("md", WinTemplate) - Tilt.register("md", WinTemplate2) - - template = Tilt["md"] - assert_equal WinTemplate2, template - end - - test "returns the last registered working template" do - Tilt.register("md", WinTemplate) - Tilt.register("md", FailTemplate) - - template = Tilt["md"] - assert_equal WinTemplate, template - end - - test "if every template fails, raise the exception from the first template" do - Tilt.register("md", FailTemplate) - Tilt.register("md", FailTemplate2) - - exc = assert_raise(LoadError) { Tilt["md"] } - assert_match /FailTemplate2/, exc.message - end - - test ".prefer should also register the template" do - Tilt.prefer(WinTemplate, "md") - assert Tilt.registered?("md") - end - - test ".prefer always win" do - Tilt.register("md", FailTemplate) - Tilt.register("md", WinTemplate) - Tilt.prefer(FailTemplate, "md") - - template = Tilt["md"] - assert_equal FailTemplate, template - end - - test ".prefer accepts multiple extensions" do - extensions = %w[md mkd markdown] - Tilt.prefer(FailTemplate, *extensions) - - extensions.each do |ext| - template = Tilt[ext] - assert_equal FailTemplate, template - end - end - - test ".prefer with no extension should use already registered extensions" do - extensions = %w[md mkd markdown] - - extensions.each do |ext| - Tilt.register(ext, FailTemplate) - Tilt.register(ext, WinTemplate) - end - - Tilt.prefer(FailTemplate) - - extensions.each do |ext| - template = Tilt[ext] - assert_equal FailTemplate, template - end - end - - test ".prefer should only override extensions the preferred library is registered for" do - Tilt.register("md", WinTemplate) - Tilt.register("mkd", FailTemplate) - Tilt.register("mkd", WinTemplate) - Tilt.prefer(FailTemplate) - assert_equal FailTemplate, Tilt["mkd"] - assert_equal WinTemplate, Tilt["md"] - end -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_hamltemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_hamltemplate_test.rb deleted file mode 100644 index 8466675..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_hamltemplate_test.rb +++ /dev/null @@ -1,144 +0,0 @@ -require 'contest' -require 'tilt' - -begin - class ::MockError < NameError - end - - require 'haml' - - class HamlTemplateTest < Test::Unit::TestCase - test "registered for '.haml' files" do - assert_equal Tilt::HamlTemplate, Tilt['test.haml'] - end - - test "preparing and evaluating templates on #render" do - template = Tilt::HamlTemplate.new { |t| "%p Hello World!" } - assert_equal "

Hello World!

\n", template.render - end - - test "can be rendered more than once" do - template = Tilt::HamlTemplate.new { |t| "%p Hello World!" } - 3.times { assert_equal "

Hello World!

\n", template.render } - end - - test "passing locals" do - template = Tilt::HamlTemplate.new { "%p= 'Hey ' + name + '!'" } - assert_equal "

Hey Joe!

\n", template.render(Object.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::HamlTemplate.new { "%p= 'Hey ' + @name + '!'" } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "

Hey Joe!

\n", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::HamlTemplate.new { "%p= 'Hey ' + yield + '!'" } - assert_equal "

Hey Joe!

\n", template.render { 'Joe' } - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?% - template = Tilt::HamlTemplate.new('test.haml', 10) { data } - begin - template.render - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.haml:/).first - assert line, "Backtrace didn't contain test.haml" - file, line, meth = line.split(":") - assert_equal '12', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?% - template = Tilt::HamlTemplate.new('test.haml') { data } - begin - res = template.render(Object.new, :name => 'Joe', :foo => 'bar') - rescue => boom - assert_kind_of MockError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.haml', file - assert_equal '5', line - end - end - end - - class CompiledHamlTemplateTest < Test::Unit::TestCase - class Scope - end - - test "compiling template source to a method" do - template = Tilt::HamlTemplate.new { |t| "Hello World!" } - template.render(Scope.new) - method = template.send(:compiled_method, []) - assert_kind_of UnboundMethod, method - end - - test "passing locals" do - template = Tilt::HamlTemplate.new { "%p= 'Hey ' + name + '!'" } - assert_equal "

Hey Joe!

\n", template.render(Scope.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::HamlTemplate.new { "%p= 'Hey ' + @name + '!'" } - scope = Scope.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "

Hey Joe!

\n", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::HamlTemplate.new { "%p= 'Hey ' + yield + '!'" } - assert_equal "

Hey Joe!

\n", template.render(Scope.new) { 'Joe' } - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?% - template = Tilt::HamlTemplate.new('test.haml', 10) { data } - begin - template.render(Scope.new) - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.haml:/).first - assert line, "Backtrace didn't contain test.haml" - file, line, meth = line.split(":") - assert_equal '12', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?% - template = Tilt::HamlTemplate.new('test.haml') { data } - begin - res = template.render(Scope.new, :name => 'Joe', :foo => 'bar') - rescue => boom - assert_kind_of MockError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.haml', file - assert_equal '5', line - end - end - end -rescue LoadError => boom - warn "Tilt::HamlTemplate (disabled)" -end - -__END__ -%html - %body - %h1= "Hey #{name}" - - = raise MockError - - %p we never get here diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_kramdown_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_kramdown_test.rb deleted file mode 100644 index c031709..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_kramdown_test.rb +++ /dev/null @@ -1,42 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'kramdown' - - class MarukuTemplateTest < Test::Unit::TestCase - test "registered for '.md' files" do - assert Tilt.mappings['md'].include?(Tilt::KramdownTemplate) - end - - test "registered for '.mkd' files" do - assert Tilt.mappings['mkd'].include?(Tilt::KramdownTemplate) - end - - test "registered for '.markdown' files" do - assert Tilt.mappings['markdown'].include?(Tilt::KramdownTemplate) - end - - test "registered above MarukuTemplate" do - %w[md mkd markdown].each do |ext| - mappings = Tilt.mappings[ext] - kram_idx = mappings.index(Tilt::KramdownTemplate) - maru_idx = mappings.index(Tilt::MarukuTemplate) - assert kram_idx < maru_idx, - "#{kram_idx} should be lower than #{maru_idx}" - end - end - - test "preparing and evaluating templates on #render" do - template = Tilt::KramdownTemplate.new { |t| "# Hello World!" } - assert_equal "

Hello World!

", template.render - end - - test "can be rendered more than once" do - template = Tilt::KramdownTemplate.new { |t| "# Hello World!" } - 3.times { assert_equal "

Hello World!

", template.render } - end - end -rescue LoadError => boom - warn "Tilt::KramdownTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_lesstemplate_test.less b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_lesstemplate_test.less deleted file mode 100644 index 3e1dafa..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_lesstemplate_test.less +++ /dev/null @@ -1 +0,0 @@ -@text-color: #ffc0cb; \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_lesstemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_lesstemplate_test.rb deleted file mode 100644 index 9b9a3e8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_lesstemplate_test.rb +++ /dev/null @@ -1,42 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'pathname' - require 'less' - - class LessTemplateTest < Test::Unit::TestCase - def assert_similar(a, b) - assert_equal a.gsub(/\s+/m, ' '), b.gsub(/\s+/m, ' ') - end - - test "is registered for '.less' files" do - assert_equal Tilt::LessTemplate, Tilt['test.less'] - end - - test "compiles and evaluates the template on #render" do - template = Tilt::LessTemplate.new { |t| ".bg { background-color: #0000ff; } \n#main\n { .bg; }\n" } - assert_similar ".bg {\n background-color: #0000ff;\n}\n#main {\n background-color: #0000ff;\n}\n", template.render - end - - test "can be rendered more than once" do - template = Tilt::LessTemplate.new { |t| ".bg { background-color: #0000ff; } \n#main\n { .bg; }\n" } - 3.times { assert_similar ".bg {\n background-color: #0000ff;\n}\n#main {\n background-color: #0000ff;\n}\n", template.render } - end - - test "can be passed a load path" do - template = Tilt::LessTemplate.new({ - :paths => [Pathname(__FILE__).dirname] - }) { - <<-EOLESS - @import 'tilt_lesstemplate_test.less'; - .bg {background-color: @text-color;} - EOLESS - } - assert_similar ".bg {\n background-color: #ffc0cb;\n}\n", template.render - end - end - -rescue LoadError => boom - warn "Tilt::LessTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_liquidtemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_liquidtemplate_test.rb deleted file mode 100644 index 13db928..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_liquidtemplate_test.rb +++ /dev/null @@ -1,78 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'liquid' - - class LiquidTemplateTest < Test::Unit::TestCase - test "registered for '.liquid' files" do - assert_equal Tilt::LiquidTemplate, Tilt['test.liquid'] - end - - test "preparing and evaluating templates on #render" do - template = Tilt::LiquidTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render - end - - test "can be rendered more than once" do - template = Tilt::LiquidTemplate.new { |t| "Hello World!" } - 3.times { assert_equal "Hello World!", template.render } - end - - test "passing locals" do - template = Tilt::LiquidTemplate.new { "Hey {{ name }}!" } - assert_equal "Hey Joe!", template.render(nil, :name => 'Joe') - end - - # Object's passed as "scope" to LiquidTemplate may respond to - # #to_h with a Hash. The Hash's contents are merged underneath - # Tilt locals. - class ExampleLiquidScope - def to_h - { :beer => 'wet', :whisky => 'wetter' } - end - end - - test "combining scope and locals when scope responds to #to_h" do - template = - Tilt::LiquidTemplate.new { - 'Beer is {{ beer }} but Whisky is {{ whisky }}.' - } - scope = ExampleLiquidScope.new - assert_equal "Beer is wet but Whisky is wetter.", template.render(scope) - end - - test "precedence when locals and scope define same variables" do - template = - Tilt::LiquidTemplate.new { - 'Beer is {{ beer }} but Whisky is {{ whisky }}.' - } - scope = ExampleLiquidScope.new - assert_equal "Beer is great but Whisky is greater.", - template.render(scope, :beer => 'great', :whisky => 'greater') - end - - # Object's passed as "scope" to LiquidTemplate that do not - # respond to #to_h are silently ignored. - class ExampleIgnoredLiquidScope - end - - test "handling scopes that do not respond to #to_h" do - template = Tilt::LiquidTemplate.new { 'Whisky' } - scope = ExampleIgnoredLiquidScope.new - assert_equal "Whisky", template.render(scope) - end - - test "passing a block for yield" do - template = - Tilt::LiquidTemplate.new { - 'Beer is {{ yield }} but Whisky is {{ content }}ter.' - } - assert_equal "Beer is wet but Whisky is wetter.", - template.render({}) { 'wet' } - end - end - -rescue LoadError => boom - warn "Tilt::LiquidTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_markaby_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_markaby_test.rb deleted file mode 100644 index 392abac..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_markaby_test.rb +++ /dev/null @@ -1,88 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'markaby' - - class MarkabyTiltTest < Test::Unit::TestCase - def setup - @block = lambda do |t| - File.read(File.dirname(__FILE__) + "/#{t.file}") - end - end - - test "should be able to render a markaby template with static html" do - tilt = Tilt::MarkabyTemplate.new("markaby/markaby.mab", &@block) - assert_equal "hello from markaby!", tilt.render - end - - test "should use the contents of the template" do - tilt = ::Tilt::MarkabyTemplate.new("markaby/markaby_other_static.mab", &@block) - assert_equal "_why?", tilt.render - end - - test "should render from a string (given as data)" do - tilt = ::Tilt::MarkabyTemplate.new { "html do; end" } - assert_equal "", tilt.render - end - - test "can be rendered more than once" do - tilt = ::Tilt::MarkabyTemplate.new { "html do; end" } - 3.times { assert_equal "", tilt.render } - end - - test "should evaluate a template file in the scope given" do - scope = Object.new - def scope.foo - "bar" - end - - tilt = ::Tilt::MarkabyTemplate.new("markaby/scope.mab", &@block) - assert_equal "
  • bar
  • ", tilt.render(scope) - end - - test "should pass locals to the template" do - tilt = ::Tilt::MarkabyTemplate.new("markaby/locals.mab", &@block) - assert_equal "
  • bar
  • ", tilt.render(Object.new, { :foo => "bar" }) - end - - test "should yield to the block given" do - tilt = ::Tilt::MarkabyTemplate.new("markaby/yielding.mab", &@block) - eval_scope = Markaby::Builder.new - - output = tilt.render(Object.new, {}) do - text("Joe") - end - - assert_equal "Hey Joe", output - end - - test "should be able to render two templates in a row" do - tilt = ::Tilt::MarkabyTemplate.new("markaby/render_twice.mab", &@block) - - assert_equal "foo", tilt.render - assert_equal "foo", tilt.render - end - - test "should retrieve a Tilt::MarkabyTemplate when calling Tilt['hello.mab']" do - assert_equal Tilt::MarkabyTemplate, ::Tilt['./markaby/markaby.mab'] - end - - test "should return a new instance of the implementation class (when calling Tilt.new)" do - assert ::Tilt.new(File.dirname(__FILE__) + "/markaby/markaby.mab").kind_of?(Tilt::MarkabyTemplate) - end - - test "should be able to evaluate block style templates" do - tilt = Tilt::MarkabyTemplate.new { |t| lambda { h1 "Hello World!" }} - assert_equal "

    Hello World!

    ", tilt.render - end - - test "should pass locals to block style templates" do - tilt = Tilt::MarkabyTemplate.new { |t| lambda { h1 "Hello #{name}!" }} - assert_equal "

    Hello _why!

    ", tilt.render(nil, :name => "_why") - end - end - -rescue LoadError => boom - warn "Tilt::MarkabyTemplate (disabled)" -end \ No newline at end of file diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_markdown_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_markdown_test.rb deleted file mode 100644 index 9e864a7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_markdown_test.rb +++ /dev/null @@ -1,172 +0,0 @@ -# coding: UTF-8 -require 'tilt' - -begin -require 'nokogiri' - -module MarkdownTests - def self.included(mod) - class << mod - def template(t = nil) - t.nil? ? @template : @template = t - end - end - end - - def render(text, options = {}) - self.class.template.new(options) { text }.render - end - - def normalize(html) - Nokogiri::HTML.fragment(html).to_s.strip - end - - def nrender(text, options = {}) - html = render(text, options) - html.encode!("UTF-8") if html.respond_to?(:encode) - normalize(html) - end - - def test_escape_html - html = nrender "Hello World" - assert_equal "

    Hello World

    ", html - end - - def test_escape_html_false - html = nrender "Hello World", :escape_html => false - assert_equal "

    Hello World

    ", html - end - - def test_escape_html_true - if self.class.template == Tilt::RedcarpetTemplate - flunk "redcarpet doesn't support :escape_html yet" - end - html = nrender "Hello World", :escape_html => true - assert_equal "

    Hello <b>World</b>

    ", html - end - - def test_smart_quotes - html = nrender 'Hello "World"' - assert_equal '

    Hello "World"

    ', html - end - - def test_smart_quotes_false - html = nrender 'Hello "World"', :smartypants => false - assert_equal '

    Hello "World"

    ', html - end - - def test_smart_quotes_true - html = nrender 'Hello "World"', :smartypants => true - assert_equal '

    Hello “World”

    ', html - end - - def test_smarty_pants - html = nrender "Hello ``World'' -- This is --- a test ..." - assert_equal "

    Hello ``World'' -- This is --- a test ...

    ", html - end - - def test_smarty_pants_false - html = nrender "Hello ``World'' -- This is --- a test ...", :smartypants => false - assert_equal "

    Hello ``World'' -- This is --- a test ...

    ", html - end - - def test_smarty_pants_true - html = nrender "Hello ``World'' -- This is --- a test ...", :smartypants => true - assert_equal "

    Hello “World” — This is —– a test …

    ", html - end -end - -begin - require 'rdiscount' - - class MarkdownRDiscountTest < Test::Unit::TestCase - include MarkdownTests - template Tilt::RDiscountTemplate - end -rescue LoadError => boom - # It should already be warned in the main tests -end - -begin - require 'redcarpet' - - class MarkdownRedcarpetTest < Test::Unit::TestCase - include MarkdownTests - template Tilt::RedcarpetTemplate - # Doesn't support escaping - undef test_escape_html_true - - def test_smarty_pants_true - html = nrender "Hello ``World'' -- This is --- a test ...", :smartypants => true - assert_equal "

    Hello “World'' – This is — a test …

    ", html - end - - def test_fenced_code_blocks_with_lang - code = <<-COD.gsub(/^\s+/,"") - ```ruby - puts "hello world" - ``` - COD - - html = nrender code, :fenced_code_blocks => true - assert_equal %Q{
    puts "hello world"\n
    }, html - end - end -rescue LoadError => boom - # It should already be warned in the main tests -end - -begin - require 'bluecloth' - - class MarkdownBlueClothTest < Test::Unit::TestCase - include MarkdownTests - template Tilt::BlueClothTemplate - end -rescue LoadError => boom - # It should already be warned in the main tests -end - -begin - require 'kramdown' - - class MarkdownKramdownTest < Test::Unit::TestCase - include MarkdownTests - template Tilt::KramdownTemplate - # Doesn't support escaping - undef test_escape_html_true - # Smarty Pants is *always* on, but doesn't support it fully - undef test_smarty_pants - undef test_smarty_pants_false - undef test_smarty_pants_true - end -rescue LoadError => boom - # It should already be warned in the main tests -end - - -begin - require 'maruku' - - class MarkdownMarukuTest < Test::Unit::TestCase - include MarkdownTests - template Tilt::MarukuTemplate - # Doesn't support escaping - undef test_escape_html_true - # Doesn't support Smarty Pants, and even fails on ``Foobar'' - undef test_smarty_pants - undef test_smarty_pants_false - undef test_smarty_pants_true - # Smart Quotes is always on - undef test_smart_quotes - undef test_smart_quotes_false - end -rescue LoadError => boom - # It should already be warned in the main tests -end - -rescue LoadError - warn "Markdown tests need Nokogiri" -end - - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_marukutemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_marukutemplate_test.rb deleted file mode 100644 index 1be67db..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_marukutemplate_test.rb +++ /dev/null @@ -1,48 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'maruku' - - class MarukuTemplateTest < Test::Unit::TestCase - test "registered for '.md' files" do - assert Tilt.mappings['md'].include?(Tilt::MarukuTemplate) - end - - test "registered for '.mkd' files" do - assert Tilt.mappings['mkd'].include?(Tilt::MarukuTemplate) - end - - test "registered for '.markdown' files" do - assert Tilt.mappings['markdown'].include?(Tilt::MarukuTemplate) - end - - test "registered below Kramdown" do - %w[md mkd markdown].each do |ext| - mappings = Tilt.mappings[ext] - kram_idx = mappings.index(Tilt::KramdownTemplate) - maru_idx = mappings.index(Tilt::MarukuTemplate) - assert maru_idx > kram_idx, - "#{maru_idx} should be higher than #{kram_idx}" - end - end - - test "preparing and evaluating templates on #render" do - template = Tilt::MarukuTemplate.new { |t| "# Hello World!" } - assert_equal "

    Hello World!

    ", template.render - end - - test "can be rendered more than once" do - template = Tilt::MarukuTemplate.new { |t| "# Hello World!" } - 3.times { assert_equal "

    Hello World!

    ", template.render } - end - - test "removes HTML when :filter_html is set" do - template = Tilt::MarukuTemplate.new(:filter_html => true) { |t| - "HELLO WORLD" } - assert_equal "

    HELLO

    ", template.render - end - end -rescue LoadError => boom - warn "Tilt::MarukuTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_nokogiritemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_nokogiritemplate_test.rb deleted file mode 100644 index 22225e8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_nokogiritemplate_test.rb +++ /dev/null @@ -1,87 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'nokogiri' - class NokogiriTemplateTest < Test::Unit::TestCase - test "registered for '.nokogiri' files" do - assert_equal Tilt::NokogiriTemplate, Tilt['test.nokogiri'] - assert_equal Tilt::NokogiriTemplate, Tilt['test.xml.nokogiri'] - end - - test "preparing and evaluating the template on #render" do - template = Tilt::NokogiriTemplate.new { |t| "xml.em 'Hello World!'" } - doc = Nokogiri.XML template.render - assert_equal 'Hello World!', doc.root.text - assert_equal 'em', doc.root.name - end - - test "can be rendered more than once" do - template = Tilt::NokogiriTemplate.new { |t| "xml.em 'Hello World!'" } - 3.times do - doc = Nokogiri.XML template.render - assert_equal 'Hello World!', doc.root.text - assert_equal 'em', doc.root.name - end - end - - test "passing locals" do - template = Tilt::NokogiriTemplate.new { "xml.em('Hey ' + name + '!')" } - doc = Nokogiri.XML template.render(Object.new, :name => 'Joe') - assert_equal 'Hey Joe!', doc.root.text - assert_equal 'em', doc.root.name - end - - test "evaluating in an object scope" do - template = Tilt::NokogiriTemplate.new { "xml.em('Hey ' + @name + '!')" } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - doc = Nokogiri.XML template.render(scope) - assert_equal 'Hey Joe!', doc.root.text - assert_equal 'em', doc.root.name - end - - test "passing a block for yield" do - template = Tilt::NokogiriTemplate.new { "xml.em('Hey ' + yield + '!')" } - 3.times do - doc = Nokogiri.XML template.render { 'Joe' } - assert_equal 'Hey Joe!', doc.root.text - assert_equal 'em', doc.root.name - end - end - - test "block style templates" do - template = - Tilt::NokogiriTemplate.new do |t| - lambda { |xml| xml.em('Hey Joe!') } - end - doc = Nokogiri.XML template.render - assert_equal 'Hey Joe!', doc.root.text - assert_equal 'em', doc.root.name - end - - test "allows nesting raw XML, API-compatible to Builder" do - subtemplate = Tilt::NokogiriTemplate.new { "xml.em 'Hello World!'" } - template = Tilt::NokogiriTemplate.new { "xml.strong { xml << yield }" } - 3.times do - options = { :xml => Nokogiri::XML::Builder.new } - doc = Nokogiri.XML(template.render(options) { subtemplate.render(options) }) - assert_equal 'Hello World!', doc.root.text.strip - assert_equal 'strong', doc.root.name - end - end - - test "doesn't modify self when template is a string" do - template = Tilt::NokogiriTemplate.new { "xml.root { xml.child @hello }" } - scope = Object.new - scope.instance_variable_set(:@hello, "Hello World!") - - 3.times do - doc = Nokogiri.XML(template.render(scope)) - assert_equal "Hello World!", doc.text.strip - end - end - end -rescue LoadError - warn "Tilt::NokogiriTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_radiustemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_radiustemplate_test.rb deleted file mode 100644 index 1db5b4b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_radiustemplate_test.rb +++ /dev/null @@ -1,75 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'radius' - - # Disable radius tests under Ruby versions >= 1.9.1 since it's still buggy. - # Remove when fixed upstream. - raise LoadError if RUBY_VERSION >= "1.9.1" and Radius.version < "0.7" - - class RadiusTemplateTest < Test::Unit::TestCase - test "registered for '.radius' files" do - assert_equal Tilt::RadiusTemplate, Tilt['test.radius'] - end - - test "preparing and evaluating templates on #render" do - template = Tilt::RadiusTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render - end - - test "can be rendered more than once" do - template = Tilt::RadiusTemplate.new { |t| "Hello World!" } - 3.times { assert_equal "Hello World!", template.render } - end - - test "passing locals" do - template = Tilt::RadiusTemplate.new { "Hey !" } - assert_equal "Hey Joe!", template.render(nil, :name => 'Joe') - end - - class ExampleRadiusScope - def beer; 'wet'; end - def whisky; 'wetter'; end - end - - test "combining scope and locals when scope responds" do - template = Tilt::RadiusTemplate.new { - 'Beer is but Whisky is .' - } - scope = ExampleRadiusScope.new - assert_equal "Beer is wet but Whisky is wetter.", template.render(scope) - end - - test "precedence when locals and scope define same variables" do - template = Tilt::RadiusTemplate.new { - 'Beer is but Whisky is .' - } - scope = ExampleRadiusScope.new - assert_equal "Beer is great but Whisky is greater.", - template.render(scope, :beer => 'great', :whisky => 'greater') - end - - #test "handles local scope" do - # beer = 'wet' - # whisky = 'wetter' - # - # template = Tilt::RadiusTemplate.new { - # 'Beer is but Whisky is .' - # } - # assert_equal "Beer is wet but Whisky is wetter.", template.render(self) - #end - - test "passing a block for yield" do - template = Tilt::RadiusTemplate.new { - 'Beer is but Whisky is ter.' - } - assert_equal "Beer is wet but Whisky is wetter.", - template.render({}) { 'wet' } - end - end - -rescue LoadError => boom - warn "Tilt::RadiusTemplate (disabled)" -end - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_rdiscounttemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_rdiscounttemplate_test.rb deleted file mode 100644 index 35ccbaf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_rdiscounttemplate_test.rb +++ /dev/null @@ -1,55 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'rdiscount' - - class RDiscountTemplateTest < Test::Unit::TestCase - test "registered for '.md' files" do - assert Tilt.mappings['md'].include?(Tilt::RDiscountTemplate) - end - - test "registered for '.mkd' files" do - assert Tilt.mappings['mkd'].include?(Tilt::RDiscountTemplate) - end - - test "registered for '.markdown' files" do - assert Tilt.mappings['markdown'].include?(Tilt::RDiscountTemplate) - end - - test "registered above BlueCloth" do - %w[md mkd markdown].each do |ext| - mappings = Tilt.mappings[ext] - blue_idx = mappings.index(Tilt::BlueClothTemplate) - rdis_idx = mappings.index(Tilt::RDiscountTemplate) - assert rdis_idx < blue_idx, - "#{rdis_idx} should be lower than #{blue_idx}" - end - end - - test "preparing and evaluating templates on #render" do - template = Tilt::RDiscountTemplate.new { |t| "# Hello World!" } - assert_equal "

    Hello World!

    \n", template.render - end - - test "can be rendered more than once" do - template = Tilt::RDiscountTemplate.new { |t| "# Hello World!" } - 3.times { assert_equal "

    Hello World!

    \n", template.render } - end - - test "smartypants when :smart is set" do - template = Tilt::RDiscountTemplate.new(:smart => true) { |t| - "OKAY -- 'Smarty Pants'" } - assert_equal "

    OKAY — ‘Smarty Pants’

    \n", - template.render - end - - test "stripping HTML when :filter_html is set" do - template = Tilt::RDiscountTemplate.new(:filter_html => true) { |t| - "HELLO WORLD" } - assert_equal "

    HELLO <blink>WORLD</blink>

    \n", template.render - end - end -rescue LoadError => boom - warn "Tilt::RDiscountTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_rdoctemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_rdoctemplate_test.rb deleted file mode 100644 index 5a729ea..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_rdoctemplate_test.rb +++ /dev/null @@ -1,31 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'rdoc' - require 'rdoc/markup' - require 'rdoc/markup/to_html' - class RDocTemplateTest < Test::Unit::TestCase - test "is registered for '.rdoc' files" do - assert_equal Tilt::RDocTemplate, Tilt['test.rdoc'] - end - - test "preparing and evaluating the template with #render" do - template = Tilt::RDocTemplate.new { |t| "= Hello World!" } - result = template.render.strip - assert_match /

    Hello World!Hello World! boom - warn "Tilt::RDocTemplate (disabled) [#{boom}]" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_redcarpettemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_redcarpettemplate_test.rb deleted file mode 100644 index f675b47..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_redcarpettemplate_test.rb +++ /dev/null @@ -1,71 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'redcarpet' - - class RedcarpetTemplateTest < Test::Unit::TestCase - test "registered for '.md' files" do - assert Tilt.mappings['md'].include?(Tilt::RedcarpetTemplate) - end - - test "registered for '.mkd' files" do - assert Tilt.mappings['mkd'].include?(Tilt::RedcarpetTemplate) - end - - test "registered for '.markdown' files" do - assert Tilt.mappings['markdown'].include?(Tilt::RedcarpetTemplate) - end - - test "registered above BlueCloth" do - %w[md mkd markdown].each do |ext| - mappings = Tilt.mappings[ext] - blue_idx = mappings.index(Tilt::BlueClothTemplate) - redc_idx = mappings.index(Tilt::RedcarpetTemplate) - assert redc_idx < blue_idx, - "#{redc_idx} should be lower than #{blue_idx}" - end - end - - test "registered above RDiscount" do - %w[md mkd markdown].each do |ext| - mappings = Tilt.mappings[ext] - rdis_idx = mappings.index(Tilt::RDiscountTemplate) - redc_idx = mappings.index(Tilt::RedcarpetTemplate) - assert redc_idx < rdis_idx, - "#{redc_idx} should be lower than #{rdis_idx}" - end - end - - test "redcarpet2 is our default choice" do - template = Tilt::RedcarpetTemplate.new {} - assert_equal Tilt::RedcarpetTemplate::Redcarpet2, template.prepare.class - end - - test "preparing and evaluating templates on #render" do - template = Tilt::RedcarpetTemplate.new { |t| "# Hello World!" } - assert_equal "

    Hello World!

    \n", template.render - end - - test "can be rendered more than once" do - template = Tilt::RedcarpetTemplate.new { |t| "# Hello World!" } - 3.times { assert_equal "

    Hello World!

    \n", template.render } - end - - test "smartypants when :smart is set" do - template = Tilt::RedcarpetTemplate.new(:smartypants => true) { |t| - "OKAY -- 'Smarty Pants'" } - assert_match /

    OKAY – 'Smarty Pants'<\/p>/, - template.render - end - - test "smartypants with a rendererer instance" do - template = Tilt::RedcarpetTemplate.new(:renderer => Redcarpet::Render::HTML.new(:hard_wrap => true), :smartypants => true) { |t| - "OKAY -- 'Smarty Pants'" } - assert_match /

    OKAY – 'Smarty Pants'<\/p>/, - template.render - end - end -rescue LoadError => boom - warn "Tilt::RedcarpetTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_redclothtemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_redclothtemplate_test.rb deleted file mode 100644 index 2d94a4c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_redclothtemplate_test.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'redcloth' - - class RedClothTemplateTest < Test::Unit::TestCase - test "is registered for '.textile' files" do - assert_equal Tilt::RedClothTemplate, Tilt['test.textile'] - end - - test "compiles and evaluates the template on #render" do - template = Tilt::RedClothTemplate.new { |t| "h1. Hello World!" } - assert_equal "

    Hello World!

    ", template.render - end - - test "can be rendered more than once" do - template = Tilt::RedClothTemplate.new { |t| "h1. Hello World!" } - 3.times { assert_equal "

    Hello World!

    ", template.render } - end - - test "ignores unknown options" do - template = Tilt::RedClothTemplate.new(:foo => "bar") { |t| "h1. Hello World!" } - 3.times { assert_equal "

    Hello World!

    ", template.render } - end - - test "passes in RedCloth options" do - template = Tilt::RedClothTemplate.new { |t| "Hard breaks are\ninserted by default." } - assert_equal "

    Hard breaks are
    \ninserted by default.

    ", template.render - template = Tilt::RedClothTemplate.new(:hard_breaks => false) { |t| "But they can be\nturned off." } - assert_equal "

    But they can be\nturned off.

    ", template.render - end - end -rescue LoadError => boom - warn "Tilt::RedClothTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_sasstemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_sasstemplate_test.rb deleted file mode 100644 index be822af..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_sasstemplate_test.rb +++ /dev/null @@ -1,41 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'sass' - - class SassTemplateTest < Test::Unit::TestCase - test "is registered for '.sass' files" do - assert_equal Tilt::SassTemplate, Tilt['test.sass'] - end - - test "compiles and evaluates the template on #render" do - template = Tilt::SassTemplate.new { |t| "#main\n :background-color #0000f1" } - assert_equal "#main {\n background-color: #0000f1; }\n", template.render - end - - test "can be rendered more than once" do - template = Tilt::SassTemplate.new { |t| "#main\n :background-color #0000f1" } - 3.times { assert_equal "#main {\n background-color: #0000f1; }\n", template.render } - end - end - - class ScssTemplateTest < Test::Unit::TestCase - test "is registered for '.scss' files" do - assert_equal Tilt::ScssTemplate, Tilt['test.scss'] - end - - test "compiles and evaluates the template on #render" do - template = Tilt::ScssTemplate.new { |t| "#main {\n background-color: #0000f1;\n}" } - assert_equal "#main {\n background-color: #0000f1; }\n", template.render - end - - test "can be rendered more than once" do - template = Tilt::ScssTemplate.new { |t| "#main {\n background-color: #0000f1;\n}" } - 3.times { assert_equal "#main {\n background-color: #0000f1; }\n", template.render } - end - end - -rescue LoadError => boom - warn "Tilt::SassTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_stringtemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_stringtemplate_test.rb deleted file mode 100644 index f0a8919..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_stringtemplate_test.rb +++ /dev/null @@ -1,170 +0,0 @@ -require 'contest' -require 'tilt' - -class StringTemplateTest < Test::Unit::TestCase - test "registered for '.str' files" do - assert_equal Tilt::StringTemplate, Tilt['test.str'] - end - - test "loading and evaluating templates on #render" do - template = Tilt::StringTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render - end - - test "can be rendered more than once" do - template = Tilt::StringTemplate.new { |t| "Hello World!" } - 3.times { assert_equal "Hello World!", template.render } - end - - test "passing locals" do - template = Tilt::StringTemplate.new { 'Hey #{name}!' } - assert_equal "Hey Joe!", template.render(Object.new, :name => 'Joe') - end - - test "evaluating in an object scope" do - template = Tilt::StringTemplate.new { 'Hey #{@name}!' } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::StringTemplate.new { 'Hey #{yield}!' } - assert_equal "Hey Joe!", template.render { 'Joe' } - assert_equal "Hey Moe!", template.render { 'Moe' } - end - - test "multiline templates" do - template = Tilt::StringTemplate.new { "Hello\nWorld!\n" } - assert_equal "Hello\nWorld!\n", template.render - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::StringTemplate.new('test.str', 11) { data } - begin - template.render - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.grep(/^test\.str:/).first - assert line, "Backtrace didn't contain test.str" - file, line, meth = line.split(":") - assert_equal '13', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::StringTemplate.new('test.str', 1) { data } - begin - template.render(nil, :name => 'Joe', :foo => 'bar') - fail 'should have raised an exception' - rescue => boom - assert_kind_of RuntimeError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.str', file - assert_equal '6', line - end - end -end - - -class CompiledStringTemplateTest < Test::Unit::TestCase - def teardown - GC.start - end - - class Scope - end - - test "compiling template source to a method" do - template = Tilt::StringTemplate.new { |t| "Hello World!" } - template.render(Scope.new) - method = template.send(:compiled_method, []) - assert_kind_of UnboundMethod, method - end - - test "loading and evaluating templates on #render" do - template = Tilt::StringTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", template.render(Scope.new) - end - - test "passing locals" do - template = Tilt::StringTemplate.new { 'Hey #{name}!' } - assert_equal "Hey Joe!", template.render(Scope.new, :name => 'Joe') - assert_equal "Hey Moe!", template.render(Scope.new, :name => 'Moe') - end - - test "evaluating in an object scope" do - template = Tilt::StringTemplate.new { 'Hey #{@name}!' } - scope = Scope.new - scope.instance_variable_set :@name, 'Joe' - assert_equal "Hey Joe!", template.render(scope) - scope.instance_variable_set :@name, 'Moe' - assert_equal "Hey Moe!", template.render(scope) - end - - test "passing a block for yield" do - template = Tilt::StringTemplate.new { 'Hey #{yield}!' } - assert_equal "Hey Joe!", template.render(Scope.new) { 'Joe' } - assert_equal "Hey Moe!", template.render(Scope.new) { 'Moe' } - end - - test "multiline templates" do - template = Tilt::StringTemplate.new { "Hello\nWorld!\n" } - assert_equal "Hello\nWorld!\n", template.render(Scope.new) - end - - - test "template with '}'" do - template = Tilt::StringTemplate.new { "Hello }" } - assert_equal "Hello }", template.render - end - - test "backtrace file and line reporting without locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::StringTemplate.new('test.str', 11) { data } - begin - template.render(Scope.new) - fail 'should have raised an exception' - rescue => boom - assert_kind_of NameError, boom - line = boom.backtrace.first - line = boom.backtrace.grep(/^test\.str:/).first - assert line, "Backtrace didn't contain test.str" - file, line, meth = line.split(":") - assert_equal '13', line - end - end - - test "backtrace file and line reporting with locals" do - data = File.read(__FILE__).split("\n__END__\n").last - fail unless data[0] == ?< - template = Tilt::StringTemplate.new('test.str') { data } - begin - template.render(Scope.new, :name => 'Joe', :foo => 'bar') - fail 'should have raised an exception' - rescue => boom - assert_kind_of RuntimeError, boom - line = boom.backtrace.first - file, line, meth = line.split(":") - assert_equal 'test.str', file - assert_equal '6', line - end - end -end - -__END__ - - -

    Hey #{name}!

    - - -

    #{fail}

    - - diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_template_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_template_test.rb deleted file mode 100644 index 111a141..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_template_test.rb +++ /dev/null @@ -1,323 +0,0 @@ -# coding: utf-8 -require 'contest' -require 'tilt' -require 'tempfile' - -class TiltTemplateTest < Test::Unit::TestCase - - class MockTemplate < Tilt::Template - def prepare - end - end - - test "needs a file or block" do - assert_raise(ArgumentError) { Tilt::Template.new } - end - - test "initializing with a file" do - inst = MockTemplate.new('foo.erb') {} - assert_equal 'foo.erb', inst.file - end - - test "initializing with a file and line" do - inst = MockTemplate.new('foo.erb', 55) {} - assert_equal 'foo.erb', inst.file - assert_equal 55, inst.line - end - - test "initializing with a tempfile" do - tempfile = Tempfile.new('tilt_template_test') - inst = MockTemplate.new(tempfile) - assert_equal File.basename(tempfile.path), inst.basename - end - - class SillyHash < Hash - def path(arg) - end - end - - test "initialize with hash that implements #path" do - options = SillyHash[:key => :value] - inst = MockTemplate.new(options) {} - assert_equal :value, inst.options[:key] - end - - test "uses correct eval_file" do - inst = MockTemplate.new('foo.erb', 55) {} - assert_equal 'foo.erb', inst.eval_file - end - - test "uses a default filename for #eval_file when no file provided" do - inst = MockTemplate.new { 'Hi' } - assert_not_nil inst.eval_file - assert !inst.eval_file.include?("\n") - end - - test "calculating template's #basename" do - inst = MockTemplate.new('/tmp/templates/foo.html.erb') {} - assert_equal 'foo.html.erb', inst.basename - end - - test "calculating the template's #name" do - inst = MockTemplate.new('/tmp/templates/foo.html.erb') {} - assert_equal 'foo', inst.name - end - - test "initializing with a data loading block" do - MockTemplate.new { |template| "Hello World!" } - end - - class InitializingMockTemplate < Tilt::Template - @@initialized_count = 0 - def self.initialized_count - @@initialized_count - end - - def initialize_engine - @@initialized_count += 1 - end - - def prepare - end - end - - test "one-time template engine initialization" do - assert_nil InitializingMockTemplate.engine_initialized - assert_equal 0, InitializingMockTemplate.initialized_count - - InitializingMockTemplate.new { "Hello World!" } - assert InitializingMockTemplate.engine_initialized - assert_equal 1, InitializingMockTemplate.initialized_count - - InitializingMockTemplate.new { "Hello World!" } - assert_equal 1, InitializingMockTemplate.initialized_count - end - - class PreparingMockTemplate < Tilt::Template - include Test::Unit::Assertions - def prepare - assert !data.nil? - @prepared = true - end - def prepared? ; @prepared ; end - end - - test "raises NotImplementedError when #prepare not defined" do - assert_raise(NotImplementedError) { Tilt::Template.new { |template| "Hello World!" } } - end - - test "raises NotImplementedError when #evaluate or #template_source not defined" do - inst = PreparingMockTemplate.new { |t| "Hello World!" } - assert_raise(NotImplementedError) { inst.render } - assert inst.prepared? - end - - class SimpleMockTemplate < PreparingMockTemplate - include Test::Unit::Assertions - def evaluate(scope, locals, &block) - assert prepared? - assert !scope.nil? - assert !locals.nil? - "#{@data}" - end - end - - test "prepares and evaluates the template on #render" do - inst = SimpleMockTemplate.new { |t| "Hello World!" } - assert_equal "Hello World!", inst.render - assert inst.prepared? - end - - class SourceGeneratingMockTemplate < PreparingMockTemplate - def precompiled_template(locals) - "foo = [] ; foo << %Q{#{data}} ; foo.join" - end - end - - test "template_source with locals" do - inst = SourceGeneratingMockTemplate.new { |t| 'Hey #{name}!' } - assert_equal "Hey Joe!", inst.render(Object.new, :name => 'Joe') - assert inst.prepared? - end - - test "template_source with locals of strings" do - inst = SourceGeneratingMockTemplate.new { |t| 'Hey #{name}!' } - assert_equal "Hey Joe!", inst.render(Object.new, 'name' => 'Joe') - assert inst.prepared? - end - - test "template_source with locals having non-variable keys raises error" do - inst = SourceGeneratingMockTemplate.new { |t| '1 + 2 = #{_answer}' } - err = assert_raise(RuntimeError) { inst.render(Object.new, 'ANSWER' => 3) } - assert_equal "invalid locals key: \"ANSWER\" (keys must be variable names)", err.message - assert_equal "1 + 2 = 3", inst.render(Object.new, '_answer' => 3) - end - - class CustomGeneratingMockTemplate < PreparingMockTemplate - def precompiled_template(locals) - data - end - - def precompiled_preamble(locals) - options.fetch(:preamble) - end - - def precompiled_postamble(locals) - options.fetch(:postamble) - end - end - - test "supports pre/postamble" do - inst = CustomGeneratingMockTemplate.new( - :preamble => 'buf = []', - :postamble => 'buf.join' - ) { 'buf << 1' } - - assert_equal "1", inst.render - end - - # Special-case for Haml - # https://github.com/rtomayko/tilt/issues/193 - test "supports Array pre/postambles" do - inst = CustomGeneratingMockTemplate.new( - :preamble => ['buf = ', '[]'], - :postamble => ['buf.', 'join'] - ) { 'buf << 1' } - - # TODO: Use assert_output when we swicth to MiniTest - warns = <<-EOF -precompiled_preamble should return String (not Array) -precompiled_postamble should return String (not Array) -EOF - - begin - require 'stringio' - $stderr = StringIO.new - assert_equal "1", inst.render - assert_equal warns, $stderr.string - ensure - $stderr = STDERR - end - end - - class Person - CONSTANT = "Bob" - - attr_accessor :name - def initialize(name) - @name = name - end - end - - test "template_source with an object scope" do - inst = SourceGeneratingMockTemplate.new { |t| 'Hey #{@name}!' } - scope = Person.new('Joe') - assert_equal "Hey Joe!", inst.render(scope) - end - - test "template_source with a block for yield" do - inst = SourceGeneratingMockTemplate.new { |t| 'Hey #{yield}!' } - assert_equal "Hey Joe!", inst.render(Object.new){ 'Joe' } - end - - test "template which accesses a constant" do - inst = SourceGeneratingMockTemplate.new { |t| 'Hey #{CONSTANT}!' } - assert_equal "Hey Bob!", inst.render(Person.new("Joe")) - end - - ## - # Encodings - - class DynamicMockTemplate < MockTemplate - def precompiled_template(locals) - options[:code] - end - end - - class UTF8Template < MockTemplate - def default_encoding - Encoding::UTF_8 - end - end - - if ''.respond_to?(:encoding) - original_encoding = Encoding.default_external - - setup do - @file = Tempfile.open('template') - @file.puts "stuff" - @file.close - @template = @file.path - end - - teardown do - Encoding.default_external = original_encoding - Encoding.default_internal = nil - @file.delete - end - - test "reading from file assumes default external encoding" do - Encoding.default_external = 'Big5' - inst = MockTemplate.new(@template) - assert_equal 'Big5', inst.data.encoding.to_s - end - - test "reading from file with a :default_encoding overrides default external" do - Encoding.default_external = 'Big5' - inst = MockTemplate.new(@template, :default_encoding => 'GBK') - assert_equal 'GBK', inst.data.encoding.to_s - end - - test "reading from file with default_internal set does no transcoding" do - Encoding.default_internal = 'utf-8' - Encoding.default_external = 'Big5' - inst = MockTemplate.new(@template) - assert_equal 'Big5', inst.data.encoding.to_s - end - - test "using provided template data verbatim when given as string" do - Encoding.default_internal = 'Big5' - inst = MockTemplate.new(@template) { "blah".force_encoding('GBK') } - assert_equal 'GBK', inst.data.encoding.to_s - end - - test "uses the template from the generated source code" do - tmpl = "ふが" - code = tmpl.inspect.encode('Shift_JIS') - inst = DynamicMockTemplate.new(:code => code) { '' } - res = inst.render - assert_equal 'Shift_JIS', res.encoding.to_s - assert_equal tmpl, res.encode(tmpl.encoding) - end - - test "uses the magic comment from the generated source code" do - tmpl = "ふが" - code = ("# coding: Shift_JIS\n" + tmpl.inspect).encode('Shift_JIS') - # Set it to an incorrect encoding - code.force_encoding('UTF-8') - - inst = DynamicMockTemplate.new(:code => code) { '' } - res = inst.render - assert_equal 'Shift_JIS', res.encoding.to_s - assert_equal tmpl, res.encode(tmpl.encoding) - end - - test "uses #default_encoding instead of default_external" do - Encoding.default_external = 'Big5' - inst = UTF8Template.new(@template) - assert_equal 'UTF-8', inst.data.encoding.to_s - end - - test "uses #default_encoding instead of current encoding" do - tmpl = "".force_encoding('Big5') - inst = UTF8Template.new(@template) { tmpl } - assert_equal 'UTF-8', inst.data.encoding.to_s - end - - test "raises error if the encoding is not valid" do - assert_raises(Encoding::InvalidByteSequenceError) do - UTF8Template.new(@template) { "\xe4" } - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_test.rb deleted file mode 100644 index f12dacb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_test.rb +++ /dev/null @@ -1,65 +0,0 @@ -require 'contest' -require 'tilt' - -class TiltTest < Test::Unit::TestCase - class MockTemplate - attr_reader :args, :block - def initialize(*args, &block) - @args = args - @block = block - end - end - - test "registering template implementation classes by file extension" do - Tilt.register('mock', MockTemplate) - end - - test "an extension is registered if explicit handle is found" do - Tilt.register('mock', MockTemplate) - assert Tilt.registered?('mock') - end - - test "registering template classes by symbol file extension" do - Tilt.register(:mock, MockTemplate) - end - - test "looking up template classes by exact file extension" do - Tilt.register('mock', MockTemplate) - impl = Tilt['mock'] - assert_equal MockTemplate, impl - end - - test "looking up template classes by implicit file extension" do - Tilt.register('mock', MockTemplate) - impl = Tilt['.mock'] - assert_equal MockTemplate, impl - end - - test "looking up template classes with multiple file extensions" do - Tilt.register('mock', MockTemplate) - impl = Tilt['index.html.mock'] - assert_equal MockTemplate, impl - end - - test "looking up template classes by file name" do - Tilt.register('mock', MockTemplate) - impl = Tilt['templates/test.mock'] - assert_equal MockTemplate, impl - end - - test "looking up non-existant template class" do - assert_nil Tilt['none'] - end - - test "accessing template class mappings at Tilt::mappings" do - assert Tilt.respond_to?(:mappings) - assert Tilt.mappings.respond_to?(:[]) - end - - test "creating new template instance with a filename" do - Tilt.register('mock', MockTemplate) - template = Tilt.new('foo.mock', 1, :key => 'val') { 'Hello World!' } - assert_equal ['foo.mock', 1, {:key => 'val'}], template.args - assert_equal 'Hello World!', template.block.call - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_wikiclothtemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_wikiclothtemplate_test.rb deleted file mode 100644 index fd52de9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_wikiclothtemplate_test.rb +++ /dev/null @@ -1,32 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'wikicloth' - - class WikiClothTemplateTest < Test::Unit::TestCase - test "is registered for '.mediawiki' files" do - assert_equal Tilt::WikiClothTemplate, Tilt['test.mediawiki'] - end - - test "is registered for '.mw' files" do - assert_equal Tilt::WikiClothTemplate, Tilt['test.mw'] - end - - test "is registered for '.wiki' files" do - assert_equal Tilt::WikiClothTemplate, Tilt['test.wiki'] - end - - test "compiles and evaluates the template on #render" do - template = Tilt::WikiClothTemplate.new { |t| "= Hello World! =" } - assert_match /

    .*Hello World!.*<\/h1>/, template.render - end - - test "can be rendered more than once" do - template = Tilt::WikiClothTemplate.new { |t| "= Hello World! =" } - 3.times { assert_match /

    .*Hello World!.*<\/h1>/, template.render } - end - end -rescue LoadError => boom - warn "Tilt::WikiClothTemplate (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_yajltemplate_test.rb b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_yajltemplate_test.rb deleted file mode 100644 index 48ef1d1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/test/tilt_yajltemplate_test.rb +++ /dev/null @@ -1,101 +0,0 @@ -require 'contest' -require 'tilt' - -begin - require 'yajl' - - class YajlTemplateTest < Test::Unit::TestCase - test "is registered for '.yajl' files" do - assert_equal Tilt::YajlTemplate, Tilt['test.yajl'] - end - - test "compiles and evaluates the template on #render" do - template = Tilt::YajlTemplate.new { "json = { :integer => 3, :string => 'hello' }" } - output = template.render - result = Yajl::Parser.parse(output) - expect = {"integer" => 3,"string" => "hello"} - assert_equal expect, result - end - - test "can be rendered more than once" do - template = Tilt::YajlTemplate.new { "json = { :integer => 3, :string => 'hello' }" } - expect = {"integer" => 3,"string" => "hello"} - 3.times do - output = template.render - result = Yajl::Parser.parse(output) - assert_equal expect, result - end - end - - test "evaluating ruby code" do - template = Tilt::YajlTemplate.new { "json = { :integer => (3 * 2) }" } - assert_equal '{"integer":6}', template.render - end - - test "evaluating in an object scope" do - template = Tilt::YajlTemplate.new { "json = { :string => 'Hey ' + @name + '!' }" } - scope = Object.new - scope.instance_variable_set :@name, 'Joe' - assert_equal '{"string":"Hey Joe!"}', template.render(scope) - end - - test "passing locals" do - template = Tilt::YajlTemplate.new { "json = { :string => 'Hey ' + name + '!' }" } - assert_equal '{"string":"Hey Joe!"}', template.render(Object.new, :name => 'Joe') - end - - test "passing a block for yield" do - template = Tilt::YajlTemplate.new { "json = { :string => 'Hey ' + yield + '!' }" } - assert_equal '{"string":"Hey Joe!"}', template.render { 'Joe' } - assert_equal '{"string":"Hey Moe!"}', template.render { 'Moe' } - end - - test "template multiline" do - template = Tilt::YajlTemplate.new { %Q{ - json = { - :string => "hello" - } - } } - assert_equal '{"string":"hello"}', template.render - end - - test "template can reuse existing json buffer" do - template = Tilt::YajlTemplate.new { "json.merge! :string => 'hello'" } - assert_equal '{"string":"hello"}', template.render - end - - test "template can end with any statement" do - template = Tilt::YajlTemplate.new { %Q{ - json = { - :string => "hello" - } - four = 2 * 2 - json[:integer] = four - nil - } } - result = template.render - assert( (result == '{"string":"hello","integer":4}') || (result == '{"integer":4,"string":"hello"}') ) - end - - test "option callback" do - options = { :callback => 'foo' } - template = Tilt::YajlTemplate.new(nil, options) { "json = { :string => 'hello' }" } - assert_equal 'foo({"string":"hello"});', template.render - end - - test "option variable" do - options = { :variable => 'output' } - template = Tilt::YajlTemplate.new(nil, options) { "json = { :string => 'hello' }" } - assert_equal 'var output = {"string":"hello"};', template.render - end - - test "option callback and variable" do - options = { :callback => 'foo', :variable => 'output' } - template = Tilt::YajlTemplate.new(nil, options) { "json = { :string => 'hello' }" } - assert_equal 'var output = {"string":"hello"}; foo(output);', template.render - end - - end -rescue LoadError - warn "Tilt::YajlTemplateTest (disabled)" -end diff --git a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/tilt.gemspec b/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/tilt.gemspec deleted file mode 100644 index 00f49f4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/tilt-1.4.1/tilt.gemspec +++ /dev/null @@ -1,120 +0,0 @@ -Gem::Specification.new do |s| - s.specification_version = 2 if s.respond_to? :specification_version= - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - - s.name = 'tilt' - s.version = '1.4.1' - s.date = '2013-05-08' - - s.description = "Generic interface to multiple Ruby template engines" - s.summary = s.description - s.license = "MIT" - - s.authors = ["Ryan Tomayko"] - s.email = "r@tomayko.com" - - # = MANIFEST = - s.files = %w[ - CHANGELOG.md - COPYING - Gemfile - HACKING - README.md - Rakefile - TEMPLATES.md - bin/tilt - lib/tilt.rb - lib/tilt/asciidoc.rb - lib/tilt/builder.rb - lib/tilt/coffee.rb - lib/tilt/css.rb - lib/tilt/csv.rb - lib/tilt/erb.rb - lib/tilt/etanni.rb - lib/tilt/haml.rb - lib/tilt/liquid.rb - lib/tilt/markaby.rb - lib/tilt/markdown.rb - lib/tilt/nokogiri.rb - lib/tilt/plain.rb - lib/tilt/radius.rb - lib/tilt/rdoc.rb - lib/tilt/string.rb - lib/tilt/template.rb - lib/tilt/textile.rb - lib/tilt/wiki.rb - lib/tilt/yajl.rb - test/contest.rb - test/markaby/locals.mab - test/markaby/markaby.mab - test/markaby/markaby_other_static.mab - test/markaby/render_twice.mab - test/markaby/scope.mab - test/markaby/yielding.mab - test/tilt_asciidoctor_test.rb - test/tilt_blueclothtemplate_test.rb - test/tilt_buildertemplate_test.rb - test/tilt_cache_test.rb - test/tilt_coffeescripttemplate_test.rb - test/tilt_compilesite_test.rb - test/tilt_creoletemplate_test.rb - test/tilt_csv_test.rb - test/tilt_erbtemplate_test.rb - test/tilt_erubistemplate_test.rb - test/tilt_etannitemplate_test.rb - test/tilt_fallback_test.rb - test/tilt_hamltemplate_test.rb - test/tilt_kramdown_test.rb - test/tilt_lesstemplate_test.less - test/tilt_lesstemplate_test.rb - test/tilt_liquidtemplate_test.rb - test/tilt_markaby_test.rb - test/tilt_markdown_test.rb - test/tilt_marukutemplate_test.rb - test/tilt_nokogiritemplate_test.rb - test/tilt_radiustemplate_test.rb - test/tilt_rdiscounttemplate_test.rb - test/tilt_rdoctemplate_test.rb - test/tilt_redcarpettemplate_test.rb - test/tilt_redclothtemplate_test.rb - test/tilt_sasstemplate_test.rb - test/tilt_stringtemplate_test.rb - test/tilt_template_test.rb - test/tilt_test.rb - test/tilt_wikiclothtemplate_test.rb - test/tilt_yajltemplate_test.rb - tilt.gemspec - ] - # = MANIFEST = - - s.executables = ['tilt'] - s.test_files = s.files.select {|path| path =~ /^test\/.*_test.rb/} - s.add_development_dependency 'asciidoctor', '>= 0.1.0' - s.add_development_dependency 'RedCloth' - s.add_development_dependency 'bluecloth' - s.add_development_dependency 'builder' - s.add_development_dependency 'coffee-script' - s.add_development_dependency 'contest' - s.add_development_dependency 'creole' - s.add_development_dependency 'erubis' - s.add_development_dependency 'haml', '>= 2.2.11' - s.add_development_dependency 'kramdown' - s.add_development_dependency 'less' - s.add_development_dependency 'liquid' - s.add_development_dependency 'markaby' - s.add_development_dependency 'maruku' - s.add_development_dependency 'nokogiri' - s.add_development_dependency 'radius' - s.add_development_dependency 'rdiscount' - s.add_development_dependency 'rdoc' - s.add_development_dependency 'redcarpet' - s.add_development_dependency 'sass' - s.add_development_dependency 'wikicloth' - s.add_development_dependency 'yajl-ruby' - s.add_development_dependency 'rdoc' - - s.homepage = "http://github.com/rtomayko/tilt/" - s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Tilt", "--main", "Tilt"] - s.require_paths = %w[lib] - s.rubygems_version = '1.1.1' -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.CHANGELOG.old b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.CHANGELOG.old deleted file mode 100644 index 8326f53..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.CHANGELOG.old +++ /dev/null @@ -1,25 +0,0 @@ -v0.91.0 - HTTP/0.9 support, multiline header support, small fixes -v0.90.0 - switch chunking+trailer handling to Ragel, v0.8.4 fixes -v0.9.2 - Ruby 1.9.2 preview1 compatibility -v0.9.1 - FD_CLOEXEC portability fix (v0.8.2 port) -v0.9.0 - bodies: "Transfer-Encoding: chunked", rewindable streaming -v0.8.4 - pass through unknown HTTP status codes -v0.8.3 - Ruby 1.9.2 preview1 compatibility -v0.8.2 - socket handling bugfixes and usability tweaks -v0.8.1 - safer timeout handling, more consistent reload behavior -v0.8.0 - enforce Rack dependency, minor performance improvements and fixes -v0.7.1 - minor fixes, cleanups and documentation improvements -v0.7.0 - rack.version is 1.0 -v0.6.0 - cleanups + optimizations, signals to {in,de}crement processes -v0.5.4 - fix data corruption with some small uploads (not curl) -v0.5.3 - fix 100% CPU usage when idle, small cleanups -v0.5.2 - force Status: header for compat, small cleanups -v0.5.1 - exit correctly on INT/TERM, QUIT is still recommended, however -v0.5.0 - {after,before}_fork API change, small tweaks/fixes -v0.4.2 - fix Rails ARStore, FD leak prevention, descriptive proctitles -v0.4.1 - Rails support, per-listener backlog and {snd,rcv}buf -v0.2.3 - Unlink Tempfiles after use (they were closed, just not unlinked) -v0.2.2 - small bug fixes, fix Rack multi-value headers (Set-Cookie:) -v0.2.1 - Fix broken Manifest that cause unicorn_rails to not be bundled -v0.2.0 - unicorn_rails launcher script. -v0.1.0 - Unicorn - UNIX-only fork of Mongrel free of threading diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.document b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.document deleted file mode 100644 index 4092597..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.document +++ /dev/null @@ -1,29 +0,0 @@ -FAQ -README -TUNING -PHILOSOPHY -HACKING -DESIGN -CONTRIBUTORS -LICENSE -SIGNALS -KNOWN_ISSUES -TODO -NEWS -ChangeLog -LATEST -lib/unicorn.rb -lib/unicorn/configurator.rb -lib/unicorn/http_server.rb -lib/unicorn/preread_input.rb -lib/unicorn/stream_input.rb -lib/unicorn/tee_input.rb -lib/unicorn/util.rb -lib/unicorn/oob_gc.rb -lib/unicorn/worker.rb -unicorn_1 -unicorn_rails_1 -ISSUES -Sandbox -Links -Application_Timeouts diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.gitignore b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.gitignore deleted file mode 100644 index 19a82d6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.gitignore +++ /dev/null @@ -1,25 +0,0 @@ -*.o -*.bundle -*.log -*.so -*.rbc -.DS_Store -/.config -/InstalledFiles -/doc -/local.mk -/test/rbx-* -/test/ruby-* -ext/unicorn_http/Makefile -ext/unicorn_http/unicorn_http.c -log/ -pkg/ -/vendor -/NEWS -/ChangeLog -/.manifest -/GIT-VERSION-FILE -/man -/tmp -/LATEST -/lib/unicorn/version.rb diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.mailmap b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.mailmap deleted file mode 100644 index 7b8974f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.mailmap +++ /dev/null @@ -1,26 +0,0 @@ -# This list is used by "git shortlog" to fixup the ugly faux email addresses -# "" that the "git svn" tool creates by default. - -# Eric Wong started this .mailmap file (and is the maintainer of it...) -Eric Wong normalperson - -# This also includes all the Mongrel contributors that committed to the -# Rubyforge SVN repo. Some real names were looked up on rubyforge.org -# (http://rubyforge.org/users/$user), but we're not going expose any email -# addresses here without their permission. - -Austin Godber godber godber -Bradley Taylor bktaylor -Ezra Zygmuntowicz ezmobius -Filipe Lautert filipe -Luis Lavena luislavena -Matt Pelletier bricolage -MenTaLguY mental -Nick Sieger nicksieger -Rick Olson technoweenie -Wayne E. Seguin wayneeseguin -Zed A. Shaw -why the lucky stiff - -# Evan had his email address in the git history we branched from anyways -Evan Weaver evanweaver diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.wrongdoc.yml b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.wrongdoc.yml deleted file mode 100644 index 3c3cbaf..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/.wrongdoc.yml +++ /dev/null @@ -1,11 +0,0 @@ ---- -cgit_url: http://bogomips.org/unicorn.git -git_url: git://bogomips.org/unicorn.git -rdoc_url: http://unicorn.bogomips.org/ -ml_url: http://bogomips.org/unicorn-public/ -changelog_start: v1.1.5 -merge_html: - unicorn_1: Documentation/unicorn.1.html - unicorn_rails_1: Documentation/unicorn_rails.1.html -public_email: unicorn-public@bogomips.org -private_email: unicorn@bogomips.org diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Application_Timeouts b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Application_Timeouts deleted file mode 100644 index 5f0370d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Application_Timeouts +++ /dev/null @@ -1,77 +0,0 @@ -= Application Timeouts - -This article focuses on _application_ setup for Rack applications, but -can be expanded to all applications that connect to external resources -and expect short response times. - -This article is not specific to \Unicorn, but exists to discourage -the overuse of the built-in -{timeout}[link:Unicorn/Configurator.html#method-i-timeout] directive -in \Unicorn. - -== ALL External Resources Are Considered Unreliable - -Network reliability can _never_ be guaranteed. Network failures cannot -be detected reliably by the client (Rack application) in a reasonable -timeframe, not even on a LAN. - -Thus, application authors must configure timeouts when interacting with -external resources. - -Most database adapters allow configurable timeouts. - -Net::HTTP and Net::SMTP in the Ruby standard library allow -configurable timeouts. - -Even for things as fast as {memcached}[http://memcached.org/], -{dalli}[http://rubygems.org/gems/dalli], -{memcached}[http://rubygems.org/gems/memcached] and -{memcache-client}[http://rubygems.org/gems/memcache-client] RubyGems all -offer configurable timeouts. - -Consult the relevant documentation for the libraries you use on -how to configure these timeouts. - -== Rolling Your Own Socket Code - -Use non-blocking I/O and IO.select with a timeout to wait on sockets. - -== Timeout module in the Ruby standard library - -Ruby offers a Timeout module in its standard library. It has several -caveats and is not always reliable: - -* /Some/ Ruby C extensions are not interrupted/timed-out gracefully by - this module (report these bugs to extension authors, please) but - pure-Ruby components should be. - -* Long-running tasks may run inside `ensure' clauses after timeout - fires, causing the timeout to be ineffective. - -The Timeout module is a second-to-last-resort solution, timeouts using -IO.select (or similar) are more reliable. If you depend on libraries -that do not offer timeouts when connecting to external resources, kindly -ask those library authors to provide configurable timeouts. - -=== A Note About Filesystems - -Most operations to regular files on POSIX filesystems are NOT -interruptable. Thus, the "timeout" module in the Ruby standard library -can not reliably timeout systems with massive amounts of iowait. - -If your app relies on the filesystem, ensure all the data your -application works with is small enough to fit in the kernel page cache. -Otherwise increase the amount of physical memory you have to match, or -employ a fast, low-latency storage system (solid state). - -Volumes mounted over NFS (and thus a potentially unreliable network) -must be mounted with timeouts and applications must be prepared to -handle network/server failures. - -== The Last Line Of Defense - -The {timeout}[link:Unicorn/Configurator.html#method-i-timeout] mechanism -in \Unicorn is an extreme solution that should be avoided whenever -possible. It will help catch bugs in your application where and when -your application forgets to use timeouts, but it is expensive as it -kills and respawns a worker process. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/CONTRIBUTORS b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/CONTRIBUTORS deleted file mode 100644 index bda399b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/CONTRIBUTORS +++ /dev/null @@ -1,35 +0,0 @@ -Unicorn developers (let us know if we forgot you): -* Eric Wong (BDFL, BOFH) -* Suraj N. Kurapati -* Andrey Stikheev -* Wayne Larsen -* Iñaki Baz Castillo -* Augusto Becciu -* Hongli Lai -* ... (help wanted) - -We would like to thank following folks for helping make Unicorn possible: - -* Ezra Zygmuntowicz - for helping Eric decide on a sane configuration - format and reasonable defaults. -* Christian Neukirchen - for Rack, which let us put more focus on the server - and drastically cut down on the amount of code we have to maintain. -* Zed A. Shaw - for Mongrel, without which Unicorn would not be possible - -The original Mongrel contributors: - -* Luis Lavena -* Wilson Bilkovich -* why the lucky stiff -* Dan Kubb -* MenTaLguY -* Filipe Lautert -* Rick Olson -* Wayne E. Seguin -* Kirk Haines -* Bradley Taylor -* Matt Pelletier -* Ry Dahl -* Nick Sieger -* Evan Weaver -* Marc-André Cournoyer diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/COPYING b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/COPYING deleted file mode 100644 index b27ad83..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/DESIGN b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/DESIGN deleted file mode 100644 index bff6a8b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/DESIGN +++ /dev/null @@ -1,97 +0,0 @@ -== Design - -* Simplicity: Unicorn is a traditional UNIX prefork web server. - No threads are used at all, this makes applications easier to debug - and fix. When your application goes awry, a BOFH can just - "kill -9" the runaway worker process without worrying about tearing - all clients down, just one. Only UNIX-like systems supporting - fork() and file descriptor inheritance are supported. - -* The Ragel+C HTTP parser is taken from Mongrel. This is the - only non-Ruby part and there are no plans to add any more - non-Ruby components. - -* All HTTP parsing and I/O is done much like Mongrel: - 1. read/parse HTTP request headers in full - 2. call Rack application - 3. write HTTP response back to the client - -* Like Mongrel, neither keepalive nor pipelining are supported. - These aren't needed since Unicorn is only designed to serve - fast, low-latency clients directly. Do one thing, do it well; - let nginx handle slow clients. - -* Configuration is purely in Ruby and eval(). Ruby is less - ambiguous than YAML and lets lambdas for - before_fork/after_fork/before_exec hooks be defined inline. An - optional, separate config_file may be used to modify supported - configuration changes (and also gives you plenty of rope if you RTFS - :>) - -* One master process spawns and reaps worker processes. The - Rack application itself is called only within the worker process (but - can be loaded within the master). A copy-on-write friendly garbage - collector like the one found in Ruby 2.0.0dev or Ruby Enterprise Edition - can be used to minimize memory usage along with the "preload_app true" - directive (see Unicorn::Configurator). - -* The number of worker processes should be scaled to the number of - CPUs, memory or even spindles you have. If you have an existing - Mongrel cluster on a single-threaded app, using the same amount of - processes should work. Let a full-HTTP-request-buffering reverse - proxy like nginx manage concurrency to thousands of slow clients for - you. Unicorn scaling should only be concerned about limits of your - backend system(s). - -* Load balancing between worker processes is done by the OS kernel. - All workers share a common set of listener sockets and does - non-blocking accept() on them. The kernel will decide which worker - process to give a socket to and workers will sleep if there is - nothing to accept(). - -* Since non-blocking accept() is used, there can be a thundering - herd when an occasional client connects when application - *is not busy*. The thundering herd problem should not affect - applications that are running all the time since worker processes - will only select()/accept() outside of the application dispatch. - -* Additionally, thundering herds are much smaller than with - configurations using existing prefork servers. Process counts should - only be scaled to backend resources, _never_ to the number of expected - clients like is typical with blocking prefork servers. So while we've - seen instances of popular prefork servers configured to run many - hundreds of worker processes, Unicorn deployments are typically only - 2-4 processes per-core. - -* On-demand scaling of worker processes never happens automatically. - Again, Unicorn is concerned about scaling to backend limits and should - never configured in a fashion where it could be waiting on slow - clients. For extremely rare circumstances, we provide TTIN and TTOU - signal handlers to increment/decrement your process counts without - reloading. Think of it as driving a car with manual transmission: - you have a lot more control if you know what you're doing. - -* Blocking I/O is used for clients. This allows a simpler code path - to be followed within the Ruby interpreter and fewer syscalls. - Applications that use threads continue to work if Unicorn - is only serving LAN or localhost clients. - -* SIGKILL is used to terminate the timed-out workers from misbehaving apps - as reliably as possible on a UNIX system. The default timeout is a - generous 60 seconds (same default as in Mongrel). - -* The poor performance of select() on large FD sets is avoided - as few file descriptors are used in each worker. - There should be no gain from moving to highly scalable but - unportable event notification solutions for watching few - file descriptors. - -* If the master process dies unexpectedly for any reason, - workers will notice within :timeout/2 seconds and follow - the master to its death. - -* There is never any explicit real-time dependency or communication - between the worker processes nor to the master process. - Synchronization is handled entirely by the OS kernel and shared - resources are never accessed by the worker when it is servicing - a client. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/.gitignore b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/.gitignore deleted file mode 100644 index 46679d6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -*.1 -*.5 -*.7 -*.gz -*.html diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/GNUmakefile b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/GNUmakefile deleted file mode 100644 index 2c04bdb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/GNUmakefile +++ /dev/null @@ -1,30 +0,0 @@ -all:: - -PANDOC = pandoc -PANDOC_OPTS = -f markdown --email-obfuscation=none -pandoc = $(PANDOC) $(PANDOC_OPTS) -pandoc_html = $(pandoc) --toc -t html --no-wrap - -man1 := $(addsuffix .1,unicorn unicorn_rails) -html1 := $(addsuffix .html,$(man1)) - -all:: html man - -html: $(html1) -man: $(man1) - -install-html: html - mkdir -p ../doc/man1 - install -m 644 $(html1) ../doc/man1 - -install-man: man - mkdir -p ../man/man1 - install -m 644 $(man1) ../man/man1 - -%.1: %.1.txt - $(pandoc) -s -t man < $< > $@+ && mv $@+ $@ -%.1.html: %.1.txt - $(pandoc_html) < $< > $@+ && mv $@+ $@ - -clean:: - $(RM) $(man1) $(html1) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/unicorn.1.txt b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/unicorn.1.txt deleted file mode 100644 index 376a6c6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/unicorn.1.txt +++ /dev/null @@ -1,178 +0,0 @@ -% UNICORN(1) Unicorn User Manual -% The Unicorn Community -% September 15, 2009 - -# NAME - -unicorn - a rackup-like command to launch the Unicorn HTTP server - -# SYNOPSIS - -unicorn [-c CONFIG_FILE] [-E RACK_ENV] [-D] [RACKUP_FILE] - -# DESCRIPTION - -A rackup(1)-like command to launch Rack applications using Unicorn. -It is expected to be started in your application root (APP_ROOT), -but the "working_directory" directive may be used in the CONFIG_FILE. - -While unicorn takes a myriad of command-line options for -compatibility with ruby(1) and rackup(1), it is recommended to stick -to the few command-line options specified in the SYNOPSIS and use -the CONFIG_FILE as much as possible. - -# RACKUP FILE - -This defaults to \"config.ru\" in APP_ROOT. It should be the same -file used by rackup(1) and other Rack launchers, it uses the -*Rack::Builder* DSL. - -Embedded command-line options are mostly parsed for compatibility -with rackup(1) but strongly discouraged. - -# UNICORN OPTIONS --c, \--config-file CONFIG_FILE -: Path to the Unicorn-specific config file. The config file is - implemented as a Ruby DSL, so Ruby code may executed. - See the RDoc/ri for the *Unicorn::Configurator* class for the full - list of directives available from the DSL. - Using an absolute path for for CONFIG_FILE is recommended as it - makes multiple instances of Unicorn easily distinguishable when - viewing ps(1) output. - --D, \--daemonize -: Run daemonized in the background. The process is detached from - the controlling terminal and stdin is redirected to "/dev/null". - Unlike many common UNIX daemons, we do not chdir to \"/\" - upon daemonization to allow more control over the startup/upgrade - process. - Unless specified in the CONFIG_FILE, stderr and stdout will - also be redirected to "/dev/null". - --E, \--env RACK_ENV -: Run under the given RACK_ENV. See the RACK ENVIRONMENT section - for more details. - --l, \--listen ADDRESS -: Listens on a given ADDRESS. ADDRESS may be in the form of - HOST:PORT or PATH, HOST:PORT is taken to mean a TCP socket - and PATH is meant to be a path to a UNIX domain socket. - Defaults to "0.0.0.0:8080" (all addresses on TCP port 8080) - For production deployments, specifying the "listen" directive in - CONFIG_FILE is recommended as it allows fine-tuning of socket - options. --N, \--no-default-middleware -: Disables loading middleware implied by RACK_ENV. This bypasses the - configuration documented in the RACK ENVIRONMENT section, but still - allows RACK_ENV to be used for application/framework-specific purposes. - -# RACKUP COMPATIBILITY OPTIONS --o, \--host HOST -: Listen on a TCP socket belonging to HOST, default is - "0.0.0.0" (all addresses). - If specified multiple times on the command-line, only the - last-specified value takes effect. - This option only exists for compatibility with the rackup(1) command, - use of "-l"/"\--listen" switch is recommended instead. - --p, \--port PORT -: Listen on the specified TCP PORT, default is 8080. - If specified multiple times on the command-line, only the last-specified - value takes effect. - This option only exists for compatibility with the rackup(1) command, - use of "-l"/"\--listen" switch is recommended instead. - --s, \--server SERVER -: No-op, this exists only for compatibility with rackup(1). - -# RUBY OPTIONS --e, \--eval LINE -: Evaluate a LINE of Ruby code. This evaluation happens - immediately as the command-line is being parsed. - --d, \--debug -: Turn on debug mode, the $DEBUG variable is set to true. - --w, \--warn -: Turn on verbose warnings, the $VERBOSE variable is set to true. - --I, \--include PATH -: specify $LOAD_PATH. PATH will be prepended to $LOAD_PATH. - The \':\' character may be used to delimit multiple directories. - This directive may be used more than once. Modifications to - $LOAD_PATH take place immediately and in the order they were - specified on the command-line. - --r, \--require LIBRARY -: require a specified LIBRARY before executing the application. The - \"require\" statement will be executed immediately and in the order - they were specified on the command-line. - -# SIGNALS - -The following UNIX signals may be sent to the master process: - -* HUP - reload config file, app, and gracefully restart all workers -* INT/TERM - quick shutdown, kills all workers immediately -* QUIT - graceful shutdown, waits for workers to finish their - current request before finishing. -* USR1 - reopen all logs owned by the master and all workers - See Unicorn::Util.reopen_logs for what is considered a log. -* USR2 - reexecute the running binary. A separate QUIT - should be sent to the original process once the child is verified to - be up and running. -* WINCH - gracefully stops workers but keep the master running. - This will only work for daemonized processes. -* TTIN - increment the number of worker processes by one -* TTOU - decrement the number of worker processes by one - -See the [SIGNALS][4] document for full description of all signals -used by Unicorn. - -# RACK ENVIRONMENT - -Accepted values of RACK_ENV and the middleware they automatically load -(outside of RACKUP_FILE) are exactly as those in rackup(1): - -* development - loads Rack::CommonLogger, Rack::ShowExceptions, and - Rack::Lint middleware -* deployment - loads Rack::CommonLogger middleware -* none - loads no middleware at all, relying - entirely on RACKUP_FILE - -All unrecognized values for RACK_ENV are assumed to be -"none". Production deployments are strongly encouraged to use -"deployment" or "none" for maximum performance. - -As of Unicorn 0.94.0, RACK_ENV is exported as a process-wide environment -variable as well. While not current a part of the Rack specification as -of Rack 1.0.1, this has become a de facto standard in the Rack world. - -Note the Rack::ContentLength and Rack::Chunked middlewares are also -loaded by "deployment" and "development", but no other values of -RACK_ENV. If needed, they must be individually specified in the -RACKUP_FILE, some frameworks do not require them. - -# ENVIRONMENT VARIABLES - -The RACK_ENV variable is set by the aforementioned \-E switch. -All application or library-specific environment variables (e.g. TMPDIR) -may always be set in the Unicorn CONFIG_FILE in addition to the spawning -shell. When transparently upgrading Unicorn, all environment variables -set in the old master process are inherited by the new master process. -Unicorn only uses (and will overwrite) the UNICORN_FD environment -variable internally when doing transparent upgrades. - -# SEE ALSO - -* unicorn_rails(1) -* *Rack::Builder* ri/RDoc -* *Unicorn::Configurator* ri/RDoc -* [Unicorn RDoc][1] -* [Rack RDoc][2] -* [Rackup HowTo][3] - -[1]: http://unicorn.bogomips.org/ -[2]: http://rdoc.info/gems/r#/gems/rack/frames -[3]: http://wiki.github.com/rack/rack/tutorial-rackup-howto -[4]: http://unicorn.bogomips.org/SIGNALS.html diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/unicorn_rails.1.txt b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/unicorn_rails.1.txt deleted file mode 100644 index c5db3a1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Documentation/unicorn_rails.1.txt +++ /dev/null @@ -1,175 +0,0 @@ -% UNICORN_RAILS(1) Unicorn User Manual -% The Unicorn Community -% September 17, 2009 - -# NAME - -unicorn_rails - a script/server-like command to launch the Unicorn HTTP server - -# SYNOPSIS - -unicorn_rails [-c CONFIG_FILE] [-E RAILS_ENV] [-D] [RACKUP_FILE] - -# DESCRIPTION - -A rackup(1)-like command to launch Rails applications using Unicorn. It -is expected to be started in your Rails application root (RAILS_ROOT), -but the "working_directory" directive may be used in the CONFIG_FILE. - -It is designed to help Rails 1.x and 2.y users transition to Rack, but -it is NOT needed for Rails 3 applications. Rails 3 users are encouraged -to use unicorn(1) instead of unicorn_rails(1). Users of Rails 1.x/2.y -may also use unicorn(1) instead of unicorn_rails(1). - -The outward interface resembles rackup(1), the internals and default -middleware loading is designed like the `script/server` command -distributed with Rails. - -While Unicorn takes a myriad of command-line options for compatibility -with ruby(1) and rackup(1), it is recommended to stick to the few -command-line options specified in the SYNOPSIS and use the CONFIG_FILE -as much as possible. - -# UNICORN OPTIONS --c, \--config-file CONFIG_FILE -: Path to the Unicorn-specific config file. The config file is - implemented as a Ruby DSL, so Ruby code may executed. - See the RDoc/ri for the *Unicorn::Configurator* class for the full - list of directives available from the DSL. - Using an absolute path for for CONFIG_FILE is recommended as it - makes multiple instances of Unicorn easily distinguishable when - viewing ps(1) output. - --D, \--daemonize -: Run daemonized in the background. The process is detached from - the controlling terminal and stdin is redirected to "/dev/null". - Unlike many common UNIX daemons, we do not chdir to \"/\" - upon daemonization to allow more control over the startup/upgrade - process. - Unless specified in the CONFIG_FILE, stderr and stdout will - also be redirected to "/dev/null". - Daemonization will _skip_ loading of the *Rails::Rack::LogTailer* - middleware under Rails \>\= 2.3.x. - By default, unicorn\_rails(1) will create a PID file in - _\"RAILS\_ROOT/tmp/pids/unicorn.pid\"_. You may override this - by specifying the "pid" directive to override this Unicorn config file. - --E, \--env RAILS_ENV -: Run under the given RAILS_ENV. This sets the RAILS_ENV environment - variable. Acceptable values are exactly those you expect in your Rails - application, typically "development" or "production". - --l, \--listen ADDRESS -: Listens on a given ADDRESS. ADDRESS may be in the form of - HOST:PORT or PATH, HOST:PORT is taken to mean a TCP socket - and PATH is meant to be a path to a UNIX domain socket. - Defaults to "0.0.0.0:8080" (all addresses on TCP port 8080). - For production deployments, specifying the "listen" directive in - CONFIG_FILE is recommended as it allows fine-tuning of socket - options. - -# RACKUP COMPATIBILITY OPTIONS --o, \--host HOST -: Listen on a TCP socket belonging to HOST, default is - "0.0.0.0" (all addresses). - If specified multiple times on the command-line, only the - last-specified value takes effect. - This option only exists for compatibility with the rackup(1) command, - use of "-l"/"\--listen" switch is recommended instead. - --p, \--port PORT -: Listen on the specified TCP PORT, default is 8080. - If specified multiple times on the command-line, only the last-specified - value takes effect. - This option only exists for compatibility with the rackup(1) command, - use of "-l"/"\--listen" switch is recommended instead. - -\--path PATH -: Mounts the Rails application at the given PATH (instead of "/"). - This is equivalent to setting the RAILS_RELATIVE_URL_ROOT - environment variable. This is only supported under Rails 2.3 - or later at the moment. - -# RUBY OPTIONS --e, \--eval LINE -: Evaluate a LINE of Ruby code. This evaluation happens - immediately as the command-line is being parsed. - --d, \--debug -: Turn on debug mode, the $DEBUG variable is set to true. - For Rails \>\= 2.3.x, this loads the *Rails::Rack::Debugger* - middleware. - --w, \--warn -: Turn on verbose warnings, the $VERBOSE variable is set to true. - --I, \--include PATH -: specify $LOAD_PATH. PATH will be prepended to $LOAD_PATH. - The \':\' character may be used to delimit multiple directories. - This directive may be used more than once. Modifications to - $LOAD_PATH take place immediately and in the order they were - specified on the command-line. - --r, \--require LIBRARY -: require a specified LIBRARY before executing the application. The - \"require\" statement will be executed immediately and in the order - they were specified on the command-line. - -# RACKUP FILE - -This defaults to \"config.ru\" in RAILS_ROOT. It should be the same -file used by rackup(1) and other Rack launchers, it uses the -*Rack::Builder* DSL. Unlike many other Rack applications, RACKUP_FILE -is completely _optional_ for Rails, but may be used to disable some -of the default middleware for performance. - -Embedded command-line options are mostly parsed for compatibility -with rackup(1) but strongly discouraged. - -# ENVIRONMENT VARIABLES - -The RAILS_ENV variable is set by the aforementioned \-E switch. The -RAILS_RELATIVE_URL_ROOT is set by the aforementioned \--path switch. -Either of these variables may also be set in the shell or the Unicorn -CONFIG_FILE. All application or library-specific environment variables -(e.g. TMPDIR, RAILS_ASSET_ID) may always be set in the Unicorn -CONFIG_FILE in addition to the spawning shell. When transparently -upgrading Unicorn, all environment variables set in the old master -process are inherited by the new master process. Unicorn only uses (and -will overwrite) the UNICORN_FD environment variable internally when -doing transparent upgrades. - -# SIGNALS - -The following UNIX signals may be sent to the master process: - -* HUP - reload config file, app, and gracefully restart all workers -* INT/TERM - quick shutdown, kills all workers immediately -* QUIT - graceful shutdown, waits for workers to finish their - current request before finishing. -* USR1 - reopen all logs owned by the master and all workers - See Unicorn::Util.reopen_logs for what is considered a log. -* USR2 - reexecute the running binary. A separate QUIT - should be sent to the original process once the child is verified to - be up and running. -* WINCH - gracefully stops workers but keep the master running. - This will only work for daemonized processes. -* TTIN - increment the number of worker processes by one -* TTOU - decrement the number of worker processes by one - -See the [SIGNALS][4] document for full description of all signals -used by Unicorn. - -# SEE ALSO - -* unicorn(1) -* *Rack::Builder* ri/RDoc -* *Unicorn::Configurator* ri/RDoc -* [Unicorn RDoc][1] -* [Rack RDoc][2] -* [Rackup HowTo][3] - -[1]: http://unicorn.bogomips.org/ -[2]: http://rdoc.info/gems/r#/gems/rack/frames -[3]: http://wiki.github.com/rack/rack/tutorial-rackup-howto -[4]: http://unicorn.bogomips.org/SIGNALS.html diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/FAQ b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/FAQ deleted file mode 100644 index c84a8af..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/FAQ +++ /dev/null @@ -1,53 +0,0 @@ -= Frequently Asked Questions about Unicorn - -=== I've installed Rack 1.1.x, why can't Unicorn load Rails (2.3.5)? - -Rails 2.3.5 is not compatible with Rack 1.1.x. Unicorn is compatible -with both Rack 1.1.x and Rack 1.0.x, and RubyGems will load the latest -version of Rack installed on the system. Uninstalling the Rack 1.1.x -gem should solve gem loading issues with Rails 2.3.5. Rails 2.3.6 -and later correctly support Rack 1.1.x. - -=== Why are my redirects going to "http" URLs when my site uses https? - -If your site is entirely behind https, then Rack applications that use -"rack.url_scheme" can set the following in the Unicorn config file: - - HttpRequest::DEFAULTS["rack.url_scheme"] = "https" - -For frameworks that do not use "rack.url_scheme", you can also -try setting one or both of the following: - - HttpRequest::DEFAULTS["HTTPS"] = "on" - HttpRequest::DEFAULTS["HTTP_X_FORWARDED_PROTO"] = "https" - -Otherwise, you can configure your proxy (nginx) to send the -"X-Forwarded-Proto: https" header only for parts of the site that use -https. For nginx, you can do it with the following line in appropriate -"location" blocks of your nginx config file: - - proxy_set_header X-Forwarded-Proto https; - -=== Why are log messages from Unicorn are unformatted when using Rails? - -Current versions of Rails unfortunately overrides the default Logger -formatter. - -You can undo this behavior with the default logger in your Unicorn -config file: - - Configurator::DEFAULTS[:logger].formatter = Logger::Formatter.new - -Of course you can specify an entirely different logger as well -with the "logger" directive described by Unicorn::Configurator. - -=== Why am I getting "connection refused"/502 errors under high load? - -Short answer: your application cannot keep up. - -You can increase the size of the :backlog parameter if your kernel -supports a larger listen() queue, but keep in mind having a large listen -queue makes failover to a different machine more difficult. - -See the TUNING and Unicorn::Configurator documents for more information -on :backlog-related topics. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/GIT-VERSION-GEN b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/GIT-VERSION-GEN deleted file mode 100755 index ad3e0f8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/GIT-VERSION-GEN +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env ruby -DEF_VER = "v4.8.3" -CONSTANT = "Unicorn::Const::UNICORN_VERSION" -RVF = "lib/unicorn/version.rb" -GVF = "GIT-VERSION-FILE" -vn = DEF_VER - -# First see if there is a version file (included in release tarballs), -# then try git-describe, then default. -if File.exist?(".git") - describe = `git describe --abbrev=4 HEAD 2>/dev/null`.strip - case describe - when /\Av[0-9]*/ - vn = describe - system(*%w(git update-index -q --refresh)) - unless `git diff-index --name-only HEAD --`.chomp.empty? - vn << "-dirty" - end - vn.tr!('-', '.') - end -end - -vn = vn.sub!(/\Av/, "") - -# generate the Ruby constant -new_ruby_version = "#{CONSTANT} = '#{vn}'\n" -cur_ruby_version = File.read(RVF) rescue nil -if new_ruby_version != cur_ruby_version - File.open(RVF, "w") { |fp| fp.write(new_ruby_version) } -end - -# generate the makefile snippet -new_make_version = "GIT_VERSION = #{vn}\n" -cur_make_version = File.read(GVF) rescue nil -if new_make_version != cur_make_version - File.open(GVF, "w") { |fp| fp.write(new_make_version) } -end - -puts vn if $0 == __FILE__ diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/GNUmakefile b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/GNUmakefile deleted file mode 100644 index 00a6ace..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/GNUmakefile +++ /dev/null @@ -1,267 +0,0 @@ -# use GNU Make to run tests in parallel, and without depending on RubyGems -all:: test - -RLFLAGS = -G2 - -MRI = ruby -RUBY = ruby -RAKE = rake -RAGEL = ragel -RSYNC = rsync - -GIT-VERSION-FILE: .FORCE-GIT-VERSION-FILE - @./GIT-VERSION-GEN --include GIT-VERSION-FILE --include local.mk -ruby_bin := $(shell which $(RUBY)) -ifeq ($(DLEXT),) # "so" for Linux - DLEXT := $(shell $(RUBY) -rrbconfig -e 'puts RbConfig::CONFIG["DLEXT"]') -endif -ifeq ($(RUBY_VERSION),) - RUBY_VERSION := $(shell $(RUBY) -e 'puts RUBY_VERSION') -endif - -RUBY_ENGINE := $(shell $(RUBY) -e 'puts((RUBY_ENGINE rescue "ruby"))') - -isolate_libs := tmp/isolate/$(RUBY_ENGINE)-$(RUBY_VERSION).mk -$(isolate_libs): script/isolate_for_tests - @$(RUBY) script/isolate_for_tests --include $(isolate_libs) -MYLIBS = $(RUBYLIB):$(ISOLATE_LIBS) - -# dunno how to implement this as concisely in Ruby, and hell, I love awk -awk_slow := awk '/def test_/{print FILENAME"--"$$2".n"}' 2>/dev/null - -slow_tests := test/unit/test_server.rb test/exec/test_exec.rb \ - test/unit/test_signals.rb test/unit/test_upload.rb -log_suffix = .$(RUBY_ENGINE).$(RUBY_VERSION).log -T := $(filter-out $(slow_tests), $(wildcard test/*/test*.rb)) -T_n := $(shell $(awk_slow) $(slow_tests)) -T_log := $(subst .rb,$(log_suffix),$(T)) -T_n_log := $(subst .n,$(log_suffix),$(T_n)) -test_prefix = $(CURDIR)/test/$(RUBY_ENGINE)-$(RUBY_VERSION) - -ext := ext/unicorn_http -c_files := $(ext)/unicorn_http.c $(ext)/httpdate.c $(wildcard $(ext)/*.h) -rl_files := $(wildcard $(ext)/*.rl) -base_bins := unicorn unicorn_rails -bins := $(addprefix bin/, $(base_bins)) -man1_rdoc := $(addsuffix _1, $(base_bins)) -man1_bins := $(addsuffix .1, $(base_bins)) -man1_paths := $(addprefix man/man1/, $(man1_bins)) -rb_files := $(bins) $(shell find lib ext -type f -name '*.rb') -inst_deps := $(c_files) $(rb_files) GNUmakefile test/test_helper.rb - -ragel: $(ext)/unicorn_http.c -$(ext)/unicorn_http.c: $(rl_files) - cd $(@D) && $(RAGEL) unicorn_http.rl -C $(RLFLAGS) -o $(@F) -$(ext)/Makefile: $(ext)/extconf.rb $(c_files) - cd $(@D) && $(RUBY) extconf.rb -$(ext)/unicorn_http.$(DLEXT): $(ext)/Makefile - $(MAKE) -C $(@D) -lib/unicorn_http.$(DLEXT): $(ext)/unicorn_http.$(DLEXT) - @mkdir -p lib - install -m644 $< $@ -http: lib/unicorn_http.$(DLEXT) - -test-install: $(test_prefix)/.stamp -$(test_prefix)/.stamp: $(inst_deps) - mkdir -p $(test_prefix)/.ccache - tar cf - $(inst_deps) GIT-VERSION-GEN | \ - (cd $(test_prefix) && tar xf -) - $(MAKE) -C $(test_prefix) clean - $(MAKE) -C $(test_prefix) http shebang RUBY="$(RUBY)" - > $@ - -# this is only intended to be run within $(test_prefix) -shebang: $(bins) - $(MRI) -i -p -e '$$_.gsub!(%r{^#!.*$$},"#!$(ruby_bin)")' $^ - -t_log := $(T_log) $(T_n_log) -test: $(T) $(T_n) - @cat $(t_log) | $(MRI) test/aggregate.rb - @$(RM) $(t_log) - -test-exec: $(wildcard test/exec/test_*.rb) -test-unit: $(wildcard test/unit/test_*.rb) -$(slow_tests): $(test_prefix)/.stamp - @$(MAKE) $(shell $(awk_slow) $@) - -test-integration: $(test_prefix)/.stamp - $(MAKE) -C t - -check: test test-integration -test-all: check - -TEST_OPTS = -v -check_test = grep '0 failures, 0 errors' $(t) >/dev/null -ifndef V - quiet_pre = @echo '* $(arg)$(extra)'; - quiet_post = >$(t) 2>&1 && $(check_test) -else - # we can't rely on -o pipefail outside of bash 3+, - # so we use a stamp file to indicate success and - # have rm fail if the stamp didn't get created - stamp = $@$(log_suffix).ok - quiet_pre = @echo $(RUBY) $(arg) $(TEST_OPTS); ! test -f $(stamp) && ( - quiet_post = && > $(stamp) )2>&1 | tee $(t); \ - rm $(stamp) 2>/dev/null && $(check_test) -endif - -# not all systems have setsid(8), we need it because we spam signals -# stupidly in some tests... -rb_setsid := $(RUBY) -e 'Process.setsid' -e 'exec *ARGV' - -# TRACER='strace -f -o $(t).strace -s 100000' -run_test = $(quiet_pre) \ - $(rb_setsid) $(TRACER) $(RUBY) -w $(arg) $(TEST_OPTS) $(quiet_post) || \ - (sed "s,^,$(extra): ," >&2 < $(t); exit 1) - -%.n: arg = $(subst .n,,$(subst --, -n ,$@)) -%.n: t = $(subst .n,$(log_suffix),$@) -%.n: export PATH := $(test_prefix)/bin:$(PATH) -%.n: export RUBYLIB := $(test_prefix):$(test_prefix)/lib:$(MYLIBS) -%.n: $(test_prefix)/.stamp - $(run_test) - -$(T): arg = $@ -$(T): t = $(subst .rb,$(log_suffix),$@) -$(T): export PATH := $(test_prefix)/bin:$(PATH) -$(T): export RUBYLIB := $(test_prefix):$(test_prefix)/lib:$(MYLIBS) -$(T): $(test_prefix)/.stamp - $(run_test) - -install: $(bins) $(ext)/unicorn_http.c - $(prep_setup_rb) - $(RM) lib/unicorn_http.$(DLEXT) - $(RM) -r .install-tmp - mkdir .install-tmp - cp -p bin/* .install-tmp - $(RUBY) setup.rb all - $(RM) $^ - mv .install-tmp/* bin/ - $(RM) -r .install-tmp - $(prep_setup_rb) - -setup_rb_files := .config InstalledFiles -prep_setup_rb := @-$(RM) $(setup_rb_files);$(MAKE) -C $(ext) clean - -clean: - -$(MAKE) -C $(ext) clean - -$(MAKE) -C Documentation clean - $(RM) $(ext)/Makefile lib/unicorn_http.$(DLEXT) - $(RM) $(setup_rb_files) $(t_log) - $(RM) -r $(test_prefix) man - -man html: - $(MAKE) -C Documentation install-$@ - -pkg_extra := GIT-VERSION-FILE lib/unicorn/version.rb ChangeLog LATEST NEWS \ - $(ext)/unicorn_http.c $(man1_paths) - -ChangeLog: GIT-VERSION-FILE .wrongdoc.yml - wrongdoc prepare - -.manifest: ChangeLog $(ext)/unicorn_http.c man - (git ls-files && for i in $@ $(pkg_extra); do echo $$i; done) | \ - LC_ALL=C sort > $@+ - cmp $@+ $@ || mv $@+ $@ - $(RM) $@+ - -doc: .document $(ext)/unicorn_http.c man html .wrongdoc.yml - for i in $(man1_rdoc); do echo > $$i; done - find bin lib -type f -name '*.rbc' -exec rm -f '{}' ';' - $(RM) -r doc - wrongdoc all - install -m644 COPYING doc/COPYING - install -m644 $(shell LC_ALL=C grep '^[A-Z]' .document) doc/ - install -m644 $(man1_paths) doc/ - tar cf - $$(git ls-files examples/) | (cd doc && tar xf -) - $(RM) $(man1_rdoc) - -# publishes docs to http://unicorn.bogomips.org -publish_doc: - -git set-file-times - $(MAKE) doc - find doc/images -type f | \ - TZ=UTC xargs touch -d '1970-01-01 00:00:02' doc/rdoc.css - $(MAKE) doc_gz - chmod 644 $$(find doc -type f) - $(RSYNC) -av doc/ unicorn.bogomips.org:/srv/unicorn/ - git ls-files | xargs touch - -# Create gzip variants of the same timestamp as the original so nginx -# "gzip_static on" can serve the gzipped versions directly. -doc_gz: docs = $(shell find doc -type f ! -regex '^.*\.\(gif\|jpg\|png\|gz\)$$') -doc_gz: - for i in $(docs); do \ - gzip --rsyncable -9 < $$i > $$i.gz; touch -r $$i $$i.gz; done - -ifneq ($(VERSION),) -rfproject := mongrel -rfpackage := unicorn -pkggem := pkg/$(rfpackage)-$(VERSION).gem -pkgtgz := pkg/$(rfpackage)-$(VERSION).tgz -release_notes := release_notes-$(VERSION) -release_changes := release_changes-$(VERSION) - -release-notes: $(release_notes) -release-changes: $(release_changes) -$(release_changes): - wrongdoc release_changes > $@+ - $(VISUAL) $@+ && test -s $@+ && mv $@+ $@ -$(release_notes): - wrongdoc release_notes > $@+ - $(VISUAL) $@+ && test -s $@+ && mv $@+ $@ - -# ensures we're actually on the tagged $(VERSION), only used for release -verify: - test x"$(shell umask)" = x0022 - git rev-parse --verify refs/tags/v$(VERSION)^{} - git diff-index --quiet HEAD^0 - test `git rev-parse --verify HEAD^0` = \ - `git rev-parse --verify refs/tags/v$(VERSION)^{}` - -fix-perms: - git ls-tree -r HEAD | awk '/^100644 / {print $$NF}' | xargs chmod 644 - git ls-tree -r HEAD | awk '/^100755 / {print $$NF}' | xargs chmod 755 - -gem: $(pkggem) - -install-gem: $(pkggem) - gem install $(CURDIR)/$< - -$(pkggem): .manifest fix-perms - gem build $(rfpackage).gemspec - mkdir -p pkg - mv $(@F) $@ - -$(pkgtgz): distdir = $(basename $@) -$(pkgtgz): HEAD = v$(VERSION) -$(pkgtgz): .manifest fix-perms - @test -n "$(distdir)" - $(RM) -r $(distdir) - mkdir -p $(distdir) - tar cf - $$(cat .manifest) | (cd $(distdir) && tar xf -) - cd pkg && tar cf - $(basename $(@F)) | gzip -9 > $(@F)+ - mv $@+ $@ - -package: $(pkgtgz) $(pkggem) - -release: verify package $(release_notes) $(release_changes) - # make tgz release on RubyForge - rubyforge add_release -f -n $(release_notes) -a $(release_changes) \ - $(rfproject) $(rfpackage) $(VERSION) $(pkgtgz) - # push gem to Gemcutter - gem push $(pkggem) - # in case of gem downloads from RubyForge releases page - -rubyforge add_file \ - $(rfproject) $(rfpackage) $(VERSION) $(pkggem) - $(RAKE) fm_update VERSION=$(VERSION) -else -gem install-gem: GIT-VERSION-FILE - $(MAKE) $@ VERSION=$(GIT_VERSION) -endif - -.PHONY: .FORCE-GIT-VERSION-FILE doc $(T) $(slow_tests) man -.PHONY: test-install diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/HACKING b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/HACKING deleted file mode 100644 index acb9f9d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/HACKING +++ /dev/null @@ -1,137 +0,0 @@ -= Unicorn Hacker's Guide - -== Polyglot Infrastructure - -Like Mongrel, we use Ruby where it makes sense, and Ragel with C where -it helps performance. All of the code that actually runs your Rack -application is written Ruby, Ragel or C. - -As far as tests and documentation goes, we're not afraid to embrace Unix -and use traditional Unix tools where they make sense and get the job -done. - -=== Tests - -Tests are good, but slow tests make development slow, so we make tests -faster (in parallel) with GNU make (instead of Rake) and avoiding -RubyGems. - -Users of GNU-based systems (such as GNU/Linux) usually have GNU make -installed as "make" instead of "gmake". - -Since we don't load RubyGems by default, loading Rack properly requires -setting up RUBYLIB to point to where Rack is located. Not loading -RubyGems drastically lowers the time to run the full test suite. You -may setup a "local.mk" file in the top-level working directory to setup -your RUBYLIB and any other environment variables. A "local.mk.sample" -file is provided for reference. - -Running the entire test suite with 4 tests in parallel: - - gmake -j4 check - -Running just one unit test: - - gmake test/unit/test_http_parser.rb - -Running just one test case in a unit test: - - gmake test/unit/test_http_parser.rb--test_parse_simple.n - -=== HttpServer - -We strive to write as little code as possible while still maintaining -readability. However, readability and flexibility may be sacrificed for -performance in hot code paths. For Ruby, less code generally means -faster code. - -Memory allocation should be minimized as much as practically possible. -Buffers for IO#readpartial are preallocated in the hot paths to avoid -building up garbage. Hash assignments use frozen strings to avoid the -duplication behind-the-scenes. - -We spend as little time as possible inside signal handlers and instead -defer handling them for predictability and robustness. Most of the -Unix-specific things are in the Unicorn::HttpServer class. Unix systems -programming experience will come in handy (or be learned) here. - -=== Documentation - -We use RDoc 2.5.x with Darkfish for documentation as much as possible, -if you're on Ruby 1.8 you want to install the latest "rdoc" gem. Due to -the lack of RDoc-to-manpage converters we know about, we're writing -manpages in Markdown and converting to troff/HTML with Pandoc. - -Please wrap documentation at 72 characters-per-line or less (long URLs -are exempt) so it is comfortably readable from terminals. - -When referencing mailing list posts, use -"http://bogomips.org/unicorn-public/m/$MESSAGE_ID.html" if possible -since the Message-ID remains searchable even if a particular site -becomes unavailable. - -=== Ruby/C Compatibility - -We target Ruby 1.8.6+, 1.9 and will target Rubinius as it becomes -production-ready. We need the Ruby implementation to support fork, -exec, pipe, UNIX signals, access to integer file descriptors and -ability to use unlinked files. - -All of our C code is OS-independent and should run on compilers -supported by the versions of Ruby we target. - -=== Ragel Compatibility - -We target the latest released version of Ragel and will update our code -to keep up with new releases. Packaged tarballs and gems include the -generated source code so they will remain usable if compatibility is -broken. - -== Contributing - -Contributions are welcome in the form of patches, pull requests, code -review, testing, documentation, user support or any other feedback is -welcome. The mailing list is the central coordination point for all -user and developer feedback and bug reports. - -=== Submitting Patches - -Follow conventions already established in the code and do not exceed 80 -characters per line. - -Inline patches (from "git format-patch -M") to the mailing list are -preferred because they allow code review and comments in the reply to -the patch. - -We will adhere to mostly the same conventions for patch submissions as -git itself. See the -{SubmittingPatches}[https://git.kernel.org/cgit/git/git.git/tree/Documentation/SubmittingPatches] -document -distributed with git on on patch submission guidelines to follow. Just -don't email the git mailing list or maintainer with Unicorn patches :) - -== Building a Gem - -In order to build the gem, you must install the following components: - - * wrongdoc - * pandoc - -You can build the Unicorn gem with the following command: - - gmake gem - -== Running Development Versions - -It is easy to install the contents of your git working directory: - -Via RubyGems (RubyGems 1.3.5+ recommended for prerelease versions): - - gmake install-gem - -Without RubyGems (via setup.rb): - - gmake install - -It is not at all recommended to mix a RubyGems installation with an -installation done without RubyGems, however. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ISSUES b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ISSUES deleted file mode 100644 index bca7f9f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ISSUES +++ /dev/null @@ -1,60 +0,0 @@ -= Issues - -mailto:unicorn-public@bogomips.org is the best place to report bugs, -submit patches and/or obtain support after you have searched the -{email archives}[http://bogomips.org/unicorn-public/] and -{documentation}[http://unicorn.bogomips.org/]. - -* No subscription will ever be required to email the public inbox. -* Please Cc: all participants in a thread, as there are no subscribers -* Do not {top post}[http://catb.org/jargon/html/T/top-post.html] in replies -* Quote as little as possible of the message you're replying to -* Do not send HTML mail, it will likely be flagged as spam - -If your issue is of a sensitive nature or you're just shy in public, -then feel free to email us privately at mailto:unicorn@bogomips.org -instead and your issue will be handled discreetly. - -If you don't get a response within a few days, we may have forgotten -about it so feel free to ask again. - -== Submitting Patches - -See the HACKING document (and additionally, the -{SubmittingPatches}[https://git.kernel.org/cgit/git/git.git/tree/Documentation/SubmittingPatches] -document distributed with git) on guidelines for patch submission. - -== Contact Info - -* public: mailto:unicorn-public@bogomips.org -* private: mailto:unicorn@bogomips.org - -We operate a {public-inbox}[http://public-inbox.org/]. -You may subscribe using {ssoma}[http://ssoma.public-inbox.org/]: - - URL=git://bogomips.org/unicorn-public - LISTNAME=unicorn - - # to initialize a maildir (this may be a new or existing maildir, - # ssoma will not touch existing messages) - # If you prefer mbox, use mbox:/path/to/mbox as the last argument - # You may also use imap://$MAILSERVER/INBOX for an IMAP account - # or imaps:// for an IMAPS account, as well. - ssoma add $LISTNAME $URL maildir:/path/to/maildir - - # read with your favorite MUA (only using mutt as an example) - mutt -f /path/to/maildir # (or /path/to/mbox) - - # to keep your mbox or maildir up-to-date, periodically run the following: - ssoma sync $LISTNAME - - # your MUA may modify and delete messages from the maildir or mbox, - # this does not affect ssoma functionality at all - - # to sync all your ssoma subscriptions - ssoma sync - - # You may wish to sync in your cronjob - ssoma sync --cron - -HTML archives are available here: http://bogomips.org/unicorn-public/ diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/KNOWN_ISSUES b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/KNOWN_ISSUES deleted file mode 100644 index 38263e7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/KNOWN_ISSUES +++ /dev/null @@ -1,79 +0,0 @@ -= Known Issues - -Occasionally odd {issues}[link:ISSUES.html] arise without a transparent or -acceptable solution. Those issues are documented here. - -* Some libraries/applications may install signal handlers which conflict - with signal handlers unicorn uses. Leaving "preload_app false" - (the default) will allow unicorn to always override existing signal - handlers. - -* Issues with FreeBSD jails can be worked around as documented by Tatsuya Ono: - http://mid.gmane.org/CAHBuKRj09FdxAgzsefJWotexw-7JYZGJMtgUp_dhjPz9VbKD6Q@mail.gmail.com - -* PRNGs (pseudo-random number generators) loaded before forking - (e.g. "preload_app true") may need to have their internal state - reset in the after_fork hook. Starting with \Unicorn 3.6.1, we - have builtin workarounds for Kernel#rand and OpenSSL::Random users, - but applications may use other PRNGs. - -* Under some versions of Ruby 1.8, it is necessary to call +srand+ in an - after_fork hook to get correct random number generation. We have a builtin - workaround for this starting with \Unicorn 3.6.1 - - See http://redmine.ruby-lang.org/issues/show/4338 - -* On Ruby 1.8 prior to Ruby 1.8.7-p248, *BSD platforms have a broken - stdio that causes failure for file uploads larger than 112K. Upgrade - your version of Ruby or continue using Unicorn 1.x/3.4.x. - -* For notes on sandboxing tools such as Bundler or Isolate, - see the {Sandbox}[link:Sandbox.html] page. - -* nginx with "sendfile on" under FreeBSD 8 is broken when - uploads are buffered to disk. Disabling sendfile is required to - work around this bug which should be fixed in newer versions of FreeBSD. - -* When using "preload_app true", with apps using background threads - need to restart them in the after_fork hook because threads are never - shared with child processes. Additionally, any synchronization - primitives (Mutexes, Monitors, ConditionVariables) should be - reinitialized in case they are held during fork time to avoid - deadlocks. The core Ruby Logger class needlessly uses a MonitorMutex - which can be disabled with a {monkey patch}[link:examples/logger_mp_safe.rb] - -== Known Issues (Old) - -* Under Ruby 1.9.1, methods like Array#shuffle and Array#sample will - segfault if called after forking. Upgrade to Ruby 1.9.2 or call - "Kernel.rand" in your after_fork hook to reinitialize the random - number generator. - - See http://redmine.ruby-lang.org/issues/show/2962 for more details - -* Rails 2.3.2 bundles its own version of Rack. This may cause subtle - bugs when simultaneously loaded with the system-wide Rack Rubygem - which Unicorn depends on. Upgrading to Rails 2.3.4 (or later) is - strongly recommended for all Rails 2.3.x users for this (and security - reasons). Rails 2.2.x series (or before) did not bundle Rack and are - should be unnaffected. If there is any reason which forces your - application to use Rails 2.3.2 and you have no other choice, then - you may edit your Unicorn gemspec and remove the Rack dependency. - - ref: http://mid.gmane.org/20091014221552.GA30624@dcvr.yhbt.net - Note: the workaround described in the article above only made - the issue more subtle and we didn't notice them immediately. - -* WONTFIX: code reloading and restarts with Sinatra 0.3.x (and likely older - versions) apps is broken. The workaround is to force production - mode to disable code reloading as well as disabling "run" in your - Sinatra application: - set :env, :production - set :run, false - Since this is no longer an issue with Sinatra 0.9.x apps, this will not be - fixed on our end. Since Unicorn is itself the application launcher, the - at_exit handler used in old Sinatra always caused Mongrel to be launched - whenever a Unicorn worker was about to exit. - - Also remember we're capable of replacing the running binary without dropping - any connections regardless of framework :) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/LICENSE b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/LICENSE deleted file mode 100644 index 5b6458e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/LICENSE +++ /dev/null @@ -1,67 +0,0 @@ -Unicorn is copyrighted free software by all contributors, see logs in -revision control for names and email addresses of all of them. - -You can redistribute it and/or modify it under either the terms of the -GNU General Public License (GPL) as published by the Free Software -Foundation (FSF), either version 2 of the License, or (at your option) -any later version. We currently prefer the GPLv3 or later for -derivative works, but the GPLv2 is fine. - -The complete texts of the GPLv2 and GPLv3 are below: -GPLv2 - http://www.gnu.org/licenses/gpl-2.0.txt -GPLv3 - http://www.gnu.org/licenses/gpl-3.0.txt - -You may (against our _preference_) also use the Ruby 1.8 license terms -which we inherited from the original Mongrel project when we forked it: - -=== Ruby 1.8-specific terms (if you're not using the GPL) - - 1. You may make and give away verbatim copies of the source form of the - software without restriction, provided that you duplicate all of the - original copyright notices and associated disclaimers. - - 2. You may modify your copy of the software in any way, provided that - you do at least ONE of the following: - - a) place your modifications in the Public Domain or otherwise make them - Freely Available, such as by posting said modifications to Usenet or an - equivalent medium, or by allowing the author to include your - modifications in the software. - - b) use the modified software only within your corporation or - organization. - - c) rename any non-standard executables so the names do not conflict with - standard executables, which must also be provided. - - d) make other distribution arrangements with the author. - - 3. You may distribute the software in object code or executable - form, provided that you do at least ONE of the following: - - a) distribute the executables and library files of the software, - together with instructions (in the manual page or equivalent) on where - to get the original distribution. - - b) accompany the distribution with the machine-readable source of the - software. - - c) give non-standard executables non-standard names, with - instructions on where to get the original software distribution. - - d) make other distribution arrangements with the author. - - 4. You may modify and include the part of the software into any other - software (possibly commercial). But some files in the distribution - are not written by the author, so that they are not under this terms. - - 5. The scripts and library files supplied as input to or produced as - output from the software do not automatically fall under the - copyright of the software, but belong to whomever generated them, - and may be sold commercially, and may be aggregated with this - software. - - 6. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR - IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Links b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Links deleted file mode 100644 index 0355850..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Links +++ /dev/null @@ -1,56 +0,0 @@ -= Related Projects - -If you're interested in \Unicorn, you may be interested in some of the projects -listed below. If you have any links to add/change/remove, please tell us at -mailto:unicorn-public@bogomips.org! - -== Disclaimer - -The \Unicorn project is not responsible for the content in these links. -Furthermore, the \Unicorn project has never, does not and will never endorse: - -* any for-profit entities or services -* any non-{Free Software}[http://www.gnu.org/philosophy/free-sw.html] - -The existence of these links does not imply endorsement of any entities -or services behind them. - -=== For use with \Unicorn - -* {Bluepill}[https://github.com/arya/bluepill] - - a simple process monitoring tool written in Ruby - -* {golden_brindle}[https://github.com/simonoff/golden_brindle] - tool to - manage multiple \Unicorn instances/applications on a single server - -* {raindrops}[http://raindrops.bogomips.org/] - real-time stats for - preforking Rack servers - -* {UnXF}[http://bogomips.org/unxf/] Un-X-Forward* the Rack environment, - useful since unicorn is designed to be deployed behind a reverse proxy. - -=== \Unicorn is written to work with - -* {Rack}[http://rack.github.io/] - a minimal interface between webservers - supporting Ruby and Ruby frameworks - -* {Ruby}[http://www.ruby-lang.org/] - the programming language of Rack and \Unicorn - -* {nginx}[http://nginx.org/] - the reverse proxy for use with \Unicorn - -* {kgio}[http://bogomips.org/kgio/] - the I/O library written for \Unicorn - -=== Derivatives - -* {Green Unicorn}[http://gunicorn.org/] - a Python version of \Unicorn - -* {Rainbows!}[http://rainbows.bogomips.org/] - \Unicorn for sleepy - apps and slow clients. - -=== Prior Work - -* {Mongrel}[http://rubygems.org/gems/mongrel] - the awesome webserver - unicorn is based on - -* {david}[http://bogomips.org/david.git] - a tool to explain why you need - nginx in front of \Unicorn diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/PHILOSOPHY b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/PHILOSOPHY deleted file mode 100644 index 18b2d82..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/PHILOSOPHY +++ /dev/null @@ -1,145 +0,0 @@ -= The Philosophy Behind unicorn - -Being a server that only runs on Unix-like platforms, unicorn is -strongly tied to the Unix philosophy of doing one thing and (hopefully) -doing it well. Despite using HTTP, unicorn is strictly a _backend_ -application server for running Rack-based Ruby applications. - -== Avoid Complexity - -Instead of attempting to be efficient at serving slow clients, unicorn -relies on a buffering reverse proxy to efficiently deal with slow -clients. - -unicorn uses an old-fashioned preforking worker model with blocking I/O. -Our processing model is the antithesis of more modern (and theoretically -more efficient) server processing models using threads or non-blocking -I/O with events. - -=== Threads and Events Are Hard - -...to many developers. Reasons for this is beyond the scope of this -document. unicorn avoids concurrency within each worker process so you -have fewer things to worry about when developing your application. Of -course unicorn can use multiple worker processes to utilize multiple -CPUs or spindles. Applications can still use threads internally, however. - -== Slow Clients Are Problematic - -Most benchmarks we've seen don't tell you this, and unicorn doesn't -care about slow clients... but you should. - -A "slow client" can be any client outside of your datacenter. Network -traffic within a local network is always faster than traffic that -crosses outside of it. The laws of physics do not allow otherwise. - -Persistent connections were introduced in HTTP/1.1 reduce latency from -connection establishment and TCP slow start. They also waste server -resources when clients are idle. - -Persistent connections mean one of the unicorn worker processes -(depending on your application, it can be very memory hungry) would -spend a significant amount of its time idle keeping the connection alive -and not doing anything else. Being single-threaded and using -blocking I/O, a worker cannot serve other clients while keeping a -connection alive. Thus unicorn does not implement persistent -connections. - -If your application responses are larger than the socket buffer or if -you're handling large requests (uploads), worker processes will also be -bottlenecked by the speed of the *client* connection. You should -not allow unicorn to serve clients outside of your local network. - -== Application Concurrency != Network Concurrency - -Performance is asymmetric across the different subsystems of the machine -and parts of the network. CPUs and main memory can process gigabytes of -data in a second; clients on the Internet are usually only capable of a -tiny fraction of that. unicorn deployments should avoid dealing with -slow clients directly and instead rely on a reverse proxy to shield it -from the effects of slow I/O. - -== Improved Performance Through Reverse Proxying - -By acting as a buffer to shield unicorn from slow I/O, a reverse proxy -will inevitably incur overhead in the form of extra data copies. -However, as I/O within a local network is fast (and faster still -with local sockets), this overhead is negligible for the vast majority -of HTTP requests and responses. - -The ideal reverse proxy complements the weaknesses of unicorn. -A reverse proxy for unicorn should meet the following requirements: - -1. It should fully buffer all HTTP requests (and large responses). - Each request should be "corked" in the reverse proxy and sent - as fast as possible to the backend unicorn processes. This is - the most important feature to look for when choosing a - reverse proxy for unicorn. - -2. It should spend minimal time in userspace. Network (and disk) I/O - are system-level tasks and usually managed by the kernel. - This may change if userspace TCP stacks become more popular in the - future; but the reverse proxy should not waste time with - application-level logic. These concerns should be separated - -3. It should avoid context switches and CPU scheduling overhead. - In many (most?) cases, network devices and their interrupts are - only be handled by one CPU at a time. It should avoid contention - within the system by serializing all network I/O into one (or few) - userspace processes. Network I/O is not a CPU-intensive task and - it is not helpful to use multiple CPU cores (at least not for GigE). - -4. It should efficiently manage persistent connections (and - pipelining) to slow clients. If you care to serve slow clients - outside your network, then these features of HTTP/1.1 will help. - -5. It should (optionally) serve static files. If you have static - files on your site (especially large ones), they are far more - efficiently served with as few data copies as possible (e.g. with - sendfile() to completely avoid copying the data to userspace). - -nginx is the only (Free) solution we know of that meets the above -requirements. - -Indeed, the folks behind unicorn have deployed nginx as a reverse-proxy not -only for Ruby applications, but also for production applications running -Apache/mod_perl, Apache/mod_php and Apache Tomcat. In every single -case, performance improved because application servers were able to use -backend resources more efficiently and spend less time waiting on slow -I/O. - -== Worse Is Better - -Requirements and scope for applications change frequently and -drastically. Thus languages like Ruby and frameworks like Rails were -built to give developers fewer things to worry about in the face of -rapid change. - -On the other hand, stable protocols which host your applications (HTTP -and TCP) only change rarely. This is why we recommend you NOT tie your -rapidly-changing application logic directly into the processes that deal -with the stable outside world. Instead, use HTTP as a common RPC -protocol to communicate between your frontend and backend. - -In short: separate your concerns. - -Of course a theoretical "perfect" solution would combine the pieces -and _maybe_ give you better performance at the end of the day, but -that is not the Unix way. - -== Just Worse in Some Cases - -unicorn is not suited for all applications. unicorn is optimized for -applications that are CPU/memory/disk intensive and spend little time -waiting on external resources (e.g. a database server or external API). - -unicorn is highly inefficient for Comet/reverse-HTTP/push applications -where the HTTP connection spends a large amount of time idle. -Nevertheless, the ease of troubleshooting, debugging, and management of -unicorn may still outweigh the drawbacks for these applications. - -The {Rainbows!}[http://rainbows.bogomips.org/] aims to fill the gap for -odd corner cases where the nginx + unicorn combination is not enough. -While Rainbows! management/administration is largely identical to -unicorn, Rainbows! is far more ambitious and has seen little real-world -usage. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/README b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/README deleted file mode 100644 index 1bd42b8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/README +++ /dev/null @@ -1,145 +0,0 @@ -= Unicorn: Rack HTTP server for fast clients and Unix - -\Unicorn is an HTTP server for Rack applications designed to only serve -fast clients on low-latency, high-bandwidth connections and take -advantage of features in Unix/Unix-like kernels. Slow clients should -only be served by placing a reverse proxy capable of fully buffering -both the the request and response in between \Unicorn and slow clients. - -== Features - -* Designed for Rack, Unix, fast clients, and ease-of-debugging. We - cut out everything that is better supported by the operating system, - {nginx}[http://nginx.net/] or {Rack}[http://rack.github.io/]. - -* Compatible with Ruby 1.8 and later. Rubinius support is in-progress. - -* Process management: \Unicorn will reap and restart workers that - die from broken apps. There is no need to manage multiple processes - or ports yourself. \Unicorn can spawn and manage any number of - worker processes you choose to scale to your backend. - -* Load balancing is done entirely by the operating system kernel. - Requests never pile up behind a busy worker process. - -* Does not care if your application is thread-safe or not, workers - all run within their own isolated address space and only serve one - client at a time for maximum robustness. - -* Supports all Rack applications, along with pre-Rack versions of - Ruby on Rails via a Rack wrapper. - -* Builtin reopening of all log files in your application via - USR1 signal. This allows logrotate to rotate files atomically and - quickly via rename instead of the racy and slow copytruncate method. - \Unicorn also takes steps to ensure multi-line log entries from one - request all stay within the same file. - -* nginx-style binary upgrades without losing connections. - You can upgrade \Unicorn, your entire application, libraries - and even your Ruby interpreter without dropping clients. - -* before_fork and after_fork hooks in case your application - has special needs when dealing with forked processes. These - should not be needed when the "preload_app" directive is - false (the default). - -* Can be used with copy-on-write-friendly memory management - to save memory (by setting "preload_app" to true). - -* Able to listen on multiple interfaces including UNIX sockets, - each worker process can also bind to a private port via the - after_fork hook for easy debugging. - -* Simple and easy Ruby DSL for configuration. - -* Decodes chunked transfers on-the-fly, thus allowing upload progress - notification to be implemented as well as being able to tunnel - arbitrary stream-based protocols over HTTP. - -== License - -\Unicorn is copyright 2009 by all contributors (see logs in git). -It is based on Mongrel 1.1.5. -Mongrel is copyright 2007 Zed A. Shaw and contributors. - -\Unicorn is licensed under (your choice) of the GPLv2 or later -(GPLv3+ preferred), or Ruby (1.8)-specific terms. -See the included LICENSE file for details. - -\Unicorn is 100% Free Software. - -== Install - -The library consists of a C extension so you'll need a C compiler -and Ruby development libraries/headers. - -You may install it via RubyGems on RubyGems.org: - - gem install unicorn - -You can get the latest source via git from the following locations -(these versions may not be stable): - - git://bogomips.org/unicorn.git - git://repo.or.cz/unicorn.git (mirror) - -You may browse the code from the web and download the latest snapshot -tarballs here: - -* http://bogomips.org/unicorn.git (cgit) -* http://repo.or.cz/w/unicorn.git (gitweb) - -See the HACKING guide on how to contribute and build prerelease gems -from git. - -== Usage - -=== non-Rails Rack applications - -In APP_ROOT, run: - - unicorn - -=== for Rails applications (should work for all 1.2 or later versions) - -In RAILS_ROOT, run: - - unicorn_rails - -\Unicorn will bind to all interfaces on TCP port 8080 by default. -You may use the +--listen/-l+ switch to bind to a different -address:port or a UNIX socket. - -=== Configuration File(s) - -\Unicorn will look for the config.ru file used by rackup in APP_ROOT. - -For deployments, it can use a config file for \Unicorn-specific options -specified by the +--config-file/-c+ command-line switch. See -Unicorn::Configurator for the syntax of the \Unicorn-specific options. -The default settings are designed for maximum out-of-the-box -compatibility with existing applications. - -Most command-line options for other Rack applications (above) are also -supported. Run `unicorn -h` or `unicorn_rails -h` to see command-line -options. - -== Disclaimer - -There is NO WARRANTY whatsoever if anything goes wrong, but -{let us know}[link:ISSUES.html] and we'll try our best to fix it. - -\Unicorn is designed to only serve fast clients either on the local host -or a fast LAN. See the PHILOSOPHY and DESIGN documents for more details -regarding this. - -== Contact - -All feedback (bug reports, user/development dicussion, patches, pull -requests) go to the mailing list/newsgroup. See the ISSUES document for -information on the {mailing list}[mailto:unicorn-public@bogomips.org]. - -For the latest on \Unicorn releases, you may also finger us at -unicorn@bogomips.org or check our NEWS page (and subscribe to our Atom -feed). diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Rakefile b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Rakefile deleted file mode 100644 index 01ff5d0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Rakefile +++ /dev/null @@ -1,60 +0,0 @@ -# -*- encoding: binary -*- -autoload :Gem, 'rubygems' -require 'wrongdoc' - -cgit_url = Wrongdoc.config[:cgit_url] -git_url = Wrongdoc.config[:git_url] - -desc "post to FM" -task :fm_update do - require 'tempfile' - require 'net/http' - require 'net/netrc' - require 'json' - version = ENV['VERSION'] or abort "VERSION= needed" - uri = URI.parse('https://freecode.com/projects/unicorn/releases.json') - rc = Net::Netrc.locate('unicorn-fm') or abort "~/.netrc not found" - api_token = rc.password - _, subject, body = `git cat-file tag v#{version}`.split(/\n\n/, 3) - tmp = Tempfile.new('fm-changelog') - tmp.puts subject - tmp.puts - tmp.puts body - tmp.flush - system(ENV["VISUAL"], tmp.path) or abort "#{ENV["VISUAL"]} failed: #$?" - changelog = File.read(tmp.path).strip - - req = { - "auth_code" => api_token, - "release" => { - "tag_list" => "Experimental", - "version" => version, - "changelog" => changelog, - }, - }.to_json - - if ! changelog.strip.empty? && version =~ %r{\A[\d\.]+\d+\z} - Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http| - p http.post(uri.path, req, {'Content-Type'=>'application/json'}) - end - else - warn "not updating freshmeat for v#{version}" - end -end - -# optional rake-compiler support in case somebody needs to cross compile -begin - mk = "ext/unicorn_http/Makefile" - if File.readable?(mk) - warn "run 'gmake -C ext/unicorn_http clean' and\n" \ - "remove #{mk} before using rake-compiler" - elsif ENV['VERSION'] - unless File.readable?("ext/unicorn_http/unicorn_http.c") - abort "run 'gmake ragel' or 'make ragel' to generate the Ragel source" - end - spec = Gem::Specification.load('unicorn.gemspec') - require 'rake/extensiontask' - Rake::ExtensionTask.new('unicorn_http', spec) - end -rescue LoadError -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/SIGNALS b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/SIGNALS deleted file mode 100644 index ef0b0d9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/SIGNALS +++ /dev/null @@ -1,123 +0,0 @@ -== Signal handling - -In general, signals need only be sent to the master process. However, -the signals Unicorn uses internally to communicate with the worker -processes are documented here as well. With the exception of TTIN/TTOU, -signal handling matches the behavior of {nginx}[http://nginx.net/] so it -should be possible to easily share process management scripts between -Unicorn and nginx. - -One example init script is distributed with unicorn: -http://unicorn.bogomips.org/examples/init.sh - -=== Master Process - -* HUP - reloads config file and gracefully restart all workers. - If the "preload_app" directive is false (the default), then workers - will also pick up any application code changes when restarted. If - "preload_app" is true, then application code changes will have no - effect; USR2 + QUIT (see below) must be used to load newer code in - this case. When reloading the application, +Gem.refresh+ will - be called so updated code for your application can pick up newly - installed RubyGems. It is not recommended that you uninstall - libraries your application depends on while Unicorn is running, - as respawned workers may enter a spawn loop when they fail to - load an uninstalled dependency. - -* INT/TERM - quick shutdown, kills all workers immediately - -* QUIT - graceful shutdown, waits for workers to finish their - current request before finishing. - -* USR1 - reopen all logs owned by the master and all workers - See Unicorn::Util.reopen_logs for what is considered a log. - -* USR2 - reexecute the running binary. A separate QUIT - should be sent to the original process once the child is verified to - be up and running. - -* WINCH - gracefully stops workers but keep the master running. - This will only work for daemonized processes. - -* TTIN - increment the number of worker processes by one - -* TTOU - decrement the number of worker processes by one - -=== Worker Processes - -Note: as of unicorn 4.8, the master uses a pipe to signal workers -instead of kill(2) for most cases. Using signals still (and works and -remains supported for external tools/libraries), however. - -Sending signals directly to the worker processes should not normally be -needed. If the master process is running, any exited worker will be -automatically respawned. - -* INT/TERM - Quick shutdown, immediately exit. - Unless WINCH has been sent to the master (or the master is killed), - the master process will respawn a worker to replace this one. - Immediate shutdown is still triggered using kill(2) and not the - internal pipe as of unicorn 4.8 - -* QUIT - Gracefully exit after finishing the current request. - Unless WINCH has been sent to the master (or the master is killed), - the master process will respawn a worker to replace this one. - -* USR1 - Reopen all logs owned by the worker process. - See Unicorn::Util.reopen_logs for what is considered a log. - Log files are not reopened until it is done processing - the current request, so multiple log lines for one request - (as done by Rails) will not be split across multiple logs. - - It is NOT recommended to send the USR1 signal directly to workers via - "killall -USR1 unicorn" if you are using user/group-switching support - in your workers. You will encounter incorrect file permissions and - workers will need to be respawned. Sending USR1 to the master process - first will ensure logs have the correct permissions before the master - forwards the USR1 signal to workers. - -=== Procedure to replace a running unicorn executable - -You may replace a running instance of unicorn with a new one without -losing any incoming connections. Doing so will reload all of your -application code, Unicorn config, Ruby executable, and all libraries. -The only things that will not change (due to OS limitations) are: - -1. The path to the unicorn executable script. If you want to change to - a different installation of Ruby, you can modify the shebang - line to point to your alternative interpreter. - -The procedure is exactly like that of nginx: - -1. Send USR2 to the master process - -2. Check your process manager or pid files to see if a new master spawned - successfully. If you're using a pid file, the old process will have - ".oldbin" appended to its path. You should have two master instances - of unicorn running now, both of which will have workers servicing - requests. Your process tree should look something like this: - - unicorn master (old) - \_ unicorn worker[0] - \_ unicorn worker[1] - \_ unicorn worker[2] - \_ unicorn worker[3] - \_ unicorn master - \_ unicorn worker[0] - \_ unicorn worker[1] - \_ unicorn worker[2] - \_ unicorn worker[3] - -3. You can now send WINCH to the old master process so only the new workers - serve requests. If your unicorn process is bound to an interactive - terminal (not daemonized), you can skip this step. Step 5 will be more - difficult but you can also skip it if your process is not daemonized. - -4. You should now ensure that everything is running correctly with the - new workers as the old workers die off. - -5. If everything seems ok, then send QUIT to the old master. You're done! - - If something is broken, then send HUP to the old master to reload - the config and restart its workers. Then send QUIT to the new master - process. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Sandbox b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Sandbox deleted file mode 100644 index 3c7f226..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/Sandbox +++ /dev/null @@ -1,103 +0,0 @@ -= Tips for using \Unicorn with Sandbox installation tools - -Since unicorn includes executables and is usually used to start a Ruby -process, there are certain caveats to using it with tools that sandbox -RubyGems installations such as -{Bundler}[http://gembundler.com/] or -{Isolate}[http://github.com/jbarnette/isolate]. - -== General deployment - -If you're sandboxing your unicorn installation and using Capistrano (or -similar), it's required that you sandbox your RubyGems in a per-application -shared directory that can be used between different revisions. - -unicorn will stash its original command-line at startup for the USR2 -upgrades, and cleaning up old revisions will cause revision-specific -installations of unicorn to go missing and upgrades to fail. If you -find yourself in this situation and can't afford downtime, you can -override the existing unicorn executable path in the config file like -this: - - Unicorn::HttpServer::START_CTX[0] = "/some/path/to/bin/unicorn" - -Then use HUP to reload, and then continue with the USR2+QUIT upgrade -sequence. - -Environment variable pollution when exec-ing a new process (with USR2) -is the primary issue with sandboxing tools such as Bundler and Isolate. - -== Bundler - -=== Running - -If you're bundling unicorn, use "bundle exec unicorn" (or "bundle exec -unicorn_rails") to start unicorn with the correct environment variables - -ref: http://mid.gmane.org/9ECF07C4-5216-47BE-961D-AFC0F0C82060@internetfamo.us - -Otherwise (if you choose to not sandbox your unicorn installation), we -expect the tips for Isolate (below) apply, too. - -=== RUBYOPT pollution from SIGUSR2 upgrades - -This is no longer be an issue as of bundler 0.9.17 - -ref: http://mid.gmane.org/8FC34B23-5994-41CC-B5AF-7198EF06909E@tramchase.com - -=== BUNDLE_GEMFILE for Capistrano users - -You may need to set or reset the BUNDLE_GEMFILE environment variable in -the before_exec hook: - - before_exec do |server| - ENV["BUNDLE_GEMFILE"] = "/path/to/app/current/Gemfile" - end - -=== Other ENV pollution issues - -If you're using an older Bundler version (0.9.x), you may need to set or -reset GEM_HOME, GEM_PATH and PATH environment variables in the -before_exec hook as illustrated by http://gist.github.com/534668 - -=== Ruby 2.0.0 close-on-exec and SIGUSR2 incompatibility - -Ruby 2.0.0 enforces FD_CLOEXEC on file descriptors by default. unicorn -has been prepared for this behavior since unicorn 4.1.0, but we forgot -to remind the Bundler developers. This issue is being tracked here: -https://github.com/bundler/bundler/issues/2628 - -== Isolate - -=== Running - -Installing "unicorn" as a system-wide Rubygem and using the -isolate gem may cause issues if you're using any of the bundled -application-level libraries in unicorn/app/* (for compatibility -with CGI-based applications, Rails <= 2.2.2, or ExecCgi). -For now workarounds include doing one of the following: - -1. Isolating unicorn, setting GEM_HOME to your Isolate path, - and running the isolated version of unicorn. You *must* set - GEM_HOME before running your isolated unicorn install in this way. - -2. Installing the same version of unicorn as a system-wide Rubygem - *and* isolating unicorn as well. - -3. Explicitly setting RUBYLIB or $LOAD_PATH to include any gem path - where the unicorn gem is installed - (e.g. /usr/lib/ruby/gems/1.9.1/gems/unicorn-VERSION/lib) - -=== RUBYOPT pollution from SIGUSR2 upgrades - -If you are using Isolate, using Isolate 2.x is strongly recommended as -environment modifications are idempotent. - -If you are stuck with 1.x versions of Isolate, it is recommended that -you disable it with the before_exec hook prevent the PATH and -RUBYOPT environment variable modifications from propagating between -upgrades in your Unicorn config file: - - before_exec do |server| - Isolate.disable - end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/TODO b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/TODO deleted file mode 100644 index 07bf0a1..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/TODO +++ /dev/null @@ -1,5 +0,0 @@ -* Documentation improvements - -* improve test suite - -* Rack 2.x support (when Rack 2.x exists) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/TUNING b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/TUNING deleted file mode 100644 index 542ebdc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/TUNING +++ /dev/null @@ -1,98 +0,0 @@ -= Tuning \Unicorn - -\Unicorn performance is generally as good as a (mostly) Ruby web server -can provide. Most often the performance bottleneck is in the web -application running on Unicorn rather than Unicorn itself. - -== \Unicorn Configuration - -See Unicorn::Configurator for details on the config file format. -+worker_processes+ is the most-commonly needed tuning parameter. - -=== Unicorn::Configurator#worker_processes - -* worker_processes should be scaled to the number of processes your - backend system(s) can support. DO NOT scale it to the number of - external network clients your application expects to be serving. - \Unicorn is NOT for serving slow clients, that is the job of nginx. - -* worker_processes should be *at* *least* the number of CPU cores on - a dedicated server. If your application has occasionally slow - responses that are /not/ CPU-intensive, you may increase this to - workaround those inefficiencies. - -* worker_processes may be increased for Unicorn::OobGC users to provide - more consistent response times. - -* Never, ever, increase worker_processes to the point where the system - runs out of physical memory and hits swap. Production servers should - never see heavy swap activity. - -=== Unicorn::Configurator#listen Options - -* Setting a very low value for the :backlog parameter in "listen" - directives can allow failover to happen more quickly if your - cluster is configured for it. - -* If you're doing extremely simple benchmarks and getting connection - errors under high request rates, increasing your :backlog parameter - above the already-generous default of 1024 can help avoid connection - errors. Keep in mind this is not recommended for real traffic if - you have another machine to failover to (see above). - -* :rcvbuf and :sndbuf parameters generally do not need to be set for TCP - listeners under Linux 2.6 because auto-tuning is enabled. UNIX domain - sockets do not have auto-tuning buffer sizes; so increasing those will - allow syscalls and task switches to be saved for larger requests - and responses. If your app only generates small responses or expects - small requests, you may shrink the buffer sizes to save memory, too. - -* Having socket buffers too large can also be detrimental or have - little effect. Huge buffers can put more pressure on the allocator - and may also thrash CPU caches, cancelling out performance gains - one would normally expect. - -* UNIX domain sockets are slightly faster than TCP sockets, but only - work if nginx is on the same machine. - -== Other \Unicorn settings - -* Setting "preload_app true" can allow copy-on-write-friendly GC to - be used to save memory. It will probably not work out of the box with - applications that open sockets or perform random I/O on files. - Databases like TokyoCabinet use concurrency-safe pread()/pwrite() - functions for safe sharing of database file descriptors across - processes. - -* On POSIX-compliant filesystems, it is safe for multiple threads or - processes to append to one log file as long as all the processes are - have them unbuffered (File#sync = true) or they are - record(line)-buffered in userspace before any writes. - -== Kernel Parameters (Linux sysctl) - -WARNING: Do not change system parameters unless you know what you're doing! - -* net.core.rmem_max and net.core.wmem_max can increase the allowed - size of :rcvbuf and :sndbuf respectively. This is mostly only useful - for UNIX domain sockets which do not have auto-tuning buffer sizes. - -* For load testing/benchmarking with UNIX domain sockets, you should - consider increasing net.core.somaxconn or else nginx will start - failing to connect under heavy load. You may also consider setting - a higher :backlog to listen on as noted earlier. - -* If you're running out of local ports, consider lowering - net.ipv4.tcp_fin_timeout to 20-30 (default: 60 seconds). Also - consider widening the usable port range by changing - net.ipv4.ip_local_port_range. - -* Setting net.ipv4.tcp_timestamps=1 will also allow setting - net.ipv4.tcp_tw_reuse=1 and net.ipv4.tcp_tw_recycle=1, which along - with the above settings can slow down port exhaustion. Not all - networks are compatible with these settings, check with your friendly - network administrator before changing these. - -* Increasing the MTU size can reduce framing overhead for larger - transfers. One often-overlooked detail is that the loopback - device (usually "lo") can have its MTU increased, too. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/archive/.gitignore b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/archive/.gitignore deleted file mode 100644 index bd7ad57..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/archive/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/data -/news -/requests diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/archive/slrnpull.conf b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/archive/slrnpull.conf deleted file mode 100644 index fcfcafe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/archive/slrnpull.conf +++ /dev/null @@ -1,4 +0,0 @@ -# group_name max expire headers_only -gmane.comp.lang.ruby.unicorn.general 1000000000 1000000000 0 - -# usage: slrnpull -d $PWD -h news.gmane.org --no-post diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/bin/unicorn b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/bin/unicorn deleted file mode 100755 index c272e43..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/bin/unicorn +++ /dev/null @@ -1,126 +0,0 @@ -#!/this/will/be/overwritten/or/wrapped/anyways/do/not/worry/ruby -# -*- encoding: binary -*- -require 'unicorn/launcher' -require 'optparse' - -ENV["RACK_ENV"] ||= "development" -rackup_opts = Unicorn::Configurator::RACKUP -options = rackup_opts[:options] - -op = OptionParser.new("", 24, ' ') do |opts| - cmd = File.basename($0) - opts.banner = "Usage: #{cmd} " \ - "[ruby options] [#{cmd} options] [rackup config file]" - opts.separator "Ruby options:" - - lineno = 1 - opts.on("-e", "--eval LINE", "evaluate a LINE of code") do |line| - eval line, TOPLEVEL_BINDING, "-e", lineno - lineno += 1 - end - - opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") do - $DEBUG = true - end - - opts.on("-w", "--warn", "turn warnings on for your script") do - $-w = true - end - - opts.on("-I", "--include PATH", - "specify $LOAD_PATH (may be used more than once)") do |path| - $LOAD_PATH.unshift(*path.split(/:/)) - end - - opts.on("-r", "--require LIBRARY", - "require the library, before executing your script") do |library| - require library - end - - opts.separator "#{cmd} options:" - - # some of these switches exist for rackup command-line compatibility, - - opts.on("-o", "--host HOST", - "listen on HOST (default: #{Unicorn::Const::DEFAULT_HOST})") do |h| - rackup_opts[:host] = h - rackup_opts[:set_listener] = true - end - - opts.on("-p", "--port PORT", Integer, - "use PORT (default: #{Unicorn::Const::DEFAULT_PORT})") do |port| - rackup_opts[:port] = port - rackup_opts[:set_listener] = true - end - - opts.on("-E", "--env RACK_ENV", - "use RACK_ENV for defaults (default: development)") do |e| - ENV["RACK_ENV"] = e - end - - opts.on("-N", "--no-default-middleware", - "do not load middleware implied by RACK_ENV") do |e| - rackup_opts[:no_default_middleware] = true - end - - opts.on("-D", "--daemonize", "run daemonized in the background") do |d| - rackup_opts[:daemonize] = !!d - end - - opts.on("-P", "--pid FILE", "DEPRECATED") do |f| - warn %q{Use of --pid/-P is strongly discouraged} - warn %q{Use the 'pid' directive in the Unicorn config file instead} - options[:pid] = f - end - - opts.on("-s", "--server SERVER", - "this flag only exists for compatibility") do |s| - warn "-s/--server only exists for compatibility with rackup" - end - - # Unicorn-specific stuff - opts.on("-l", "--listen {HOST:PORT|PATH}", - "listen on HOST:PORT or PATH", - "this may be specified multiple times", - "(default: #{Unicorn::Const::DEFAULT_LISTEN})") do |address| - options[:listeners] << address - end - - opts.on("-c", "--config-file FILE", "Unicorn-specific config file") do |f| - options[:config_file] = f - end - - # I'm avoiding Unicorn-specific config options on the command-line. - # IMNSHO, config options on the command-line are redundant given - # config files and make things unnecessarily complicated with multiple - # places to look for a config option. - - opts.separator "Common options:" - - opts.on_tail("-h", "--help", "Show this message") do - puts opts.to_s.gsub(/^.*DEPRECATED.*$/s, '') - exit - end - - opts.on_tail("-v", "--version", "Show version") do - puts "#{cmd} v#{Unicorn::Const::UNICORN_VERSION}" - exit - end - - opts.parse! ARGV -end - -app = Unicorn.builder(ARGV[0] || 'config.ru', op) -op = nil - -if $DEBUG - require 'pp' - pp({ - :unicorn_options => options, - :app => app, - :daemonize => rackup_opts[:daemonize], - }) -end - -Unicorn::Launcher.daemonize!(options) if rackup_opts[:daemonize] -Unicorn::HttpServer.new(app, options).start.join diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/bin/unicorn_rails b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/bin/unicorn_rails deleted file mode 100755 index b080846..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/bin/unicorn_rails +++ /dev/null @@ -1,209 +0,0 @@ -#!/this/will/be/overwritten/or/wrapped/anyways/do/not/worry/ruby -# -*- encoding: binary -*- -require 'unicorn/launcher' -require 'optparse' -require 'fileutils' - -ENV['RAILS_ENV'] ||= "development" -rackup_opts = Unicorn::Configurator::RACKUP -options = rackup_opts[:options] - -op = OptionParser.new("", 24, ' ') do |opts| - cmd = File.basename($0) - opts.banner = "Usage: #{cmd} " \ - "[ruby options] [#{cmd} options] [rackup config file]" - opts.separator "Ruby options:" - - lineno = 1 - opts.on("-e", "--eval LINE", "evaluate a LINE of code") do |line| - eval line, TOPLEVEL_BINDING, "-e", lineno - lineno += 1 - end - - opts.on("-d", "--debug", "set debugging flags (set $DEBUG to true)") do - $DEBUG = true - end - - opts.on("-w", "--warn", "turn warnings on for your script") do - $-w = true - end - - opts.on("-I", "--include PATH", - "specify $LOAD_PATH (may be used more than once)") do |path| - $LOAD_PATH.unshift(*path.split(/:/)) - end - - opts.on("-r", "--require LIBRARY", - "require the library, before executing your script") do |library| - require library - end - - opts.separator "#{cmd} options:" - - # some of these switches exist for rackup command-line compatibility, - - opts.on("-o", "--host HOST", - "listen on HOST (default: #{Unicorn::Const::DEFAULT_HOST})") do |h| - rackup_opts[:host] = h - rackup_opts[:set_listener] = true - end - - opts.on("-p", "--port PORT", Integer, - "use PORT (default: #{Unicorn::Const::DEFAULT_PORT})") do |port| - rackup_opts[:port] = port - rackup_opts[:set_listener] = true - end - - opts.on("-E", "--env RAILS_ENV", - "use RAILS_ENV for defaults (default: development)") do |e| - ENV['RAILS_ENV'] = e - end - - opts.on("-D", "--daemonize", "run daemonized in the background") do |d| - rackup_opts[:daemonize] = !!d - end - - # Unicorn-specific stuff - opts.on("-l", "--listen {HOST:PORT|PATH}", - "listen on HOST:PORT or PATH", - "this may be specified multiple times", - "(default: #{Unicorn::Const::DEFAULT_LISTEN})") do |address| - options[:listeners] << address - end - - opts.on("-c", "--config-file FILE", "Unicorn-specific config file") do |f| - options[:config_file] = f - end - - opts.on("-P PATH", "DEPRECATED") do |v| - warn %q{Use of -P is ambiguous and discouraged} - warn %q{Use --path or RAILS_RELATIVE_URL_ROOT instead} - ENV['RAILS_RELATIVE_URL_ROOT'] = v - end - - opts.on("--path PATH", "Runs Rails app mounted at a specific path.", - "(default: /)") do |v| - ENV['RAILS_RELATIVE_URL_ROOT'] = v - end - - # I'm avoiding Unicorn-specific config options on the command-line. - # IMNSHO, config options on the command-line are redundant given - # config files and make things unnecessarily complicated with multiple - # places to look for a config option. - - opts.separator "Common options:" - - opts.on_tail("-h", "--help", "Show this message") do - puts opts.to_s.gsub(/^.*DEPRECATED.*$/s, '') - exit - end - - opts.on_tail("-v", "--version", "Show version") do - puts "#{cmd} v#{Unicorn::Const::UNICORN_VERSION}" - exit - end - - opts.parse! ARGV -end - -def rails_dispatcher - if ::Rails::VERSION::MAJOR >= 3 && ::File.exist?('config/application.rb') - if ::File.read('config/application.rb') =~ /^module\s+([\w:]+)\s*$/ - app_module = Object.const_get($1) - begin - result = app_module::Application - rescue NameError - end - end - end - - if result.nil? && defined?(ActionController::Dispatcher) - result = ActionController::Dispatcher.new - end - - result || abort("Unable to locate the application dispatcher class") -end - -def rails_builder(ru, op, daemonize) - return Unicorn.builder(ru, op) if ru - - # allow Configurator to parse cli switches embedded in the ru file - Unicorn::Configurator::RACKUP.update(:file => :rails, :optparse => op) - - # this lambda won't run until after forking if preload_app is false - # this runs after config file reloading - lambda do || - # Rails 3 includes a config.ru, use it if we find it after - # working_directory is bound. - ::File.exist?('config.ru') and - return Unicorn.builder('config.ru', op).call - - # Load Rails and (possibly) the private version of Rack it bundles. - begin - require ::File.expand_path('config/boot') - require ::File.expand_path('config/environment') - rescue LoadError => err - abort "#$0 must be run inside RAILS_ROOT: #{err.inspect}" - end - - defined?(::Rails::VERSION::STRING) or - abort "Rails::VERSION::STRING not defined by config/{boot,environment}" - # it seems Rails >=2.2 support Rack, but only >=2.3 requires it - old_rails = case ::Rails::VERSION::MAJOR - when 0, 1 then true - when 2 then Rails::VERSION::MINOR < 3 ? true : false - else - false - end - - Rack::Builder.new do - map_path = ENV['RAILS_RELATIVE_URL_ROOT'] || '/' - if old_rails - if map_path != '/' - # patches + tests welcome, but I really cbf to deal with this - # since all apps I've ever dealt with just use "/" ... - warn "relative URL roots may not work for older Rails" - end - warn "LogTailer not available for Rails < 2.3" unless daemonize - warn "Debugger not available" if $DEBUG - require 'unicorn/app/old_rails' - map(map_path) do - use Unicorn::App::OldRails::Static - run Unicorn::App::OldRails.new - end - else - use Rails::Rack::LogTailer unless daemonize - use Rails::Rack::Debugger if $DEBUG - map(map_path) do - unless defined?(ActionDispatch::Static) - use Rails::Rack::Static - end - run rails_dispatcher - end - end - end.to_app - end -end - -app = rails_builder(ARGV[0], op, rackup_opts[:daemonize]) -op = nil - -if $DEBUG - require 'pp' - pp({ - :unicorn_options => options, - :app => app, - :daemonize => rackup_opts[:daemonize], - }) -end - -# ensure Rails standard tmp paths exist -options[:after_reload] = lambda do - FileUtils.mkdir_p(%w(cache pids sessions sockets).map! { |d| "tmp/#{d}" }) -end - -if rackup_opts[:daemonize] - options[:pid] = "tmp/pids/unicorn.pid" - Unicorn::Launcher.daemonize!(options) -end -Unicorn::HttpServer.new(app, options).start.join diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/big_app_gc.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/big_app_gc.rb deleted file mode 100644 index c4c8b04..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/big_app_gc.rb +++ /dev/null @@ -1,2 +0,0 @@ -# see {Unicorn::OobGC}[http://unicorn.bogomips.org/Unicorn/OobGC.html] -# Unicorn::OobGC was broken in Unicorn v3.3.1 - v3.6.1 and fixed in v3.6.2 diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/echo.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/echo.ru deleted file mode 100644 index 14908c5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/echo.ru +++ /dev/null @@ -1,27 +0,0 @@ -#\-E none -# -# Example application that echoes read data back to the HTTP client. -# This emulates the old echo protocol people used to run. -# -# An example of using this in a client would be to run: -# curl --no-buffer -T- http://host:port/ -# -# Then type random stuff in your terminal to watch it get echoed back! - -class EchoBody < Struct.new(:input) - - def each(&block) - while buf = input.read(4096) - yield buf - end - self - end - -end - -use Rack::Chunked -run lambda { |env| - /\A100-continue\z/i =~ env['HTTP_EXPECT'] and return [100, {}, []] - [ 200, { 'Content-Type' => 'application/octet-stream' }, - EchoBody.new(env['rack.input']) ] -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/git.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/git.ru deleted file mode 100644 index 59a31c9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/git.ru +++ /dev/null @@ -1,13 +0,0 @@ -#\-E none - -# See http://thread.gmane.org/gmane.comp.web.curl.general/10473/raw on -# how to setup git for this. A better version of the above patch was -# accepted and committed on June 15, 2009, so you can pull the latest -# curl CVS snapshot to try this out. -require 'unicorn/app/inetd' - -use Rack::Lint -use Rack::Chunked # important! -run Unicorn::App::Inetd.new( - *%w(git daemon --verbose --inetd --export-all --base-path=/home/ew/unicorn) -) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/init.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/init.sh deleted file mode 100644 index 1f0e035..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/init.sh +++ /dev/null @@ -1,74 +0,0 @@ -#!/bin/sh -set -e -# Example init script, this can be used with nginx, too, -# since nginx and unicorn accept the same signals - -# Feel free to change any of the following variables for your app: -TIMEOUT=${TIMEOUT-60} -APP_ROOT=/home/x/my_app/current -PID=$APP_ROOT/tmp/pids/unicorn.pid -CMD="/usr/bin/unicorn -D -c $APP_ROOT/config/unicorn.rb" -INIT_CONF=$APP_ROOT/config/init.conf -action="$1" -set -u - -test -f "$INIT_CONF" && . $INIT_CONF - -old_pid="$PID.oldbin" - -cd $APP_ROOT || exit 1 - -sig () { - test -s "$PID" && kill -$1 `cat $PID` -} - -oldsig () { - test -s $old_pid && kill -$1 `cat $old_pid` -} - -case $action in -start) - sig 0 && echo >&2 "Already running" && exit 0 - $CMD - ;; -stop) - sig QUIT && exit 0 - echo >&2 "Not running" - ;; -force-stop) - sig TERM && exit 0 - echo >&2 "Not running" - ;; -restart|reload) - sig HUP && echo reloaded OK && exit 0 - echo >&2 "Couldn't reload, starting '$CMD' instead" - $CMD - ;; -upgrade) - if sig USR2 && sleep 2 && sig 0 && oldsig QUIT - then - n=$TIMEOUT - while test -s $old_pid && test $n -ge 0 - do - printf '.' && sleep 1 && n=$(( $n - 1 )) - done - echo - - if test $n -lt 0 && test -s $old_pid - then - echo >&2 "$old_pid still exists after $TIMEOUT seconds" - exit 1 - fi - exit 0 - fi - echo >&2 "Couldn't upgrade, starting '$CMD' instead" - $CMD - ;; -reopen-logs) - sig USR1 - ;; -*) - echo >&2 "Usage: $0 " - exit 1 - ;; -esac diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/logger_mp_safe.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/logger_mp_safe.rb deleted file mode 100644 index 05ad3fa..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/logger_mp_safe.rb +++ /dev/null @@ -1,25 +0,0 @@ -# Multi-Processing-safe monkey patch for Logger -# -# This monkey patch fixes the case where "preload_app true" is used and -# the application spawns a background thread upon being loaded. -# -# This removes all lock from the Logger code and solely relies on the -# underlying filesystem to handle write(2) system calls atomically when -# O_APPEND is used. This is safe in the presence of both multiple -# threads (native or green) and multiple processes when writing to -# a filesystem with POSIX O_APPEND semantics. -# -# It should be noted that the original locking on Logger could _never_ be -# considered reliable on non-POSIX filesystems with multiple processes, -# either, so nothing is lost in that case. - -require 'logger' -class Logger::LogDevice - def write(message) - @dev.syswrite(message) - end - - def close - @dev.close - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/logrotate.conf b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/logrotate.conf deleted file mode 100644 index 03fefc6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/logrotate.conf +++ /dev/null @@ -1,29 +0,0 @@ -# example logrotate config file, I usually keep this in -# /etc/logrotate.d/unicorn_app on my Debian systems -# -# See the logrotate(8) manpage for more information: -# http://linux.die.net/man/8/logrotate - -# Modify the following glob to match the logfiles your app writes to: -/var/log/unicorn_app/*.log { - # this first block is mostly just personal preference, though - # I wish logrotate offered an "hourly" option... - daily - missingok - rotate 180 - compress # must use with delaycompress below - dateext - - # this is important if using "compress" since we need to call - # the "lastaction" script below before compressing: - delaycompress - - # note the lack of the evil "copytruncate" option in this - # config. Unicorn supports the USR1 signal and we send it - # as our "lastaction" action: - lastaction - # assuming your pid file is in /var/run/unicorn_app/pid - pid=/var/run/unicorn_app/pid - test -s $pid && kill -USR1 "$(cat $pid)" - endscript -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/nginx.conf b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/nginx.conf deleted file mode 100644 index a68fe6f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/nginx.conf +++ /dev/null @@ -1,156 +0,0 @@ -# This is example contains the bare mininum to get nginx going with -# Unicorn or Rainbows! servers. Generally these configuration settings -# are applicable to other HTTP application servers (and not just Ruby -# ones), so if you have one working well for proxying another app -# server, feel free to continue using it. -# -# The only setting we feel strongly about is the fail_timeout=0 -# directive in the "upstream" block. max_fails=0 also has the same -# effect as fail_timeout=0 for current versions of nginx and may be -# used in its place. -# -# Users are strongly encouraged to refer to nginx documentation for more -# details and search for other example configs. - -# you generally only need one nginx worker unless you're serving -# large amounts of static files which require blocking disk reads -worker_processes 1; - -# # drop privileges, root is needed on most systems for binding to port 80 -# # (or anything < 1024). Capability-based security may be available for -# # your system and worth checking out so you won't need to be root to -# # start nginx to bind on 80 -user nobody nogroup; # for systems with a "nogroup" -# user nobody nobody; # for systems with "nobody" as a group instead - -# Feel free to change all paths to suite your needs here, of course -pid /path/to/nginx.pid; -error_log /path/to/nginx.error.log; - -events { - worker_connections 1024; # increase if you have lots of clients - accept_mutex off; # "on" if nginx worker_processes > 1 - # use epoll; # enable for Linux 2.6+ - # use kqueue; # enable for FreeBSD, OSX -} - -http { - # nginx will find this file in the config directory set at nginx build time - include mime.types; - - # fallback in case we can't determine a type - default_type application/octet-stream; - - # click tracking! - access_log /path/to/nginx.access.log combined; - - # you generally want to serve static files with nginx since neither - # Unicorn nor Rainbows! is optimized for it at the moment - sendfile on; - - tcp_nopush on; # off may be better for *some* Comet/long-poll stuff - tcp_nodelay off; # on may be better for some Comet/long-poll stuff - - # we haven't checked to see if Rack::Deflate on the app server is - # faster or not than doing compression via nginx. It's easier - # to configure it all in one place here for static files and also - # to disable gzip for clients who don't get gzip/deflate right. - # There are other gzip settings that may be needed used to deal with - # bad clients out there, see http://wiki.nginx.org/NginxHttpGzipModule - gzip on; - gzip_http_version 1.0; - gzip_proxied any; - gzip_min_length 500; - gzip_disable "MSIE [1-6]\."; - gzip_types text/plain text/html text/xml text/css - text/comma-separated-values - text/javascript application/x-javascript - application/atom+xml; - - # this can be any application server, not just Unicorn/Rainbows! - upstream app_server { - # fail_timeout=0 means we always retry an upstream even if it failed - # to return a good HTTP response (in case the Unicorn master nukes a - # single worker for timing out). - - # for UNIX domain socket setups: - server unix:/path/to/.unicorn.sock fail_timeout=0; - - # for TCP setups, point these to your backend servers - # server 192.168.0.7:8080 fail_timeout=0; - # server 192.168.0.8:8080 fail_timeout=0; - # server 192.168.0.9:8080 fail_timeout=0; - } - - server { - # enable one of the following if you're on Linux or FreeBSD - # listen 80 default deferred; # for Linux - # listen 80 default accept_filter=httpready; # for FreeBSD - - # If you have IPv6, you'll likely want to have two separate listeners. - # One on IPv4 only (the default), and another on IPv6 only instead - # of a single dual-stack listener. A dual-stack listener will make - # for ugly IPv4 addresses in $remote_addr (e.g ":ffff:10.0.0.1" - # instead of just "10.0.0.1") and potentially trigger bugs in - # some software. - # listen [::]:80 ipv6only=on; # deferred or accept_filter recommended - - client_max_body_size 4G; - server_name _; - - # ~2 seconds is often enough for most folks to parse HTML/CSS and - # retrieve needed images/icons/frames, connections are cheap in - # nginx so increasing this is generally safe... - keepalive_timeout 5; - - # path for static files - root /path/to/app/current/public; - - # Prefer to serve static files directly from nginx to avoid unnecessary - # data copies from the application server. - # - # try_files directive appeared in in nginx 0.7.27 and has stabilized - # over time. Older versions of nginx (e.g. 0.6.x) requires - # "if (!-f $request_filename)" which was less efficient: - # http://bogomips.org/unicorn.git/tree/examples/nginx.conf?id=v3.3.1#n127 - try_files $uri/index.html $uri.html $uri @app; - - location @app { - # an HTTP header important enough to have its own Wikipedia entry: - # http://en.wikipedia.org/wiki/X-Forwarded-For - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - - # enable this if you forward HTTPS traffic to unicorn, - # this helps Rack set the proper URL scheme for doing redirects: - # proxy_set_header X-Forwarded-Proto $scheme; - - # pass the Host: header from the client right along so redirects - # can be set properly within the Rack application - proxy_set_header Host $http_host; - - # we don't want nginx trying to do something clever with - # redirects, we set the Host: header above already. - proxy_redirect off; - - # set "proxy_buffering off" *only* for Rainbows! when doing - # Comet/long-poll/streaming. It's also safe to set if you're using - # only serving fast clients with Unicorn + nginx, but not slow - # clients. You normally want nginx to buffer responses to slow - # clients, even with Rails 3.1 streaming because otherwise a slow - # client can become a bottleneck of Unicorn. - # - # The Rack application may also set "X-Accel-Buffering (yes|no)" - # in the response headers do disable/enable buffering on a - # per-response basis. - # proxy_buffering off; - - proxy_pass http://app_server; - } - - # Rails error pages - error_page 500 502 503 504 /500.html; - location = /500.html { - root /path/to/app/current/public; - } - } -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/unicorn.conf.minimal.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/unicorn.conf.minimal.rb deleted file mode 100644 index 2a47910..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/unicorn.conf.minimal.rb +++ /dev/null @@ -1,13 +0,0 @@ -# Minimal sample configuration file for Unicorn (not Rack) when used -# with daemonization (unicorn -D) started in your working directory. -# -# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete -# documentation. -# See also http://unicorn.bogomips.org/examples/unicorn.conf.rb for -# a more verbose configuration using more features. - -listen 2007 # by default Unicorn listens on port 8080 -worker_processes 2 # this should be >= nr_cpus -pid "/path/to/app/shared/pids/unicorn.pid" -stderr_path "/path/to/app/shared/log/unicorn.log" -stdout_path "/path/to/app/shared/log/unicorn.log" diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/unicorn.conf.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/unicorn.conf.rb deleted file mode 100644 index 9dce58a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/examples/unicorn.conf.rb +++ /dev/null @@ -1,102 +0,0 @@ -# Sample verbose configuration file for Unicorn (not Rack) -# -# This configuration file documents many features of Unicorn -# that may not be needed for some applications. See -# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb -# for a much simpler configuration file. -# -# See http://unicorn.bogomips.org/Unicorn/Configurator.html for complete -# documentation. - -# Use at least one worker per core if you're on a dedicated server, -# more will usually help for _short_ waits on databases/caches. -worker_processes 4 - -# Since Unicorn is never exposed to outside clients, it does not need to -# run on the standard HTTP port (80), there is no reason to start Unicorn -# as root unless it's from system init scripts. -# If running the master process as root and the workers as an unprivileged -# user, do this to switch euid/egid in the workers (also chowns logs): -# user "unprivileged_user", "unprivileged_group" - -# Help ensure your application will always spawn in the symlinked -# "current" directory that Capistrano sets up. -working_directory "/path/to/app/current" # available in 0.94.0+ - -# listen on both a Unix domain socket and a TCP port, -# we use a shorter backlog for quicker failover when busy -listen "/path/to/.unicorn.sock", :backlog => 64 -listen 8080, :tcp_nopush => true - -# nuke workers after 30 seconds instead of 60 seconds (the default) -timeout 30 - -# feel free to point this anywhere accessible on the filesystem -pid "/path/to/app/shared/pids/unicorn.pid" - -# By default, the Unicorn logger will write to stderr. -# Additionally, ome applications/frameworks log to stderr or stdout, -# so prevent them from going to /dev/null when daemonized here: -stderr_path "/path/to/app/shared/log/unicorn.stderr.log" -stdout_path "/path/to/app/shared/log/unicorn.stdout.log" - -# combine Ruby 2.0.0dev or REE with "preload_app true" for memory savings -# http://rubyenterpriseedition.com/faq.html#adapt_apps_for_cow -preload_app true -GC.respond_to?(:copy_on_write_friendly=) and - GC.copy_on_write_friendly = true - -# Enable this flag to have unicorn test client connections by writing the -# beginning of the HTTP headers before calling the application. This -# prevents calling the application for connections that have disconnected -# while queued. This is only guaranteed to detect clients on the same -# host unicorn runs on, and unlikely to detect disconnects even on a -# fast LAN. -check_client_connection false - -before_fork do |server, worker| - # the following is highly recomended for Rails + "preload_app true" - # as there's no need for the master process to hold a connection - defined?(ActiveRecord::Base) and - ActiveRecord::Base.connection.disconnect! - - # The following is only recommended for memory/DB-constrained - # installations. It is not needed if your system can house - # twice as many worker_processes as you have configured. - # - # # This allows a new master process to incrementally - # # phase out the old master process with SIGTTOU to avoid a - # # thundering herd (especially in the "preload_app false" case) - # # when doing a transparent upgrade. The last worker spawned - # # will then kill off the old master process with a SIGQUIT. - # old_pid = "#{server.config[:pid]}.oldbin" - # if old_pid != server.pid - # begin - # sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU - # Process.kill(sig, File.read(old_pid).to_i) - # rescue Errno::ENOENT, Errno::ESRCH - # end - # end - # - # Throttle the master from forking too quickly by sleeping. Due - # to the implementation of standard Unix signal handlers, this - # helps (but does not completely) prevent identical, repeated signals - # from being lost when the receiving process is busy. - # sleep 1 -end - -after_fork do |server, worker| - # per-process listener ports for debugging/admin/migrations - # addr = "127.0.0.1:#{9293 + worker.nr}" - # server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true) - - # the following is *required* for Rails + "preload_app true", - defined?(ActiveRecord::Base) and - ActiveRecord::Base.establish_connection - - # if preload_app is true, then you may also want to check and - # restart any other shared sockets/descriptors such as Memcached, - # and Redis. TokyoCabinet file handles are safe to reuse - # between any number of forked children (assuming your kernel - # correctly implements pread()/pwrite() system calls) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/.RUBYARCHDIR.time b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/.RUBYARCHDIR.time deleted file mode 100644 index e69de29..0000000 diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/CFLAGS b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/CFLAGS deleted file mode 100644 index 2b83d0e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/CFLAGS +++ /dev/null @@ -1,13 +0,0 @@ -# CFLAGS used for development (gcc-dependent) -# source this file if you want/need them -CFLAGS= -CFLAGS="$CFLAGS -Wall" -CFLAGS="$CFLAGS -Wwrite-strings" -CFLAGS="$CFLAGS -Wdeclaration-after-statement" -CFLAGS="$CFLAGS -Wcast-qual" -CFLAGS="$CFLAGS -Wstrict-prototypes" -CFLAGS="$CFLAGS -Wshadow" -CFLAGS="$CFLAGS -Wextra" -CFLAGS="$CFLAGS -Wno-deprecated-declarations" -CFLAGS="$CFLAGS -Waggregate-return" -CFLAGS="$CFLAGS -Wchar-subscripts" diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/c_util.h b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/c_util.h deleted file mode 100644 index ab1fc0e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/c_util.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Generic C functions and macros go here, there are no dependencies - * on Unicorn internal structures or the Ruby C API in here. - */ - -#ifndef UH_util_h -#define UH_util_h - -#include -#include - -#define MIN(a,b) (a < b ? a : b) -#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) - -#ifndef SIZEOF_OFF_T -# define SIZEOF_OFF_T 4 -# warning SIZEOF_OFF_T not defined, guessing 4. Did you run extconf.rb? -#endif - -#if SIZEOF_OFF_T == 4 -# define UH_OFF_T_MAX 0x7fffffff -#elif SIZEOF_OFF_T == 8 -# if SIZEOF_LONG == 4 -# define UH_OFF_T_MAX 0x7fffffffffffffffLL -# else -# define UH_OFF_T_MAX 0x7fffffffffffffff -# endif -#else -# error off_t size unknown for this platform! -#endif /* SIZEOF_OFF_T check */ - -/* - * ragel enforces fpc as a const, and merely casting can make picky - * compilers unhappy, so we have this little helper do our dirty work - */ -static inline void *deconst(const void *in) -{ - union { const void *in; void *out; } tmp; - - tmp.in = in; - - return tmp.out; -} - -/* - * capitalizes all lower-case ASCII characters and converts dashes - * to underscores for HTTP headers. Locale-agnostic. - */ -static void snake_upcase_char(char *c) -{ - if (*c >= 'a' && *c <= 'z') - *c &= ~0x20; - else if (*c == '-') - *c = '_'; -} - -/* Downcases a single ASCII character. Locale-agnostic. */ -static void downcase_char(char *c) -{ - if (*c >= 'A' && *c <= 'Z') - *c |= 0x20; -} - -static int hexchar2int(int xdigit) -{ - if (xdigit >= 'A' && xdigit <= 'F') - return xdigit - 'A' + 10; - if (xdigit >= 'a' && xdigit <= 'f') - return xdigit - 'a' + 10; - - /* Ragel already does runtime range checking for us in Unicorn: */ - assert(xdigit >= '0' && xdigit <= '9' && "invalid digit character"); - - return xdigit - '0'; -} - -/* - * multiplies +i+ by +base+ and increments the result by the parsed - * integer value of +xdigit+. +xdigit+ is a character byte - * representing a number the range of 0..(base-1) - * returns the new value of +i+ on success - * returns -1 on errors (including overflow) - */ -static off_t step_incr(off_t i, int xdigit, const int base) -{ - static const off_t max = UH_OFF_T_MAX; - const off_t next_max = (max - (max % base)) / base; - off_t offset = hexchar2int(xdigit); - - if (offset > (base - 1)) - return -1; - if (i > next_max) - return -1; - i *= base; - - if ((offset > (base - 1)) || ((max - i) < offset)) - return -1; - - return i + offset; -} - -/* - * parses a non-negative length according to base-10 and - * returns it as an off_t value. Returns -1 on errors - * (including overflow). - */ -static off_t parse_length(const char *value, size_t length) -{ - off_t rv; - - for (rv = 0; length-- && rv >= 0; ++value) { - if (*value >= '0' && *value <= '9') - rv = step_incr(rv, *value, 10); - else - return -1; - } - - return rv; -} - -#define CONST_MEM_EQ(const_p, buf, len) \ - ((sizeof(const_p) - 1) == len && !memcmp(const_p, buf, sizeof(const_p) - 1)) - -#endif /* UH_util_h */ diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/common_field_optimization.h b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/common_field_optimization.h deleted file mode 100644 index 42c5430..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/common_field_optimization.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef common_field_optimization -#define common_field_optimization -#include "ruby.h" -#include "c_util.h" - -struct common_field { - const signed long len; - const char *name; - VALUE value; -}; - -/* - * A list of common HTTP headers we expect to receive. - * This allows us to avoid repeatedly creating identical string - * objects to be used with rb_hash_aset(). - */ -static struct common_field common_http_fields[] = { -# define f(N) { (sizeof(N) - 1), N, Qnil } - f("ACCEPT"), - f("ACCEPT_CHARSET"), - f("ACCEPT_ENCODING"), - f("ACCEPT_LANGUAGE"), - f("ALLOW"), - f("AUTHORIZATION"), - f("CACHE_CONTROL"), - f("CONNECTION"), - f("CONTENT_ENCODING"), - f("CONTENT_LENGTH"), - f("CONTENT_TYPE"), - f("COOKIE"), - f("DATE"), - f("EXPECT"), - f("FROM"), - f("HOST"), - f("IF_MATCH"), - f("IF_MODIFIED_SINCE"), - f("IF_NONE_MATCH"), - f("IF_RANGE"), - f("IF_UNMODIFIED_SINCE"), - f("KEEP_ALIVE"), /* Firefox sends this */ - f("MAX_FORWARDS"), - f("PRAGMA"), - f("PROXY_AUTHORIZATION"), - f("RANGE"), - f("REFERER"), - f("TE"), - f("TRAILER"), - f("TRANSFER_ENCODING"), - f("UPGRADE"), - f("USER_AGENT"), - f("VIA"), - f("X_FORWARDED_FOR"), /* common for proxies */ - f("X_FORWARDED_PROTO"), /* common for proxies */ - f("X_REAL_IP"), /* common for proxies */ - f("WARNING") -# undef f -}; - -#define HTTP_PREFIX "HTTP_" -#define HTTP_PREFIX_LEN (sizeof(HTTP_PREFIX) - 1) - -/* this function is not performance-critical, called only at load time */ -static void init_common_fields(void) -{ - int i; - struct common_field *cf = common_http_fields; - char tmp[64]; - memcpy(tmp, HTTP_PREFIX, HTTP_PREFIX_LEN); - - for(i = ARRAY_SIZE(common_http_fields); --i >= 0; cf++) { - /* Rack doesn't like certain headers prefixed with "HTTP_" */ - if (!strcmp("CONTENT_LENGTH", cf->name) || - !strcmp("CONTENT_TYPE", cf->name)) { - cf->value = rb_str_new(cf->name, cf->len); - } else { - memcpy(tmp + HTTP_PREFIX_LEN, cf->name, cf->len + 1); - cf->value = rb_str_new(tmp, HTTP_PREFIX_LEN + cf->len); - } - cf->value = rb_obj_freeze(cf->value); - rb_global_variable(&cf->value); - } -} - -/* this function is called for every header set */ -static VALUE find_common_field(const char *field, size_t flen) -{ - int i; - struct common_field *cf = common_http_fields; - - for(i = ARRAY_SIZE(common_http_fields); --i >= 0; cf++) { - if (cf->len == (long)flen && !memcmp(cf->name, field, flen)) - return cf->value; - } - return Qnil; -} - -/* - * We got a strange header that we don't have a memoized value for. - * Fallback to creating a new string to use as a hash key. - */ -static VALUE uncommon_field(const char *field, size_t flen) -{ - VALUE f = rb_str_new(NULL, HTTP_PREFIX_LEN + flen); - memcpy(RSTRING_PTR(f), HTTP_PREFIX, HTTP_PREFIX_LEN); - memcpy(RSTRING_PTR(f) + HTTP_PREFIX_LEN, field, flen); - assert(*(RSTRING_PTR(f) + RSTRING_LEN(f)) == '\0' && - "string didn't end with \\0"); /* paranoia */ - return rb_obj_freeze(f); -} - -#endif /* common_field_optimization_h */ diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/ext_help.h b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/ext_help.h deleted file mode 100644 index c87c272..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/ext_help.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef ext_help_h -#define ext_help_h - -#ifndef RSTRING_PTR -#define RSTRING_PTR(s) (RSTRING(s)->ptr) -#endif /* !defined(RSTRING_PTR) */ -#ifndef RSTRING_LEN -#define RSTRING_LEN(s) (RSTRING(s)->len) -#endif /* !defined(RSTRING_LEN) */ - -#ifndef HAVE_RB_STR_SET_LEN -# ifdef RUBINIUS -# error we should never get here with current Rubinius (1.x) -# endif -/* this is taken from Ruby 1.8.7, 1.8.6 may not have it */ -static void rb_18_str_set_len(VALUE str, long len) -{ - RSTRING(str)->len = len; - RSTRING(str)->ptr[len] = '\0'; -} -# define rb_str_set_len(str,len) rb_18_str_set_len(str,len) -#endif /* !defined(HAVE_RB_STR_SET_LEN) */ - -/* not all Ruby implementations support frozen objects (Rubinius does not) */ -#if defined(OBJ_FROZEN) -# define assert_frozen(f) assert(OBJ_FROZEN(f) && "unfrozen object") -#else -# define assert_frozen(f) do {} while (0) -#endif /* !defined(OBJ_FROZEN) */ - -#if !defined(OFFT2NUM) -# if SIZEOF_OFF_T == SIZEOF_LONG -# define OFFT2NUM(n) LONG2NUM(n) -# else -# define OFFT2NUM(n) LL2NUM(n) -# endif -#endif /* ! defined(OFFT2NUM) */ - -#if !defined(SIZET2NUM) -# if SIZEOF_SIZE_T == SIZEOF_LONG -# define SIZET2NUM(n) ULONG2NUM(n) -# else -# define SIZET2NUM(n) ULL2NUM(n) -# endif -#endif /* ! defined(SIZET2NUM) */ - -#if !defined(NUM2SIZET) -# if SIZEOF_SIZE_T == SIZEOF_LONG -# define NUM2SIZET(n) ((size_t)NUM2ULONG(n)) -# else -# define NUM2SIZET(n) ((size_t)NUM2ULL(n)) -# endif -#endif /* ! defined(NUM2SIZET) */ - -static inline int str_cstr_eq(VALUE val, const char *ptr, long len) -{ - return (RSTRING_LEN(val) == len && !memcmp(ptr, RSTRING_PTR(val), len)); -} - -#define STR_CSTR_EQ(val, const_str) \ - str_cstr_eq(val, const_str, sizeof(const_str) - 1) - -/* strcasecmp isn't locale independent */ -static int str_cstr_case_eq(VALUE val, const char *ptr, long len) -{ - if (RSTRING_LEN(val) == len) { - const char *v = RSTRING_PTR(val); - - for (; len--; ++ptr, ++v) { - if ((*ptr == *v) || (*v >= 'A' && *v <= 'Z' && (*v | 0x20) == *ptr)) - continue; - return 0; - } - return 1; - } - return 0; -} - -#define STR_CSTR_CASE_EQ(val, const_str) \ - str_cstr_case_eq(val, const_str, sizeof(const_str) - 1) - -#endif /* ext_help_h */ diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/extconf.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/extconf.rb deleted file mode 100644 index 7a1b0cd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/extconf.rb +++ /dev/null @@ -1,10 +0,0 @@ -# -*- encoding: binary -*- -require 'mkmf' - -have_macro("SIZEOF_OFF_T", "ruby.h") or check_sizeof("off_t", "sys/types.h") -have_macro("SIZEOF_SIZE_T", "ruby.h") or check_sizeof("size_t", "sys/types.h") -have_macro("SIZEOF_LONG", "ruby.h") or check_sizeof("long", "sys/types.h") -have_func("rb_str_set_len", "ruby.h") -have_func("gmtime_r", "time.h") - -create_makefile("unicorn_http") diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/global_variables.h b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/global_variables.h deleted file mode 100644 index e1c43c9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/global_variables.h +++ /dev/null @@ -1,97 +0,0 @@ -#ifndef global_variables_h -#define global_variables_h -static VALUE eHttpParserError; -static VALUE e413; -static VALUE e414; - -static VALUE g_rack_url_scheme; -static VALUE g_request_method; -static VALUE g_request_uri; -static VALUE g_fragment; -static VALUE g_query_string; -static VALUE g_http_version; -static VALUE g_request_path; -static VALUE g_path_info; -static VALUE g_server_name; -static VALUE g_server_port; -static VALUE g_server_protocol; -static VALUE g_http_host; -static VALUE g_http_x_forwarded_proto; -static VALUE g_http_x_forwarded_ssl; -static VALUE g_http_transfer_encoding; -static VALUE g_content_length; -static VALUE g_http_trailer; -static VALUE g_http_connection; -static VALUE g_port_80; -static VALUE g_port_443; -static VALUE g_localhost; -static VALUE g_http; -static VALUE g_https; -static VALUE g_http_09; -static VALUE g_http_10; -static VALUE g_http_11; - -/** Defines common length and error messages for input length validation. */ -#define DEF_MAX_LENGTH(N, length) \ - static const size_t MAX_##N##_LENGTH = length; \ - static const char * const MAX_##N##_LENGTH_ERR = \ - "HTTP element " # N " is longer than the " # length " allowed length." - -NORETURN(static void parser_raise(VALUE klass, const char *)); - -/** - * Validates the max length of given input and throws an HttpParserError - * exception if over. - */ -#define VALIDATE_MAX_LENGTH(len, N) do { \ - if (len > MAX_##N##_LENGTH) \ - parser_raise(eHttpParserError, MAX_##N##_LENGTH_ERR); \ -} while (0) - -#define VALIDATE_MAX_URI_LENGTH(len, N) do { \ - if (len > MAX_##N##_LENGTH) \ - parser_raise(e414, MAX_##N##_LENGTH_ERR); \ -} while (0) - -/** Defines global strings in the init method. */ -#define DEF_GLOBAL(N, val) do { \ - g_##N = rb_obj_freeze(rb_str_new(val, sizeof(val) - 1)); \ - rb_global_variable(&g_##N); \ -} while (0) - -/* Defines the maximum allowed lengths for various input elements.*/ -DEF_MAX_LENGTH(FIELD_NAME, 256); -DEF_MAX_LENGTH(FIELD_VALUE, 80 * 1024); -DEF_MAX_LENGTH(REQUEST_URI, 1024 * 15); -DEF_MAX_LENGTH(FRAGMENT, 1024); /* Don't know if this length is specified somewhere or not */ -DEF_MAX_LENGTH(REQUEST_PATH, 4096); /* common PATH_MAX on modern systems */ -DEF_MAX_LENGTH(QUERY_STRING, (1024 * 10)); - -static void init_globals(void) -{ - DEF_GLOBAL(rack_url_scheme, "rack.url_scheme"); - DEF_GLOBAL(request_method, "REQUEST_METHOD"); - DEF_GLOBAL(request_uri, "REQUEST_URI"); - DEF_GLOBAL(fragment, "FRAGMENT"); - DEF_GLOBAL(query_string, "QUERY_STRING"); - DEF_GLOBAL(http_version, "HTTP_VERSION"); - DEF_GLOBAL(request_path, "REQUEST_PATH"); - DEF_GLOBAL(path_info, "PATH_INFO"); - DEF_GLOBAL(server_name, "SERVER_NAME"); - DEF_GLOBAL(server_port, "SERVER_PORT"); - DEF_GLOBAL(server_protocol, "SERVER_PROTOCOL"); - DEF_GLOBAL(http_x_forwarded_proto, "HTTP_X_FORWARDED_PROTO"); - DEF_GLOBAL(http_x_forwarded_ssl, "HTTP_X_FORWARDED_SSL"); - DEF_GLOBAL(port_80, "80"); - DEF_GLOBAL(port_443, "443"); - DEF_GLOBAL(localhost, "localhost"); - DEF_GLOBAL(http, "http"); - DEF_GLOBAL(https, "https"); - DEF_GLOBAL(http_11, "HTTP/1.1"); - DEF_GLOBAL(http_10, "HTTP/1.0"); - DEF_GLOBAL(http_09, "HTTP/0.9"); -} - -#undef DEF_GLOBAL - -#endif /* global_variables_h */ diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/httpdate.c b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/httpdate.c deleted file mode 100644 index bf54fdd..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/httpdate.c +++ /dev/null @@ -1,78 +0,0 @@ -#include -#include -#include - -static const size_t buf_capa = sizeof("Thu, 01 Jan 1970 00:00:00 GMT"); -static VALUE buf; -static char *buf_ptr; -static const char week[] = "Sun\0Mon\0Tue\0Wed\0Thu\0Fri\0Sat"; -static const char months[] = "Jan\0Feb\0Mar\0Apr\0May\0Jun\0" - "Jul\0Aug\0Sep\0Oct\0Nov\0Dec"; - -/* for people on wonky systems only */ -#ifndef HAVE_GMTIME_R -static struct tm * my_gmtime_r(time_t *now, struct tm *tm) -{ - struct tm *global = gmtime(now); - if (global) - *tm = *global; - return tm; -} -# define gmtime_r my_gmtime_r -#endif - - -/* - * Returns a string which represents the time as rfc1123-date of HTTP-date - * defined by RFC 2616: - * - * day-of-week, DD month-name CCYY hh:mm:ss GMT - * - * Note that the result is always GMT. - * - * This method is identical to Time#httpdate in the Ruby standard library, - * except it is implemented in C for performance. We always saw - * Time#httpdate at or near the top of the profiler output so we - * decided to rewrite this in C. - * - * Caveats: it relies on a Ruby implementation with the global VM lock, - * a thread-safe version will be provided when a Unix-only, GVL-free Ruby - * implementation becomes viable. - */ -static VALUE httpdate(VALUE self) -{ - static time_t last; - time_t now = time(NULL); /* not a syscall on modern 64-bit systems */ - struct tm tm; - - if (last == now) - return buf; - last = now; - gmtime_r(&now, &tm); - - /* we can make this thread-safe later if our Ruby loses the GVL */ - snprintf(buf_ptr, buf_capa, - "%s, %02d %s %4d %02d:%02d:%02d GMT", - week + (tm.tm_wday * 4), - tm.tm_mday, - months + (tm.tm_mon * 4), - tm.tm_year + 1900, - tm.tm_hour, - tm.tm_min, - tm.tm_sec); - - return buf; -} - -void init_unicorn_httpdate(void) -{ - VALUE mod = rb_const_get(rb_cObject, rb_intern("Unicorn")); - mod = rb_define_module_under(mod, "HttpResponse"); - - buf = rb_str_new(0, buf_capa - 1); - rb_global_variable(&buf); - buf_ptr = RSTRING_PTR(buf); - httpdate(Qnil); - - rb_define_method(mod, "httpdate", httpdate, 0); -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/unicorn_http.rl b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/unicorn_http.rl deleted file mode 100644 index 6293033..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/unicorn_http.rl +++ /dev/null @@ -1,1036 +0,0 @@ -/** - * Copyright (c) 2009 Eric Wong (all bugs are Eric's fault) - * Copyright (c) 2005 Zed A. Shaw - * You can redistribute it and/or modify it under the same terms as Ruby 1.8 or - * the GPLv2+ (GPLv3+ preferred) - */ -#include "ruby.h" -#include "ext_help.h" -#include -#include -#include -#include "common_field_optimization.h" -#include "global_variables.h" -#include "c_util.h" - -void init_unicorn_httpdate(void); - -#define UH_FL_CHUNKED 0x1 -#define UH_FL_HASBODY 0x2 -#define UH_FL_INBODY 0x4 -#define UH_FL_HASTRAILER 0x8 -#define UH_FL_INTRAILER 0x10 -#define UH_FL_INCHUNK 0x20 -#define UH_FL_REQEOF 0x40 -#define UH_FL_KAVERSION 0x80 -#define UH_FL_HASHEADER 0x100 -#define UH_FL_TO_CLEAR 0x200 - -/* all of these flags need to be set for keepalive to be supported */ -#define UH_FL_KEEPALIVE (UH_FL_KAVERSION | UH_FL_REQEOF | UH_FL_HASHEADER) - -/* - * whether or not to trust X-Forwarded-Proto and X-Forwarded-SSL when - * setting rack.url_scheme - */ -static VALUE trust_x_forward = Qtrue; - -static unsigned long keepalive_requests = 100; /* same as nginx */ - -/* - * Returns the maximum number of keepalive requests a client may make - * before the parser refuses to continue. - */ -static VALUE ka_req(VALUE self) -{ - return ULONG2NUM(keepalive_requests); -} - -/* - * Sets the maximum number of keepalive requests a client may make. - * A special value of +nil+ causes this to be the maximum value - * possible (this is architecture-dependent). - */ -static VALUE set_ka_req(VALUE self, VALUE val) -{ - keepalive_requests = NIL_P(val) ? ULONG_MAX : NUM2ULONG(val); - - return ka_req(self); -} - -/* - * Sets whether or not the parser will trust X-Forwarded-Proto and - * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly. - * Rainbows!/Zbatery installations facing untrusted clients directly - * should set this to +false+ - */ -static VALUE set_xftrust(VALUE self, VALUE val) -{ - if (Qtrue == val || Qfalse == val) - trust_x_forward = val; - else - rb_raise(rb_eTypeError, "must be true or false"); - - return val; -} - -/* - * returns whether or not the parser will trust X-Forwarded-Proto and - * X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly - */ -static VALUE xftrust(VALUE self) -{ - return trust_x_forward; -} - -static size_t MAX_HEADER_LEN = 1024 * (80 + 32); /* same as Mongrel */ - -/* this is only intended for use with Rainbows! */ -static VALUE set_maxhdrlen(VALUE self, VALUE len) -{ - return SIZET2NUM(MAX_HEADER_LEN = NUM2SIZET(len)); -} - -/* keep this small for Rainbows! since every client has one */ -struct http_parser { - int cs; /* Ragel internal state */ - unsigned int flags; - unsigned long nr_requests; - size_t mark; - size_t offset; - union { /* these 2 fields don't nest */ - size_t field; - size_t query; - } start; - union { - size_t field_len; /* only used during header processing */ - size_t dest_offset; /* only used during body processing */ - } s; - VALUE buf; - VALUE env; - VALUE cont; /* Qfalse: unset, Qnil: ignored header, T_STRING: append */ - union { - off_t content; - off_t chunk; - } len; -}; - -static ID id_clear, id_set_backtrace, id_response_start_sent; - -static void finalize_header(struct http_parser *hp); - -static void parser_raise(VALUE klass, const char *msg) -{ - VALUE exc = rb_exc_new2(klass, msg); - VALUE bt = rb_ary_new(); - - rb_funcall(exc, id_set_backtrace, 1, bt); - rb_exc_raise(exc); -} - -#define REMAINING (unsigned long)(pe - p) -#define LEN(AT, FPC) (FPC - buffer - hp->AT) -#define MARK(M,FPC) (hp->M = (FPC) - buffer) -#define PTR_TO(F) (buffer + hp->F) -#define STR_NEW(M,FPC) rb_str_new(PTR_TO(M), LEN(M, FPC)) -#define STRIPPED_STR_NEW(M,FPC) stripped_str_new(PTR_TO(M), LEN(M, FPC)) - -#define HP_FL_TEST(hp,fl) ((hp)->flags & (UH_FL_##fl)) -#define HP_FL_SET(hp,fl) ((hp)->flags |= (UH_FL_##fl)) -#define HP_FL_UNSET(hp,fl) ((hp)->flags &= ~(UH_FL_##fl)) -#define HP_FL_ALL(hp,fl) (HP_FL_TEST(hp, fl) == (UH_FL_##fl)) - -static int is_lws(char c) -{ - return (c == ' ' || c == '\t'); -} - -static VALUE stripped_str_new(const char *str, long len) -{ - long end; - - for (end = len - 1; end >= 0 && is_lws(str[end]); end--); - - return rb_str_new(str, end + 1); -} - -/* - * handles values of the "Connection:" header, keepalive is implied - * for HTTP/1.1 but needs to be explicitly enabled with HTTP/1.0 - * Additionally, we require GET/HEAD requests to support keepalive. - */ -static void hp_keepalive_connection(struct http_parser *hp, VALUE val) -{ - if (STR_CSTR_CASE_EQ(val, "keep-alive")) { - /* basically have HTTP/1.0 masquerade as HTTP/1.1+ */ - HP_FL_SET(hp, KAVERSION); - } else if (STR_CSTR_CASE_EQ(val, "close")) { - /* - * it doesn't matter what HTTP version or request method we have, - * if a client says "Connection: close", we disable keepalive - */ - HP_FL_UNSET(hp, KAVERSION); - } else { - /* - * client could've sent anything, ignore it for now. Maybe - * "HP_FL_UNSET(hp, KAVERSION);" just in case? - * Raising an exception might be too mean... - */ - } -} - -static void -request_method(struct http_parser *hp, const char *ptr, size_t len) -{ - VALUE v = rb_str_new(ptr, len); - - rb_hash_aset(hp->env, g_request_method, v); -} - -static void -http_version(struct http_parser *hp, const char *ptr, size_t len) -{ - VALUE v; - - HP_FL_SET(hp, HASHEADER); - - if (CONST_MEM_EQ("HTTP/1.1", ptr, len)) { - /* HTTP/1.1 implies keepalive unless "Connection: close" is set */ - HP_FL_SET(hp, KAVERSION); - v = g_http_11; - } else if (CONST_MEM_EQ("HTTP/1.0", ptr, len)) { - v = g_http_10; - } else { - v = rb_str_new(ptr, len); - } - rb_hash_aset(hp->env, g_server_protocol, v); - rb_hash_aset(hp->env, g_http_version, v); -} - -static inline void hp_invalid_if_trailer(struct http_parser *hp) -{ - if (HP_FL_TEST(hp, INTRAILER)) - parser_raise(eHttpParserError, "invalid Trailer"); -} - -static void write_cont_value(struct http_parser *hp, - char *buffer, const char *p) -{ - char *vptr; - long end; - long len = LEN(mark, p); - long cont_len; - - if (hp->cont == Qfalse) - parser_raise(eHttpParserError, "invalid continuation line"); - if (NIL_P(hp->cont)) - return; /* we're ignoring this header (probably Host:) */ - - assert(TYPE(hp->cont) == T_STRING && "continuation line is not a string"); - assert(hp->mark > 0 && "impossible continuation line offset"); - - if (len == 0) - return; - - cont_len = RSTRING_LEN(hp->cont); - if (cont_len > 0) { - --hp->mark; - len = LEN(mark, p); - } - vptr = PTR_TO(mark); - - /* normalize tab to space */ - if (cont_len > 0) { - assert((' ' == *vptr || '\t' == *vptr) && "invalid leading white space"); - *vptr = ' '; - } - - for (end = len - 1; end >= 0 && is_lws(vptr[end]); end--); - rb_str_buf_cat(hp->cont, vptr, end + 1); -} - -static void write_value(struct http_parser *hp, - const char *buffer, const char *p) -{ - VALUE f = find_common_field(PTR_TO(start.field), hp->s.field_len); - VALUE v; - VALUE e; - - VALIDATE_MAX_LENGTH(LEN(mark, p), FIELD_VALUE); - v = LEN(mark, p) == 0 ? rb_str_buf_new(128) : STRIPPED_STR_NEW(mark, p); - if (NIL_P(f)) { - const char *field = PTR_TO(start.field); - size_t flen = hp->s.field_len; - - VALIDATE_MAX_LENGTH(flen, FIELD_NAME); - - /* - * ignore "Version" headers since they conflict with the HTTP_VERSION - * rack env variable. - */ - if (CONST_MEM_EQ("VERSION", field, flen)) { - hp->cont = Qnil; - return; - } - f = uncommon_field(field, flen); - } else if (f == g_http_connection) { - hp_keepalive_connection(hp, v); - } else if (f == g_content_length) { - hp->len.content = parse_length(RSTRING_PTR(v), RSTRING_LEN(v)); - if (hp->len.content < 0) - parser_raise(eHttpParserError, "invalid Content-Length"); - if (hp->len.content != 0) - HP_FL_SET(hp, HASBODY); - hp_invalid_if_trailer(hp); - } else if (f == g_http_transfer_encoding) { - if (STR_CSTR_CASE_EQ(v, "chunked")) { - HP_FL_SET(hp, CHUNKED); - HP_FL_SET(hp, HASBODY); - } - hp_invalid_if_trailer(hp); - } else if (f == g_http_trailer) { - HP_FL_SET(hp, HASTRAILER); - hp_invalid_if_trailer(hp); - } else { - assert(TYPE(f) == T_STRING && "memoized object is not a string"); - assert_frozen(f); - } - - e = rb_hash_aref(hp->env, f); - if (NIL_P(e)) { - hp->cont = rb_hash_aset(hp->env, f, v); - } else if (f == g_http_host) { - /* - * ignored, absolute URLs in REQUEST_URI take precedence over - * the Host: header (ref: rfc 2616, section 5.2.1) - */ - hp->cont = Qnil; - } else { - rb_str_buf_cat(e, ",", 1); - hp->cont = rb_str_buf_append(e, v); - } -} - -/** Machine **/ - -%%{ - machine http_parser; - - action mark {MARK(mark, fpc); } - - action start_field { MARK(start.field, fpc); } - action snake_upcase_field { snake_upcase_char(deconst(fpc)); } - action downcase_char { downcase_char(deconst(fpc)); } - action write_field { hp->s.field_len = LEN(start.field, fpc); } - action start_value { MARK(mark, fpc); } - action write_value { write_value(hp, buffer, fpc); } - action write_cont_value { write_cont_value(hp, buffer, fpc); } - action request_method { request_method(hp, PTR_TO(mark), LEN(mark, fpc)); } - action scheme { - rb_hash_aset(hp->env, g_rack_url_scheme, STR_NEW(mark, fpc)); - } - action host { rb_hash_aset(hp->env, g_http_host, STR_NEW(mark, fpc)); } - action request_uri { - VALUE str; - - VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_URI); - str = rb_hash_aset(hp->env, g_request_uri, STR_NEW(mark, fpc)); - /* - * "OPTIONS * HTTP/1.1\r\n" is a valid request, but we can't have '*' - * in REQUEST_PATH or PATH_INFO or else Rack::Lint will complain - */ - if (STR_CSTR_EQ(str, "*")) { - str = rb_str_new(NULL, 0); - rb_hash_aset(hp->env, g_path_info, str); - rb_hash_aset(hp->env, g_request_path, str); - } - } - action fragment { - VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), FRAGMENT); - rb_hash_aset(hp->env, g_fragment, STR_NEW(mark, fpc)); - } - action start_query {MARK(start.query, fpc); } - action query_string { - VALIDATE_MAX_URI_LENGTH(LEN(start.query, fpc), QUERY_STRING); - rb_hash_aset(hp->env, g_query_string, STR_NEW(start.query, fpc)); - } - action http_version { http_version(hp, PTR_TO(mark), LEN(mark, fpc)); } - action request_path { - VALUE val; - - VALIDATE_MAX_URI_LENGTH(LEN(mark, fpc), REQUEST_PATH); - val = rb_hash_aset(hp->env, g_request_path, STR_NEW(mark, fpc)); - - /* rack says PATH_INFO must start with "/" or be empty */ - if (!STR_CSTR_EQ(val, "*")) - rb_hash_aset(hp->env, g_path_info, val); - } - action add_to_chunk_size { - hp->len.chunk = step_incr(hp->len.chunk, fc, 16); - if (hp->len.chunk < 0) - parser_raise(eHttpParserError, "invalid chunk size"); - } - action header_done { - finalize_header(hp); - - cs = http_parser_first_final; - if (HP_FL_TEST(hp, HASBODY)) { - HP_FL_SET(hp, INBODY); - if (HP_FL_TEST(hp, CHUNKED)) - cs = http_parser_en_ChunkedBody; - } else { - HP_FL_SET(hp, REQEOF); - assert(!HP_FL_TEST(hp, CHUNKED) && "chunked encoding without body!"); - } - /* - * go back to Ruby so we can call the Rack application, we'll reenter - * the parser iff the body needs to be processed. - */ - goto post_exec; - } - - action end_trailers { - cs = http_parser_first_final; - goto post_exec; - } - - action end_chunked_body { - HP_FL_SET(hp, INTRAILER); - cs = http_parser_en_Trailers; - ++p; - assert(p <= pe && "buffer overflow after chunked body"); - goto post_exec; - } - - action skip_chunk_data { - skip_chunk_data_hack: { - size_t nr = MIN((size_t)hp->len.chunk, REMAINING); - memcpy(RSTRING_PTR(hp->cont) + hp->s.dest_offset, fpc, nr); - hp->s.dest_offset += nr; - hp->len.chunk -= nr; - p += nr; - assert(hp->len.chunk >= 0 && "negative chunk length"); - if ((size_t)hp->len.chunk > REMAINING) { - HP_FL_SET(hp, INCHUNK); - goto post_exec; - } else { - fhold; - fgoto chunk_end; - } - }} - - include unicorn_http_common "unicorn_http_common.rl"; -}%% - -/** Data **/ -%% write data; - -static void http_parser_init(struct http_parser *hp) -{ - int cs = 0; - hp->flags = 0; - hp->mark = 0; - hp->offset = 0; - hp->start.field = 0; - hp->s.field_len = 0; - hp->len.content = 0; - hp->cont = Qfalse; /* zero on MRI, should be optimized away by above */ - %% write init; - hp->cs = cs; -} - -/** exec **/ -static void -http_parser_execute(struct http_parser *hp, char *buffer, size_t len) -{ - const char *p, *pe; - int cs = hp->cs; - size_t off = hp->offset; - - if (cs == http_parser_first_final) - return; - - assert(off <= len && "offset past end of buffer"); - - p = buffer+off; - pe = buffer+len; - - assert((void *)(pe - p) == (void *)(len - off) && - "pointers aren't same distance"); - - if (HP_FL_TEST(hp, INCHUNK)) { - HP_FL_UNSET(hp, INCHUNK); - goto skip_chunk_data_hack; - } - %% write exec; -post_exec: /* "_out:" also goes here */ - if (hp->cs != http_parser_error) - hp->cs = cs; - hp->offset = p - buffer; - - assert(p <= pe && "buffer overflow after parsing execute"); - assert(hp->offset <= len && "offset longer than length"); -} - -static struct http_parser *data_get(VALUE self) -{ - struct http_parser *hp; - - Data_Get_Struct(self, struct http_parser, hp); - assert(hp && "failed to extract http_parser struct"); - return hp; -} - -/* - * set rack.url_scheme to "https" or "http", no others are allowed by Rack - * this resembles the Rack::Request#scheme method as of rack commit - * 35bb5ba6746b5d346de9202c004cc926039650c7 - */ -static void set_url_scheme(VALUE env, VALUE *server_port) -{ - VALUE scheme = rb_hash_aref(env, g_rack_url_scheme); - - if (NIL_P(scheme)) { - if (trust_x_forward == Qfalse) { - scheme = g_http; - } else { - scheme = rb_hash_aref(env, g_http_x_forwarded_ssl); - if (!NIL_P(scheme) && STR_CSTR_EQ(scheme, "on")) { - *server_port = g_port_443; - scheme = g_https; - } else { - scheme = rb_hash_aref(env, g_http_x_forwarded_proto); - if (NIL_P(scheme)) { - scheme = g_http; - } else { - long len = RSTRING_LEN(scheme); - if (len >= 5 && !memcmp(RSTRING_PTR(scheme), "https", 5)) { - if (len != 5) - scheme = g_https; - *server_port = g_port_443; - } else { - scheme = g_http; - } - } - } - } - rb_hash_aset(env, g_rack_url_scheme, scheme); - } else if (STR_CSTR_EQ(scheme, "https")) { - *server_port = g_port_443; - } else { - assert(*server_port == g_port_80 && "server_port not set"); - } -} - -/* - * Parse and set the SERVER_NAME and SERVER_PORT variables - * Not supporting X-Forwarded-Host/X-Forwarded-Port in here since - * anybody who needs them is using an unsupported configuration and/or - * incompetent. Rack::Request will handle X-Forwarded-{Port,Host} just - * fine. - */ -static void set_server_vars(VALUE env, VALUE *server_port) -{ - VALUE server_name = g_localhost; - VALUE host = rb_hash_aref(env, g_http_host); - - if (!NIL_P(host)) { - char *host_ptr = RSTRING_PTR(host); - long host_len = RSTRING_LEN(host); - char *colon; - - if (*host_ptr == '[') { /* ipv6 address format */ - char *rbracket = memchr(host_ptr + 1, ']', host_len - 1); - - if (rbracket) - colon = (rbracket[1] == ':') ? rbracket + 1 : NULL; - else - colon = memchr(host_ptr + 1, ':', host_len - 1); - } else { - colon = memchr(host_ptr, ':', host_len); - } - - if (colon) { - long port_start = colon - host_ptr + 1; - - server_name = rb_str_substr(host, 0, colon - host_ptr); - if ((host_len - port_start) > 0) - *server_port = rb_str_substr(host, port_start, host_len); - } else { - server_name = host; - } - } - rb_hash_aset(env, g_server_name, server_name); - rb_hash_aset(env, g_server_port, *server_port); -} - -static void finalize_header(struct http_parser *hp) -{ - VALUE server_port = g_port_80; - - set_url_scheme(hp->env, &server_port); - set_server_vars(hp->env, &server_port); - - if (!HP_FL_TEST(hp, HASHEADER)) - rb_hash_aset(hp->env, g_server_protocol, g_http_09); - - /* rack requires QUERY_STRING */ - if (NIL_P(rb_hash_aref(hp->env, g_query_string))) - rb_hash_aset(hp->env, g_query_string, rb_str_new(NULL, 0)); -} - -static void hp_mark(void *ptr) -{ - struct http_parser *hp = ptr; - - rb_gc_mark(hp->buf); - rb_gc_mark(hp->env); - rb_gc_mark(hp->cont); -} - -static VALUE HttpParser_alloc(VALUE klass) -{ - struct http_parser *hp; - return Data_Make_Struct(klass, struct http_parser, hp_mark, -1, hp); -} - - -/** - * call-seq: - * parser.new => parser - * - * Creates a new parser. - */ -static VALUE HttpParser_init(VALUE self) -{ - struct http_parser *hp = data_get(self); - - http_parser_init(hp); - hp->buf = rb_str_new(NULL, 0); - hp->env = rb_hash_new(); - hp->nr_requests = keepalive_requests; - - return self; -} - -/** - * call-seq: - * parser.clear => parser - * - * Resets the parser to it's initial state so that you can reuse it - * rather than making new ones. - */ -static VALUE HttpParser_clear(VALUE self) -{ - struct http_parser *hp = data_get(self); - - http_parser_init(hp); - rb_funcall(hp->env, id_clear, 0); - rb_ivar_set(self, id_response_start_sent, Qfalse); - - return self; -} - -/** - * call-seq: - * parser.dechunk! => parser - * - * Resets the parser to a state suitable for dechunking response bodies - * - */ -static VALUE HttpParser_dechunk_bang(VALUE self) -{ - struct http_parser *hp = data_get(self); - - http_parser_init(hp); - - /* - * we don't care about trailers in dechunk-only mode, - * but if we did we'd set UH_FL_HASTRAILER and clear hp->env - */ - if (0) { - rb_funcall(hp->env, id_clear, 0); - hp->flags = UH_FL_HASTRAILER; - } - - hp->flags |= UH_FL_HASBODY | UH_FL_INBODY | UH_FL_CHUNKED; - hp->cs = http_parser_en_ChunkedBody; - - return self; -} - -/** - * call-seq: - * parser.reset => nil - * - * Resets the parser to it's initial state so that you can reuse it - * rather than making new ones. - * - * This method is deprecated and to be removed in Unicorn 4.x - */ -static VALUE HttpParser_reset(VALUE self) -{ - static int warned; - - if (!warned) { - rb_warn("Unicorn::HttpParser#reset is deprecated; " - "use Unicorn::HttpParser#clear instead"); - } - HttpParser_clear(self); - return Qnil; -} - -static void advance_str(VALUE str, off_t nr) -{ - long len = RSTRING_LEN(str); - - if (len == 0) - return; - - rb_str_modify(str); - - assert(nr <= len && "trying to advance past end of buffer"); - len -= nr; - if (len > 0) /* unlikely, len is usually 0 */ - memmove(RSTRING_PTR(str), RSTRING_PTR(str) + nr, len); - rb_str_set_len(str, len); -} - -/** - * call-seq: - * parser.content_length => nil or Integer - * - * Returns the number of bytes left to run through HttpParser#filter_body. - * This will initially be the value of the "Content-Length" HTTP header - * after header parsing is complete and will decrease in value as - * HttpParser#filter_body is called for each chunk. This should return - * zero for requests with no body. - * - * This will return nil on "Transfer-Encoding: chunked" requests. - */ -static VALUE HttpParser_content_length(VALUE self) -{ - struct http_parser *hp = data_get(self); - - return HP_FL_TEST(hp, CHUNKED) ? Qnil : OFFT2NUM(hp->len.content); -} - -/** - * Document-method: parse - * call-seq: - * parser.parse => env or nil - * - * Takes a Hash and a String of data, parses the String of data filling - * in the Hash returning the Hash if parsing is finished, nil otherwise - * When returning the env Hash, it may modify data to point to where - * body processing should begin. - * - * Raises HttpParserError if there are parsing errors. - */ -static VALUE HttpParser_parse(VALUE self) -{ - struct http_parser *hp = data_get(self); - VALUE data = hp->buf; - - if (HP_FL_TEST(hp, TO_CLEAR)) - HttpParser_clear(self); - - http_parser_execute(hp, RSTRING_PTR(data), RSTRING_LEN(data)); - if (hp->offset > MAX_HEADER_LEN) - parser_raise(e413, "HTTP header is too large"); - - if (hp->cs == http_parser_first_final || - hp->cs == http_parser_en_ChunkedBody) { - advance_str(data, hp->offset + 1); - hp->offset = 0; - if (HP_FL_TEST(hp, INTRAILER)) - HP_FL_SET(hp, REQEOF); - - return hp->env; - } - - if (hp->cs == http_parser_error) - parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails."); - - return Qnil; -} - -/** - * Document-method: parse - * call-seq: - * parser.add_parse(buffer) => env or nil - * - * adds the contents of +buffer+ to the internal buffer and attempts to - * continue parsing. Returns the +env+ Hash on success or nil if more - * data is needed. - * - * Raises HttpParserError if there are parsing errors. - */ -static VALUE HttpParser_add_parse(VALUE self, VALUE buffer) -{ - struct http_parser *hp = data_get(self); - - Check_Type(buffer, T_STRING); - rb_str_buf_append(hp->buf, buffer); - - return HttpParser_parse(self); -} - -/** - * Document-method: trailers - * call-seq: - * parser.trailers(req, data) => req or nil - * - * This is an alias for HttpParser#headers - */ - -/** - * Document-method: headers - */ -static VALUE HttpParser_headers(VALUE self, VALUE env, VALUE buf) -{ - struct http_parser *hp = data_get(self); - - hp->env = env; - hp->buf = buf; - - return HttpParser_parse(self); -} - -static int chunked_eof(struct http_parser *hp) -{ - return ((hp->cs == http_parser_first_final) || HP_FL_TEST(hp, INTRAILER)); -} - -/** - * call-seq: - * parser.body_eof? => true or false - * - * Detects if we're done filtering the body or not. This can be used - * to detect when to stop calling HttpParser#filter_body. - */ -static VALUE HttpParser_body_eof(VALUE self) -{ - struct http_parser *hp = data_get(self); - - if (HP_FL_TEST(hp, CHUNKED)) - return chunked_eof(hp) ? Qtrue : Qfalse; - - return hp->len.content == 0 ? Qtrue : Qfalse; -} - -/** - * call-seq: - * parser.keepalive? => true or false - * - * This should be used to detect if a request can really handle - * keepalives and pipelining. Currently, the rules are: - * - * 1. MUST be a GET or HEAD request - * 2. MUST be HTTP/1.1 +or+ HTTP/1.0 with "Connection: keep-alive" - * 3. MUST NOT have "Connection: close" set - */ -static VALUE HttpParser_keepalive(VALUE self) -{ - struct http_parser *hp = data_get(self); - - return HP_FL_ALL(hp, KEEPALIVE) ? Qtrue : Qfalse; -} - -/** - * call-seq: - * parser.next? => true or false - * - * Exactly like HttpParser#keepalive?, except it will reset the internal - * parser state on next parse if it returns true. It will also respect - * the maximum *keepalive_requests* value and return false if that is - * reached. - */ -static VALUE HttpParser_next(VALUE self) -{ - struct http_parser *hp = data_get(self); - - if ((HP_FL_ALL(hp, KEEPALIVE)) && (hp->nr_requests-- != 0)) { - HP_FL_SET(hp, TO_CLEAR); - return Qtrue; - } - return Qfalse; -} - -/** - * call-seq: - * parser.headers? => true or false - * - * This should be used to detect if a request has headers (and if - * the response will have headers as well). HTTP/0.9 requests - * should return false, all subsequent HTTP versions will return true - */ -static VALUE HttpParser_has_headers(VALUE self) -{ - struct http_parser *hp = data_get(self); - - return HP_FL_TEST(hp, HASHEADER) ? Qtrue : Qfalse; -} - -static VALUE HttpParser_buf(VALUE self) -{ - return data_get(self)->buf; -} - -static VALUE HttpParser_env(VALUE self) -{ - return data_get(self)->env; -} - -/** - * call-seq: - * parser.filter_body(dst, src) => nil/src - * - * Takes a String of +src+, will modify data if dechunking is done. - * Returns +nil+ if there is more data left to process. Returns - * +src+ if body processing is complete. When returning +src+, - * it may modify +src+ so the start of the string points to where - * the body ended so that trailer processing can begin. - * - * Raises HttpParserError if there are dechunking errors. - * Basically this is a glorified memcpy(3) that copies +src+ - * into +buf+ while filtering it through the dechunker. - */ -static VALUE HttpParser_filter_body(VALUE self, VALUE dst, VALUE src) -{ - struct http_parser *hp = data_get(self); - char *srcptr; - long srclen; - - srcptr = RSTRING_PTR(src); - srclen = RSTRING_LEN(src); - - StringValue(dst); - - if (HP_FL_TEST(hp, CHUNKED)) { - if (!chunked_eof(hp)) { - rb_str_modify(dst); - rb_str_resize(dst, srclen); /* we can never copy more than srclen bytes */ - - hp->s.dest_offset = 0; - hp->cont = dst; - hp->buf = src; - http_parser_execute(hp, srcptr, srclen); - if (hp->cs == http_parser_error) - parser_raise(eHttpParserError, "Invalid HTTP format, parsing fails."); - - assert(hp->s.dest_offset <= hp->offset && - "destination buffer overflow"); - advance_str(src, hp->offset); - rb_str_set_len(dst, hp->s.dest_offset); - - if (RSTRING_LEN(dst) == 0 && chunked_eof(hp)) { - assert(hp->len.chunk == 0 && "chunk at EOF but more to parse"); - } else { - src = Qnil; - } - } - } else { - /* no need to enter the Ragel machine for unchunked transfers */ - assert(hp->len.content >= 0 && "negative Content-Length"); - if (hp->len.content > 0) { - long nr = MIN(srclen, hp->len.content); - - rb_str_modify(dst); - rb_str_resize(dst, nr); - /* - * using rb_str_replace() to avoid memcpy() doesn't help in - * most cases because a GC-aware programmer will pass an explicit - * buffer to env["rack.input"].read and reuse the buffer in a loop. - * This causes copy-on-write behavior to be triggered anyways - * when the +src+ buffer is modified (when reading off the socket). - */ - hp->buf = src; - memcpy(RSTRING_PTR(dst), srcptr, nr); - hp->len.content -= nr; - if (hp->len.content == 0) { - HP_FL_SET(hp, REQEOF); - hp->cs = http_parser_first_final; - } - advance_str(src, nr); - src = Qnil; - } - } - hp->offset = 0; /* for trailer parsing */ - return src; -} - -#define SET_GLOBAL(var,str) do { \ - var = find_common_field(str, sizeof(str) - 1); \ - assert(!NIL_P(var) && "missed global field"); \ -} while (0) - -void Init_unicorn_http(void) -{ - VALUE mUnicorn, cHttpParser; - - mUnicorn = rb_const_get(rb_cObject, rb_intern("Unicorn")); - cHttpParser = rb_define_class_under(mUnicorn, "HttpParser", rb_cObject); - eHttpParserError = - rb_define_class_under(mUnicorn, "HttpParserError", rb_eIOError); - e413 = rb_define_class_under(mUnicorn, "RequestEntityTooLargeError", - eHttpParserError); - e414 = rb_define_class_under(mUnicorn, "RequestURITooLongError", - eHttpParserError); - - init_globals(); - rb_define_alloc_func(cHttpParser, HttpParser_alloc); - rb_define_method(cHttpParser, "initialize", HttpParser_init, 0); - rb_define_method(cHttpParser, "clear", HttpParser_clear, 0); - rb_define_method(cHttpParser, "reset", HttpParser_reset, 0); - rb_define_method(cHttpParser, "dechunk!", HttpParser_dechunk_bang, 0); - rb_define_method(cHttpParser, "parse", HttpParser_parse, 0); - rb_define_method(cHttpParser, "add_parse", HttpParser_add_parse, 1); - rb_define_method(cHttpParser, "headers", HttpParser_headers, 2); - rb_define_method(cHttpParser, "trailers", HttpParser_headers, 2); - rb_define_method(cHttpParser, "filter_body", HttpParser_filter_body, 2); - rb_define_method(cHttpParser, "content_length", HttpParser_content_length, 0); - rb_define_method(cHttpParser, "body_eof?", HttpParser_body_eof, 0); - rb_define_method(cHttpParser, "keepalive?", HttpParser_keepalive, 0); - rb_define_method(cHttpParser, "headers?", HttpParser_has_headers, 0); - rb_define_method(cHttpParser, "next?", HttpParser_next, 0); - rb_define_method(cHttpParser, "buf", HttpParser_buf, 0); - rb_define_method(cHttpParser, "env", HttpParser_env, 0); - - /* - * The maximum size a single chunk when using chunked transfer encoding. - * This is only a theoretical maximum used to detect errors in clients, - * it is highly unlikely to encounter clients that send more than - * several kilobytes at once. - */ - rb_define_const(cHttpParser, "CHUNK_MAX", OFFT2NUM(UH_OFF_T_MAX)); - - /* - * The maximum size of the body as specified by Content-Length. - * This is only a theoretical maximum, the actual limit is subject - * to the limits of the file system used for +Dir.tmpdir+. - */ - rb_define_const(cHttpParser, "LENGTH_MAX", OFFT2NUM(UH_OFF_T_MAX)); - - /* default value for keepalive_requests */ - rb_define_const(cHttpParser, "KEEPALIVE_REQUESTS_DEFAULT", - ULONG2NUM(keepalive_requests)); - - rb_define_singleton_method(cHttpParser, "keepalive_requests", ka_req, 0); - rb_define_singleton_method(cHttpParser, "keepalive_requests=", set_ka_req, 1); - rb_define_singleton_method(cHttpParser, "trust_x_forwarded=", set_xftrust, 1); - rb_define_singleton_method(cHttpParser, "trust_x_forwarded?", xftrust, 0); - rb_define_singleton_method(cHttpParser, "max_header_len=", set_maxhdrlen, 1); - - init_common_fields(); - SET_GLOBAL(g_http_host, "HOST"); - SET_GLOBAL(g_http_trailer, "TRAILER"); - SET_GLOBAL(g_http_transfer_encoding, "TRANSFER_ENCODING"); - SET_GLOBAL(g_content_length, "CONTENT_LENGTH"); - SET_GLOBAL(g_http_connection, "CONNECTION"); - id_clear = rb_intern("clear"); - id_set_backtrace = rb_intern("set_backtrace"); - id_response_start_sent = rb_intern("@response_start_sent"); - init_unicorn_httpdate(); -} -#undef SET_GLOBAL diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/unicorn_http_common.rl b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/unicorn_http_common.rl deleted file mode 100644 index cc1d455..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/ext/unicorn_http/unicorn_http_common.rl +++ /dev/null @@ -1,76 +0,0 @@ -%%{ - - machine unicorn_http_common; - -#### HTTP PROTOCOL GRAMMAR -# line endings - CRLF = "\r\n"; - -# character types - CTL = (cntrl | 127); - safe = ("$" | "-" | "_" | "."); - extra = ("!" | "*" | "'" | "(" | ")" | ","); - reserved = (";" | "/" | "?" | ":" | "@" | "&" | "=" | "+"); - sorta_safe = ("\"" | "<" | ">"); - unsafe = (CTL | " " | "#" | "%" | sorta_safe); - national = any -- (alpha | digit | reserved | extra | safe | unsafe); - unreserved = (alpha | digit | safe | extra | national); - escape = ("%" xdigit xdigit); - uchar = (unreserved | escape | sorta_safe); - pchar = (uchar | ":" | "@" | "&" | "=" | "+"); - tspecials = ("(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\\" | "\"" | "/" | "[" | "]" | "?" | "=" | "{" | "}" | " " | "\t"); - lws = (" " | "\t"); - content = ((any -- CTL) | lws); - -# elements - token = (ascii -- (CTL | tspecials)); - -# URI schemes and absolute paths - scheme = ( "http"i ("s"i)? ) $downcase_char >mark %scheme; - hostname = ((alnum | "-" | "." | "_")+ | ("[" (":" | xdigit)+ "]")); - host_with_port = (hostname (":" digit*)?) >mark %host; - userinfo = ((unreserved | escape | ";" | ":" | "&" | "=" | "+")+ "@")*; - - path = ( pchar+ ( "/" pchar* )* ) ; - query = ( uchar | reserved )* %query_string ; - param = ( pchar | "/" )* ; - params = ( param ( ";" param )* ) ; - rel_path = (path? (";" params)? %request_path) ("?" %start_query query)?; - absolute_path = ( "/"+ rel_path ); - path_uri = absolute_path > mark %request_uri; - Absolute_URI = (scheme "://" userinfo host_with_port path_uri); - - Request_URI = ((absolute_path | "*") >mark %request_uri) | Absolute_URI; - Fragment = ( uchar | reserved )* >mark %fragment; - Method = (token){1,20} >mark %request_method; - GetOnly = "GET" >mark %request_method; - - http_number = ( digit+ "." digit+ ) ; - HTTP_Version = ( "HTTP/" http_number ) >mark %http_version ; - Request_Line = ( Method " " Request_URI ("#" Fragment){0,1} " " HTTP_Version CRLF ) ; - - field_name = ( token -- ":" )+ >start_field $snake_upcase_field %write_field; - - field_value = content* >start_value %write_value; - - value_cont = lws+ content* >start_value %write_cont_value; - - message_header = ((field_name ":" lws* field_value)|value_cont) :> CRLF; - chunk_ext_val = token*; - chunk_ext_name = token*; - chunk_extension = ( ";" " "* chunk_ext_name ("=" chunk_ext_val)? )*; - last_chunk = "0"+ chunk_extension CRLF; - chunk_size = (xdigit* [1-9a-fA-F] xdigit*) $add_to_chunk_size; - chunk_end = CRLF; - chunk_body = any >skip_chunk_data; - chunk_begin = chunk_size chunk_extension CRLF; - chunk = chunk_begin chunk_body chunk_end; - ChunkedBody := chunk* last_chunk @end_chunked_body; - Trailers := (message_header)* CRLF @end_trailers; - - FullRequest = Request_Line (message_header)* CRLF @header_done; - SimpleRequest = GetOnly " " Request_URI ("#"Fragment){0,1} CRLF @header_done; - -main := FullRequest | SimpleRequest; - -}%% diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn.rb deleted file mode 100644 index 638b846..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn.rb +++ /dev/null @@ -1,118 +0,0 @@ -# -*- encoding: binary -*- -require 'fcntl' -require 'etc' -require 'stringio' -require 'rack' -require 'kgio' - -# :stopdoc: -# Unicorn module containing all of the classes (include C extensions) for -# running a Unicorn web server. It contains a minimalist HTTP server with just -# enough functionality to service web application requests fast as possible. -# :startdoc: - -# \Unicorn exposes very little of an user-visible API and most of its -# internals are subject to change. \Unicorn is designed to host Rack -# applications, so applications should be written against the Rack SPEC -# and not \Unicorn internals. -module Unicorn - - # Raised inside TeeInput when a client closes the socket inside the - # application dispatch. This is always raised with an empty backtrace - # since there is nothing in the application stack that is responsible - # for client shutdowns/disconnects. This exception is visible to Rack - # applications unless PrereadInput middleware is loaded. - class ClientShutdown < EOFError - end - - # :stopdoc: - - # This returns a lambda to pass in as the app, this does not "build" the - # app (which we defer based on the outcome of "preload_app" in the - # Unicorn config). The returned lambda will be called when it is - # time to build the app. - def self.builder(ru, op) - # allow Configurator to parse cli switches embedded in the ru file - op = Unicorn::Configurator::RACKUP.merge!(:file => ru, :optparse => op) - - # Op is going to get cleared before the returned lambda is called, so - # save this value so that it's still there when we need it: - no_default_middleware = op[:no_default_middleware] - - # always called after config file parsing, may be called after forking - lambda do || - inner_app = case ru - when /\.ru$/ - raw = File.read(ru) - raw.sub!(/^__END__\n.*/, '') - eval("Rack::Builder.new {(\n#{raw}\n)}.to_app", TOPLEVEL_BINDING, ru) - else - require ru - Object.const_get(File.basename(ru, '.rb').capitalize) - end - - pp({ :inner_app => inner_app }) if $DEBUG - - return inner_app if no_default_middleware - - # return value, matches rackup defaults based on env - # Unicorn does not support persistent connections, but Rainbows! - # and Zbatery both do. Users accustomed to the Rack::Server default - # middlewares will need ContentLength/Chunked middlewares. - case ENV["RACK_ENV"] - when "development" - Rack::Builder.new do - use Rack::ContentLength - use Rack::Chunked - use Rack::CommonLogger, $stderr - use Rack::ShowExceptions - use Rack::Lint - run inner_app - end.to_app - when "deployment" - Rack::Builder.new do - use Rack::ContentLength - use Rack::Chunked - use Rack::CommonLogger, $stderr - run inner_app - end.to_app - else - inner_app - end - end - end - - # returns an array of strings representing TCP listen socket addresses - # and Unix domain socket paths. This is useful for use with - # Raindrops::Middleware under Linux: http://raindrops.bogomips.org/ - def self.listener_names - Unicorn::HttpServer::LISTENERS.map do |io| - Unicorn::SocketHelper.sock_name(io) - end + Unicorn::HttpServer::NEW_LISTENERS - end - - def self.log_error(logger, prefix, exc) - message = exc.message - message = message.dump if /[[:cntrl:]]/ =~ message - logger.error "#{prefix}: #{message} (#{exc.class})" - exc.backtrace.each { |line| logger.error(line) } - end - - # remove this when we only support Ruby >= 2.0 - def self.pipe # :nodoc: - Kgio::Pipe.new.each { |io| io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) } - end - # :startdoc: -end -# :enddoc: -require 'unicorn/const' -require 'unicorn/socket_helper' -require 'unicorn/stream_input' -require 'unicorn/tee_input' -require 'unicorn/http_request' -require 'unicorn/configurator' -require 'unicorn/tmpio' -require 'unicorn/util' -require 'unicorn/http_response' -require 'unicorn/worker' -require 'unicorn/http_server' diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/exec_cgi.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/exec_cgi.rb deleted file mode 100644 index 232b681..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/exec_cgi.rb +++ /dev/null @@ -1,154 +0,0 @@ -# -*- encoding: binary -*- -# :enddoc: -require 'unicorn' - -module Unicorn::App - - # This class is highly experimental (even more so than the rest of Unicorn) - # and has never run anything other than cgit. - class ExecCgi < Struct.new(:args) - - CHUNK_SIZE = 16384 - PASS_VARS = %w( - CONTENT_LENGTH - CONTENT_TYPE - GATEWAY_INTERFACE - AUTH_TYPE - PATH_INFO - PATH_TRANSLATED - QUERY_STRING - REMOTE_ADDR - REMOTE_HOST - REMOTE_IDENT - REMOTE_USER - REQUEST_METHOD - SERVER_NAME - SERVER_PORT - SERVER_PROTOCOL - SERVER_SOFTWARE - ).map { |x| x.freeze } # frozen strings are faster for Hash assignments - - class Body < Unicorn::TmpIO - def body_offset=(n) - sysseek(@body_offset = n) - end - - def each - sysseek @body_offset - # don't use a preallocated buffer for sysread since we can't - # guarantee an actual socket is consuming the yielded string - # (or if somebody is pushing to an array for eventual concatenation - begin - yield sysread(CHUNK_SIZE) - rescue EOFError - break - end while true - end - end - - # Intializes the app, example of usage in a config.ru - # map "/cgit" do - # run Unicorn::App::ExecCgi.new("/path/to/cgit.cgi") - # end - def initialize(*args) - self.args = args - first = args[0] or - raise ArgumentError, "need path to executable" - first[0] == ?/ or args[0] = ::File.expand_path(first) - File.executable?(args[0]) or - raise ArgumentError, "#{args[0]} is not executable" - end - - # Calls the app - def call(env) - out, err = Body.new, Unicorn::TmpIO.new - inp = force_file_input(env) - pid = fork { run_child(inp, out, err, env) } - inp.close - pid, status = Process.waitpid2(pid) - write_errors(env, err, status) if err.stat.size > 0 - err.close - - return parse_output!(out) if status.success? - out.close - [ 500, { 'Content-Length' => '0', 'Content-Type' => 'text/plain' }, [] ] - end - - private - - def run_child(inp, out, err, env) - PASS_VARS.each do |key| - val = env[key] or next - ENV[key] = val - end - ENV['SCRIPT_NAME'] = args[0] - ENV['GATEWAY_INTERFACE'] = 'CGI/1.1' - env.keys.grep(/^HTTP_/) { |key| ENV[key] = env[key] } - - $stdin.reopen(inp) - $stdout.reopen(out) - $stderr.reopen(err) - exec(*args) - end - - # Extracts headers from CGI out, will change the offset of out. - # This returns a standard Rack-compatible return value: - # [ 200, HeadersHash, body ] - def parse_output!(out) - size = out.stat.size - out.sysseek(0) - head = out.sysread(CHUNK_SIZE) - offset = 2 - head, body = head.split(/\n\n/, 2) - if body.nil? - head, body = head.split(/\r\n\r\n/, 2) - offset = 4 - end - offset += head.length - out.body_offset = offset - size -= offset - prev = nil - headers = Rack::Utils::HeaderHash.new - head.split(/\r?\n/).each do |line| - case line - when /^([A-Za-z0-9-]+):\s*(.*)$/ then headers[prev = $1] = $2 - when /^[ \t]/ then headers[prev] << "\n#{line}" if prev - end - end - status = headers.delete("Status") || 200 - headers['Content-Length'] = size.to_s - [ status, headers, out ] - end - - # ensures rack.input is a file handle that we can redirect stdin to - def force_file_input(env) - inp = env['rack.input'] - # inp could be a StringIO or StringIO-like object - if inp.respond_to?(:size) && inp.size == 0 - ::File.open('/dev/null', 'rb') - else - tmp = Unicorn::TmpIO.new - - buf = inp.read(CHUNK_SIZE) - begin - tmp.syswrite(buf) - end while inp.read(CHUNK_SIZE, buf) - tmp.sysseek(0) - tmp - end - end - - # rack.errors this may not be an IO object, so we couldn't - # just redirect the CGI executable to that earlier. - def write_errors(env, err, status) - err.seek(0) - dst = env['rack.errors'] - pid = status.pid - dst.write("#{pid}: #{args.inspect} status=#{status} stderr:\n") - err.each_line { |line| dst.write("#{pid}: #{line}") } - dst.flush - end - - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/inetd.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/inetd.rb deleted file mode 100644 index 13b6624..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/inetd.rb +++ /dev/null @@ -1,109 +0,0 @@ -# -*- encoding: binary -*- -# :enddoc: -# Copyright (c) 2009 Eric Wong -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) - -# this class *must* be used with Rack::Chunked -module Unicorn::App - class Inetd < Struct.new(:cmd) - - class CatBody < Struct.new(:errors, :err_rd, :out_rd, :pid_map) - def initialize(env, cmd) - self.errors = env['rack.errors'] - in_rd, in_wr = IO.pipe - self.err_rd, err_wr = IO.pipe - self.out_rd, out_wr = IO.pipe - - cmd_pid = fork { - inp, out, err = (0..2).map { |i| IO.new(i) } - inp.reopen(in_rd) - out.reopen(out_wr) - err.reopen(err_wr) - [ in_rd, in_wr, err_rd, err_wr, out_rd, out_wr ].each { |i| i.close } - exec(*cmd) - } - [ in_rd, err_wr, out_wr ].each { |io| io.close } - [ in_wr, err_rd, out_rd ].each { |io| io.binmode } - in_wr.sync = true - - # Unfortunately, input here must be processed inside a seperate - # thread/process using blocking I/O since env['rack.input'] is not - # IO.select-able and attempting to make it so would trip Rack::Lint - inp_pid = fork { - input = env['rack.input'] - [ err_rd, out_rd ].each { |io| io.close } - - # this is dependent on input.read having readpartial semantics: - buf = input.read(16384) - begin - in_wr.write(buf) - end while input.read(16384, buf) - } - in_wr.close - self.pid_map = { - inp_pid => 'input streamer', - cmd_pid => cmd.inspect, - } - end - - def each - begin - rd, = IO.select([err_rd, out_rd]) - rd && rd.first or next - - if rd.include?(err_rd) - begin - errors.write(err_rd.read_nonblock(16384)) - rescue Errno::EINTR - rescue Errno::EAGAIN - break - end while true - end - - rd.include?(out_rd) or next - - begin - yield out_rd.read_nonblock(16384) - rescue Errno::EINTR - rescue Errno::EAGAIN - break - end while true - rescue EOFError,Errno::EPIPE,Errno::EBADF,Errno::EINVAL - break - end while true - - self - end - - def close - pid_map.each { |pid, str| - begin - pid, status = Process.waitpid2(pid) - status.success? or - errors.write("#{str}: #{status.inspect} (PID:#{pid})\n") - rescue Errno::ECHILD - errors.write("Failed to reap #{str} (PID:#{pid})\n") - end - } - out_rd.close - err_rd.close - end - - end - - def initialize(*cmd) - self.cmd = cmd - end - - def call(env) - /\A100-continue\z/i =~ env[Unicorn::Const::HTTP_EXPECT] and - return [ 100, {} , [] ] - - [ 200, { 'Content-Type' => 'application/octet-stream' }, - CatBody.new(env, cmd) ] - end - - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/old_rails.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/old_rails.rb deleted file mode 100644 index 1e8c41a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/old_rails.rb +++ /dev/null @@ -1,35 +0,0 @@ -# -*- encoding: binary -*- - -# :enddoc: -# This code is based on the original Rails handler in Mongrel -# Copyright (c) 2005 Zed A. Shaw -# Copyright (c) 2009 Eric Wong -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) -# Additional work donated by contributors. See CONTRIBUTORS for more info. -require 'unicorn/cgi_wrapper' -require 'dispatcher' - -module Unicorn; module App; end; end - -# Implements a handler that can run Rails. -class Unicorn::App::OldRails - - autoload :Static, "unicorn/app/old_rails/static" - - def call(env) - cgi = Unicorn::CGIWrapper.new(env) - begin - Dispatcher.dispatch(cgi, - ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS, - cgi.body) - rescue => e - err = env['rack.errors'] - err.write("#{e} #{e.message}\n") - e.backtrace.each { |line| err.write("#{line}\n") } - end - cgi.out # finalize the response - cgi.rack_response - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/old_rails/static.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/old_rails/static.rb deleted file mode 100644 index 2257270..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/app/old_rails/static.rb +++ /dev/null @@ -1,59 +0,0 @@ -# -*- encoding: binary -*- -# :enddoc: -# This code is based on the original Rails handler in Mongrel -# Copyright (c) 2005 Zed A. Shaw -# Copyright (c) 2009 Eric Wong -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv3 - -# Static file handler for Rails < 2.3. This handler is only provided -# as a convenience for developers. Performance-minded deployments should -# use nginx (or similar) for serving static files. -# -# This supports page caching directly and will try to resolve a -# request in the following order: -# -# * If the requested exact PATH_INFO exists as a file then serve it. -# * If it exists at PATH_INFO+rest_operator+".html" exists -# then serve that. -# -# This means that if you are using page caching it will actually work -# with Unicorn and you should see a decent speed boost (but not as -# fast as if you use a static server like nginx). -class Unicorn::App::OldRails::Static < Struct.new(:app, :root, :file_server) - FILE_METHODS = { 'GET' => true, 'HEAD' => true } - - # avoid allocating new strings for hash lookups - REQUEST_METHOD = 'REQUEST_METHOD' - REQUEST_URI = 'REQUEST_URI' - PATH_INFO = 'PATH_INFO' - - def initialize(app) - self.app = app - self.root = "#{::RAILS_ROOT}/public" - self.file_server = ::Rack::File.new(root) - end - - def call(env) - # short circuit this ASAP if serving non-file methods - FILE_METHODS.include?(env[REQUEST_METHOD]) or return app.call(env) - - # first try the path as-is - path_info = env[PATH_INFO].chomp("/") - if File.file?("#{root}/#{::Rack::Utils.unescape(path_info)}") - # File exists as-is so serve it up - env[PATH_INFO] = path_info - return file_server.call(env) - end - - # then try the cached version: - path_info << ActionController::Base.page_cache_extension - - if File.file?("#{root}/#{::Rack::Utils.unescape(path_info)}") - env[PATH_INFO] = path_info - return file_server.call(env) - end - - app.call(env) # call OldRails - end -end if defined?(Unicorn::App::OldRails) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/cgi_wrapper.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/cgi_wrapper.rb deleted file mode 100644 index d9b7fe5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/cgi_wrapper.rb +++ /dev/null @@ -1,147 +0,0 @@ -# -*- encoding: binary -*- - -# :enddoc: -# This code is based on the original CGIWrapper from Mongrel -# Copyright (c) 2005 Zed A. Shaw -# Copyright (c) 2009 Eric Wong -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) -# -# Additional work donated by contributors. See CONTRIBUTORS for more info. - -require 'cgi' - -module Unicorn; end - -# The beginning of a complete wrapper around Unicorn's internal HTTP -# processing system but maintaining the original Ruby CGI module. Use -# this only as a crutch to get existing CGI based systems working. It -# should handle everything, but please notify us if you see special -# warnings. This work is still very alpha so we need testers to help -# work out the various corner cases. -class Unicorn::CGIWrapper < ::CGI - undef_method :env_table - attr_reader :env_table - attr_reader :body - - # these are stripped out of any keys passed to CGIWrapper.header function - NPH = 'nph'.freeze # Completely ignored, Unicorn outputs the date regardless - CONNECTION = 'connection'.freeze # Completely ignored. Why is CGI doing this? - CHARSET = 'charset'.freeze # this gets appended to Content-Type - COOKIE = 'cookie'.freeze # maps (Hash,Array,String) to "Set-Cookie" headers - STATUS = 'status'.freeze # stored as @status - Status = 'Status'.freeze # code + human-readable text, Rails sets this - - # some of these are common strings, but this is the only module - # using them and the reason they're not in Unicorn::Const - SET_COOKIE = 'Set-Cookie'.freeze - CONTENT_TYPE = 'Content-Type'.freeze - CONTENT_LENGTH = 'Content-Length'.freeze # this is NOT Const::CONTENT_LENGTH - RACK_INPUT = 'rack.input'.freeze - RACK_ERRORS = 'rack.errors'.freeze - - # this maps CGI header names to HTTP header names - HEADER_MAP = { - 'status' => Status, - 'type' => CONTENT_TYPE, - 'server' => 'Server'.freeze, - 'language' => 'Content-Language'.freeze, - 'expires' => 'Expires'.freeze, - 'length' => CONTENT_LENGTH, - } - - # Takes an a Rackable environment, plus any additional CGI.new - # arguments These are used internally to create a wrapper around the - # real CGI while maintaining Rack/Unicorn's view of the world. This - # this will NOT deal well with large responses that take up a lot of - # memory, but neither does the CGI nor the original CGIWrapper from - # Mongrel... - def initialize(rack_env, *args) - @env_table = rack_env - @status = nil - @head = {} - @headv = Hash.new { |hash,key| hash[key] = [] } - @body = StringIO.new("") - super(*args) - end - - # finalizes the response in a way Rack applications would expect - def rack_response - # @head[CONTENT_LENGTH] ||= @body.size - @headv[SET_COOKIE].concat(@output_cookies) if @output_cookies - @headv.each_pair do |key,value| - @head[key] ||= value.join("\n") unless value.empty? - end - - # Capitalized "Status:", with human-readable status code (e.g. "200 OK") - @status ||= @head.delete(Status) - - [ @status || 500, @head, [ @body.string ] ] - end - - # The header is typically called to send back the header. In our case we - # collect it into a hash for later usage. This can be called multiple - # times to set different cookies. - def header(options = "text/html") - # if they pass in a string then just write the Content-Type - if String === options - @head[CONTENT_TYPE] ||= options - else - HEADER_MAP.each_pair do |from, to| - from = options.delete(from) or next - @head[to] = from.to_s - end - - @head[CONTENT_TYPE] ||= "text/html" - if charset = options.delete(CHARSET) - @head[CONTENT_TYPE] << "; charset=#{charset}" - end - - # lots of ways to set cookies - if cookie = options.delete(COOKIE) - set_cookies = @headv[SET_COOKIE] - case cookie - when Array - cookie.each { |c| set_cookies << c.to_s } - when Hash - cookie.each_value { |c| set_cookies << c.to_s } - else - set_cookies << cookie.to_s - end - end - @status ||= options.delete(STATUS) # all lower-case - - # drop the keys we don't want anymore - options.delete(NPH) - options.delete(CONNECTION) - - # finally, set the rest of the headers as-is, allowing duplicates - options.each_pair { |k,v| @headv[k] << v } - end - - # doing this fakes out the cgi library to think the headers are empty - # we then do the real headers in the out function call later - "" - end - - # The dumb thing is people can call header or this or both and in - # any order. So, we just reuse header and then finalize the - # HttpResponse the right way. This will have no effect if called - # the second time if the first "outputted" anything. - def out(options = "text/html") - header(options) - @body.size == 0 or return - @body << yield if block_given? - end - - # Used to wrap the normal stdinput variable used inside CGI. - def stdinput - @env_table[RACK_INPUT] - end - - # return a pointer to the StringIO body since it's STDOUT-like - def stdoutput - @body - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/configurator.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/configurator.rb deleted file mode 100644 index 9406223..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/configurator.rb +++ /dev/null @@ -1,679 +0,0 @@ -# -*- encoding: binary -*- -require 'logger' -require 'unicorn/ssl_configurator' - -# Implements a simple DSL for configuring a \Unicorn server. -# -# See http://unicorn.bogomips.org/examples/unicorn.conf.rb and -# http://unicorn.bogomips.org/examples/unicorn.conf.minimal.rb -# example configuration files. An example config file for use with -# nginx is also available at -# http://unicorn.bogomips.org/examples/nginx.conf -# -# See the link:/TUNING.html document for more information on tuning unicorn. -class Unicorn::Configurator - include Unicorn - include Unicorn::SSLConfigurator - - # :stopdoc: - attr_accessor :set, :config_file, :after_reload - - # used to stash stuff for deferred processing of cli options in - # config.ru after "working_directory" is bound. Do not rely on - # this being around later on... - RACKUP = { - :daemonize => false, - :host => Unicorn::Const::DEFAULT_HOST, - :port => Unicorn::Const::DEFAULT_PORT, - :set_listener => false, - :options => { :listeners => [] } - } - - # Default settings for Unicorn - DEFAULTS = { - :timeout => 60, - :logger => Logger.new($stderr), - :worker_processes => 1, - :after_fork => lambda { |server, worker| - server.logger.info("worker=#{worker.nr} spawned pid=#{$$}") - }, - :before_fork => lambda { |server, worker| - server.logger.info("worker=#{worker.nr} spawning...") - }, - :before_exec => lambda { |server| - server.logger.info("forked child re-executing...") - }, - :pid => nil, - :preload_app => false, - :check_client_connection => false, - :rewindable_input => true, # for Rack 2.x: (Rack::VERSION[0] <= 1), - :client_body_buffer_size => Unicorn::Const::MAX_BODY, - :trust_x_forwarded => true, - } - #:startdoc: - - def initialize(defaults = {}) #:nodoc: - self.set = Hash.new(:unset) - @use_defaults = defaults.delete(:use_defaults) - self.config_file = defaults.delete(:config_file) - - # after_reload is only used by unicorn_rails, unsupported otherwise - self.after_reload = defaults.delete(:after_reload) - - set.merge!(DEFAULTS) if @use_defaults - defaults.each { |key, value| self.__send__(key, value) } - Hash === set[:listener_opts] or - set[:listener_opts] = Hash.new { |hash,key| hash[key] = {} } - Array === set[:listeners] or set[:listeners] = [] - reload(false) - end - - def reload(merge_defaults = true) #:nodoc: - if merge_defaults && @use_defaults - set.merge!(DEFAULTS) if @use_defaults - end - instance_eval(File.read(config_file), config_file) if config_file - - parse_rackup_file - - RACKUP[:set_listener] and - set[:listeners] << "#{RACKUP[:host]}:#{RACKUP[:port]}" - - # unicorn_rails creates dirs here after working_directory is bound - after_reload.call if after_reload - - # working_directory binds immediately (easier error checking that way), - # now ensure any paths we changed are correctly set. - [ :pid, :stderr_path, :stdout_path ].each do |var| - String === (path = set[var]) or next - path = File.expand_path(path) - File.writable?(path) || File.writable?(File.dirname(path)) or \ - raise ArgumentError, "directory for #{var}=#{path} not writable" - end - end - - def commit!(server, options = {}) #:nodoc: - skip = options[:skip] || [] - if ready_pipe = RACKUP.delete(:ready_pipe) - server.ready_pipe = ready_pipe - end - if set[:check_client_connection] - set[:listeners].each do |address| - if set[:listener_opts][address][:tcp_nopush] == true - raise ArgumentError, - "check_client_connection is incompatible with tcp_nopush:true" - end - end - end - set.each do |key, value| - value == :unset and next - skip.include?(key) and next - server.__send__("#{key}=", value) - end - end - - def [](key) # :nodoc: - set[key] - end - - # sets object to the +obj+ Logger-like object. The new Logger-like - # object must respond to the following methods: - # * debug - # * info - # * warn - # * error - # * fatal - # The default Logger will log its output to the path specified - # by +stderr_path+. If you're running Unicorn daemonized, then - # you must specify a path to prevent error messages from going - # to /dev/null. - def logger(obj) - %w(debug info warn error fatal).each do |m| - obj.respond_to?(m) and next - raise ArgumentError, "logger=#{obj} does not respond to method=#{m}" - end - - set[:logger] = obj - end - - # sets after_fork hook to a given block. This block will be called by - # the worker after forking. The following is an example hook which adds - # a per-process listener to every worker: - # - # after_fork do |server,worker| - # # per-process listener ports for debugging/admin: - # addr = "127.0.0.1:#{9293 + worker.nr}" - # - # # the negative :tries parameter indicates we will retry forever - # # waiting on the existing process to exit with a 5 second :delay - # # Existing options for Unicorn::Configurator#listen such as - # # :backlog, :rcvbuf, :sndbuf are available here as well. - # server.listen(addr, :tries => -1, :delay => 5, :backlog => 128) - # end - def after_fork(*args, &block) - set_hook(:after_fork, block_given? ? block : args[0]) - end - - # sets before_fork got be a given Proc object. This Proc - # object will be called by the master process before forking - # each worker. - def before_fork(*args, &block) - set_hook(:before_fork, block_given? ? block : args[0]) - end - - # sets the before_exec hook to a given Proc object. This - # Proc object will be called by the master process right - # before exec()-ing the new unicorn binary. This is useful - # for freeing certain OS resources that you do NOT wish to - # share with the reexeced child process. - # There is no corresponding after_exec hook (for obvious reasons). - def before_exec(*args, &block) - set_hook(:before_exec, block_given? ? block : args[0], 1) - end - - # sets the timeout of worker processes to +seconds+. Workers - # handling the request/app.call/response cycle taking longer than - # this time period will be forcibly killed (via SIGKILL). This - # timeout is enforced by the master process itself and not subject - # to the scheduling limitations by the worker process. Due the - # low-complexity, low-overhead implementation, timeouts of less - # than 3.0 seconds can be considered inaccurate and unsafe. - # - # For running Unicorn behind nginx, it is recommended to set - # "fail_timeout=0" for in your nginx configuration like this - # to have nginx always retry backends that may have had workers - # SIGKILL-ed due to timeouts. - # - # # See http://wiki.nginx.org/NginxHttpUpstreamModule for more details - # # on nginx upstream configuration: - # upstream unicorn_backend { - # # for UNIX domain socket setups: - # server unix:/path/to/.unicorn.sock fail_timeout=0; - # - # # for TCP setups - # server 192.168.0.7:8080 fail_timeout=0; - # server 192.168.0.8:8080 fail_timeout=0; - # server 192.168.0.9:8080 fail_timeout=0; - # } - def timeout(seconds) - set_int(:timeout, seconds, 3) - # POSIX says 31 days is the smallest allowed maximum timeout for select() - max = 30 * 60 * 60 * 24 - set[:timeout] = seconds > max ? max : seconds - end - - # sets the current number of worker_processes to +nr+. Each worker - # process will serve exactly one client at a time. You can - # increment or decrement this value at runtime by sending SIGTTIN - # or SIGTTOU respectively to the master process without reloading - # the rest of your Unicorn configuration. See the SIGNALS document - # for more information. - def worker_processes(nr) - set_int(:worker_processes, nr, 1) - end - - # sets listeners to the given +addresses+, replacing or augmenting the - # current set. This is for the global listener pool shared by all - # worker processes. For per-worker listeners, see the after_fork example - # This is for internal API use only, do not use it in your Unicorn - # config file. Use listen instead. - def listeners(addresses) # :nodoc: - Array === addresses or addresses = Array(addresses) - addresses.map! { |addr| expand_addr(addr) } - set[:listeners] = addresses - end - - # Adds an +address+ to the existing listener set. May be specified more - # than once. +address+ may be an Integer port number for a TCP port, an - # "IP_ADDRESS:PORT" for TCP listeners or a pathname for UNIX domain sockets. - # - # listen 3000 # listen to port 3000 on all TCP interfaces - # listen "127.0.0.1:3000" # listen to port 3000 on the loopback interface - # listen "/path/to/.unicorn.sock" # listen on the given Unix domain socket - # listen "[::1]:3000" # listen to port 3000 on the IPv6 loopback interface - # - # When using Unix domain sockets, be sure: - # 1) the path matches the one used by nginx - # 2) uses the same filesystem namespace as the nginx process - # For systemd users using PrivateTmp=true (for either nginx or unicorn), - # this means Unix domain sockets must not be placed in /tmp - # - # The following options may be specified (but are generally not needed): - # - # [:backlog => number of clients] - # - # This is the backlog of the listen() syscall. - # - # Some operating systems allow negative values here to specify the - # maximum allowable value. In most cases, this number is only - # recommendation and there are other OS-specific tunables and - # variables that can affect this number. See the listen(2) - # syscall documentation of your OS for the exact semantics of - # this. - # - # If you are running unicorn on multiple machines, lowering this number - # can help your load balancer detect when a machine is overloaded - # and give requests to a different machine. - # - # Default: 1024 - # - # [:rcvbuf => bytes, :sndbuf => bytes] - # - # Maximum receive and send buffer sizes (in bytes) of sockets. - # - # These correspond to the SO_RCVBUF and SO_SNDBUF settings which - # can be set via the setsockopt(2) syscall. Some kernels - # (e.g. Linux 2.4+) have intelligent auto-tuning mechanisms and - # there is no need (and it is sometimes detrimental) to specify them. - # - # See the socket API documentation of your operating system - # to determine the exact semantics of these settings and - # other operating system-specific knobs where they can be - # specified. - # - # Defaults: operating system defaults - # - # [:tcp_nodelay => true or false] - # - # Disables Nagle's algorithm on TCP sockets if +true+. - # - # Setting this to +true+ can make streaming responses in Rails 3.1 - # appear more quickly at the cost of slightly higher bandwidth usage. - # The effect of this option is most visible if nginx is not used, - # but nginx remains highly recommended with \Unicorn. - # - # This has no effect on UNIX sockets. - # - # Default: +true+ (Nagle's algorithm disabled) in \Unicorn, - # +true+ in Rainbows! This defaulted to +false+ in \Unicorn - # 3.x - # - # [:tcp_nopush => true or false] - # - # Enables/disables TCP_CORK in Linux or TCP_NOPUSH in FreeBSD - # - # This prevents partial TCP frames from being sent out and reduces - # wakeups in nginx if it is on a different machine. Since \Unicorn - # is only designed for applications that send the response body - # quickly without keepalive, sockets will always be flushed on close - # to prevent delays. - # - # This has no effect on UNIX sockets. - # - # Default: +false+ - # This defaulted to +true+ in \Unicorn 3.4 - 3.7 - # - # [:ipv6only => true or false] - # - # This option makes IPv6-capable TCP listeners IPv6-only and unable - # to receive IPv4 queries on dual-stack systems. A separate IPv4-only - # listener is required if this is true. - # - # This option is only available for Ruby 1.9.2 and later. - # - # Enabling this option for the IPv6-only listener and having a - # separate IPv4 listener is recommended if you wish to support IPv6 - # on the same TCP port. Otherwise, the value of \env[\"REMOTE_ADDR\"] - # will appear as an ugly IPv4-mapped-IPv6 address for IPv4 clients - # (e.g ":ffff:10.0.0.1" instead of just "10.0.0.1"). - # - # Default: Operating-system dependent - # - # [:reuseport => true or false] - # - # This enables multiple, independently-started unicorn instances to - # bind to the same port (as long as all the processes enable this). - # - # This option must be used when unicorn first binds the listen socket. - # It cannot be enabled when a socket is inherited via SIGUSR2 - # (but it will remain on if inherited), and it cannot be enabled - # directly via SIGHUP. - # - # Note: there is a chance of connections being dropped if - # one of the unicorn instances is stopped while using this. - # - # This is supported on *BSD systems and Linux 3.9 or later. - # - # ref: https://lwn.net/Articles/542629/ - # - # Default: false (unset) - # - # [:tries => Integer] - # - # Times to retry binding a socket if it is already in use - # - # A negative number indicates we will retry indefinitely, this is - # useful for migrations and upgrades when individual workers - # are binding to different ports. - # - # Default: 5 - # - # [:delay => seconds] - # - # Seconds to wait between successive +tries+ - # - # Default: 0.5 seconds - # - # [:umask => mode] - # - # Sets the file mode creation mask for UNIX sockets. If specified, - # this is usually in octal notation. - # - # Typically UNIX domain sockets are created with more liberal - # file permissions than the rest of the application. By default, - # we create UNIX domain sockets to be readable and writable by - # all local users to give them the same accessibility as - # locally-bound TCP listeners. - # - # This has no effect on TCP listeners. - # - # Default: 0000 (world-read/writable) - # - # [:tcp_defer_accept => Integer] - # - # Defer accept() until data is ready (Linux-only) - # - # For Linux 2.6.32 and later, this is the number of retransmits to - # defer an accept() for if no data arrives, but the client will - # eventually be accepted after the specified number of retransmits - # regardless of whether data is ready. - # - # For Linux before 2.6.32, this is a boolean option, and - # accepts are _always_ deferred indefinitely if no data arrives. - # This is similar to :accept_filter => "dataready" - # under FreeBSD. - # - # Specifying +true+ is synonymous for the default value(s) below, - # and +false+ or +nil+ is synonymous for a value of zero. - # - # A value of +1+ is a good optimization for local networks - # and trusted clients. For Rainbows! and Zbatery users, a higher - # value (e.g. +60+) provides more protection against some - # denial-of-service attacks. There is no good reason to ever - # disable this with a +zero+ value when serving HTTP. - # - # Default: 1 retransmit for \Unicorn, 60 for Rainbows! 0.95.0\+ - # - # [:accept_filter => String] - # - # defer accept() until data is ready (FreeBSD-only) - # - # This enables either the "dataready" or (default) "httpready" - # accept() filter under FreeBSD. This is intended as an - # optimization to reduce context switches with common GET/HEAD - # requests. For Rainbows! and Zbatery users, this provides - # some protection against certain denial-of-service attacks, too. - # - # There is no good reason to change from the default. - # - # Default: "httpready" - def listen(address, options = {}) - address = expand_addr(address) - if String === address - [ :umask, :backlog, :sndbuf, :rcvbuf, :tries ].each do |key| - value = options[key] or next - Integer === value or - raise ArgumentError, "not an integer: #{key}=#{value.inspect}" - end - [ :tcp_nodelay, :tcp_nopush, :ipv6only, :reuseport ].each do |key| - (value = options[key]).nil? and next - TrueClass === value || FalseClass === value or - raise ArgumentError, "not boolean: #{key}=#{value.inspect}" - end - unless (value = options[:delay]).nil? - Numeric === value or - raise ArgumentError, "not numeric: delay=#{value.inspect}" - end - set[:listener_opts][address].merge!(options) - end - - set[:listeners] << address - end - - # sets the +path+ for the PID file of the unicorn master process - def pid(path); set_path(:pid, path); end - - # Enabling this preloads an application before forking worker - # processes. This allows memory savings when using a - # copy-on-write-friendly GC but can cause bad things to happen when - # resources like sockets are opened at load time by the master - # process and shared by multiple children. People enabling this are - # highly encouraged to look at the before_fork/after_fork hooks to - # properly close/reopen sockets. Files opened for logging do not - # have to be reopened as (unbuffered-in-userspace) files opened with - # the File::APPEND flag are written to atomically on UNIX. - # - # In addition to reloading the unicorn-specific config settings, - # SIGHUP will reload application code in the working - # directory/symlink when workers are gracefully restarted when - # preload_app=false (the default). As reloading the application - # sometimes requires RubyGems updates, +Gem.refresh+ is always - # called before the application is loaded (for RubyGems users). - # - # During deployments, care should _always_ be taken to ensure your - # applications are properly deployed and running. Using - # preload_app=false (the default) means you _must_ check if - # your application is responding properly after a deployment. - # Improperly deployed applications can go into a spawn loop - # if the application fails to load. While your children are - # in a spawn loop, it is is possible to fix an application - # by properly deploying all required code and dependencies. - # Using preload_app=true means any application load error will - # cause the master process to exit with an error. - - def preload_app(bool) - set_bool(:preload_app, bool) - end - - # Toggles making \env[\"rack.input\"] rewindable. - # Disabling rewindability can improve performance by lowering - # I/O and memory usage for applications that accept uploads. - # Keep in mind that the Rack 1.x spec requires - # \env[\"rack.input\"] to be rewindable, so this allows - # intentionally violating the current Rack 1.x spec. - # - # +rewindable_input+ defaults to +true+ when used with Rack 1.x for - # Rack conformance. When Rack 2.x is finalized, this will most - # likely default to +false+ while still conforming to the newer - # (less demanding) spec. - def rewindable_input(bool) - set_bool(:rewindable_input, bool) - end - - # The maximum size (in +bytes+) to buffer in memory before - # resorting to a temporary file. Default is 112 kilobytes. - # This option has no effect if "rewindable_input" is set to - # +false+. - def client_body_buffer_size(bytes) - set_int(:client_body_buffer_size, bytes, 0) - end - - # When enabled, unicorn will check the client connection by writing - # the beginning of the HTTP headers before calling the application. - # - # This will prevent calling the application for clients who have - # disconnected while their connection was queued. - # - # This only affects clients connecting over Unix domain sockets - # and TCP via loopback (127.*.*.*). It is unlikely to detect - # disconnects if the client is on a remote host (even on a fast LAN). - # - # This option cannot be used in conjunction with :tcp_nopush. - def check_client_connection(bool) - set_bool(:check_client_connection, bool) - end - - # Allow redirecting $stderr to a given path. Unlike doing this from - # the shell, this allows the unicorn process to know the path its - # writing to and rotate the file if it is used for logging. The - # file will be opened with the File::APPEND flag and writes - # synchronized to the kernel (but not necessarily to _disk_) so - # multiple processes can safely append to it. - # - # If you are daemonizing and using the default +logger+, it is important - # to specify this as errors will otherwise be lost to /dev/null. - # Some applications/libraries may also triggering warnings that go to - # stderr, and they will end up here. - def stderr_path(path) - set_path(:stderr_path, path) - end - - # Same as stderr_path, except for $stdout. Not many Rack applications - # write to $stdout, but any that do will have their output written here. - # It is safe to point this to the same location a stderr_path. - # Like stderr_path, this defaults to /dev/null when daemonized. - def stdout_path(path) - set_path(:stdout_path, path) - end - - # sets the working directory for Unicorn. This ensures SIGUSR2 will - # start a new instance of Unicorn in this directory. This may be - # a symlink, a common scenario for Capistrano users. Unlike - # all other Unicorn configuration directives, this binds immediately - # for error checking and cannot be undone by unsetting it in the - # configuration file and reloading. - def working_directory(path) - # just let chdir raise errors - path = File.expand_path(path) - if config_file && - config_file[0] != ?/ && - ! File.readable?("#{path}/#{config_file}") - raise ArgumentError, - "config_file=#{config_file} would not be accessible in" \ - " working_directory=#{path}" - end - Dir.chdir(path) - Unicorn::HttpServer::START_CTX[:cwd] = ENV["PWD"] = path - end - - # Runs worker processes as the specified +user+ and +group+. - # The master process always stays running as the user who started it. - # This switch will occur after calling the after_fork hook, and only - # if the Worker#user method is not called in the after_fork hook - # +group+ is optional and will not change if unspecified. - def user(user, group = nil) - # raises ArgumentError on invalid user/group - Etc.getpwnam(user) - Etc.getgrnam(group) if group - set[:user] = [ user, group ] - end - - # Sets whether or not the parser will trust X-Forwarded-Proto and - # X-Forwarded-SSL headers and set "rack.url_scheme" to "https" accordingly. - # Rainbows!/Zbatery installations facing untrusted clients directly - # should set this to +false+. This is +true+ by default as Unicorn - # is designed to only sit behind trusted nginx proxies. - # - # This has never been publically documented and is subject to removal - # in future releases. - def trust_x_forwarded(bool) # :nodoc: - set_bool(:trust_x_forwarded, bool) - end - - # expands "unix:path/to/foo" to a socket relative to the current path - # expands pathnames of sockets if relative to "~" or "~username" - # expands "*:port and ":port" to "0.0.0.0:port" - def expand_addr(address) #:nodoc: - return "0.0.0.0:#{address}" if Integer === address - return address unless String === address - - case address - when %r{\Aunix:(.*)\z} - File.expand_path($1) - when %r{\A~} - File.expand_path(address) - when %r{\A(?:\*:)?(\d+)\z} - "0.0.0.0:#$1" - when %r{\A\[([a-fA-F0-9:]+)\]\z}, %r/\A((?:\d+\.){3}\d+)\z/ - canonicalize_tcp($1, 80) - when %r{\A\[([a-fA-F0-9:]+)\]:(\d+)\z}, %r{\A(.*):(\d+)\z} - canonicalize_tcp($1, $2.to_i) - else - address - end - end - -private - def set_int(var, n, min) #:nodoc: - Integer === n or raise ArgumentError, "not an integer: #{var}=#{n.inspect}" - n >= min or raise ArgumentError, "too low (< #{min}): #{var}=#{n.inspect}" - set[var] = n - end - - def canonicalize_tcp(addr, port) - packed = Socket.pack_sockaddr_in(port, addr) - port, addr = Socket.unpack_sockaddr_in(packed) - /:/ =~ addr ? "[#{addr}]:#{port}" : "#{addr}:#{port}" - end - - def set_path(var, path) #:nodoc: - case path - when NilClass, String - set[var] = path - else - raise ArgumentError - end - end - - def check_bool(var, bool) # :nodoc: - case bool - when true, false - return bool - end - raise ArgumentError, "#{var}=#{bool.inspect} not a boolean" - end - - def set_bool(var, bool) #:nodoc: - set[var] = check_bool(var, bool) - end - - def set_hook(var, my_proc, req_arity = 2) #:nodoc: - case my_proc - when Proc - arity = my_proc.arity - (arity == req_arity) or \ - raise ArgumentError, - "#{var}=#{my_proc.inspect} has invalid arity: " \ - "#{arity} (need #{req_arity})" - when NilClass - my_proc = DEFAULTS[var] - else - raise ArgumentError, "invalid type: #{var}=#{my_proc.inspect}" - end - set[var] = my_proc - end - - # this is called _after_ working_directory is bound. This only - # parses the embedded switches in .ru files - # (for "rackup" compatibility) - def parse_rackup_file # :nodoc: - ru = RACKUP[:file] or return # we only return here in unit tests - - # :rails means use (old) Rails autodetect - if ru == :rails - File.readable?('config.ru') or return - ru = 'config.ru' - end - - File.readable?(ru) or - raise ArgumentError, "rackup file (#{ru}) not readable" - - # it could be a .rb file, too, we don't parse those manually - ru =~ /\.ru\z/ or return - - /^#\\(.*)/ =~ File.read(ru) or return - RACKUP[:optparse].parse!($1.split(/\s+/)) - - if RACKUP[:daemonize] - # unicorn_rails wants a default pid path, (not plain 'unicorn') - if after_reload - spid = set[:pid] - pid('tmp/pids/unicorn.pid') if spid.nil? || spid == :unset - end - unless RACKUP[:daemonized] - Unicorn::Launcher.daemonize!(RACKUP[:options]) - RACKUP[:ready_pipe] = RACKUP[:options].delete(:ready_pipe) - end - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/const.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/const.rb deleted file mode 100644 index 51d7394..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/const.rb +++ /dev/null @@ -1,44 +0,0 @@ -# -*- encoding: binary -*- - -# :enddoc: -# Frequently used constants when constructing requests or responses. -# Many times the constant just refers to a string with the same -# contents. Using these constants gave about a 3% to 10% performance -# improvement over using the strings directly. Symbols did not really -# improve things much compared to constants. -module Unicorn::Const - # default TCP listen host address (0.0.0.0, all interfaces) - DEFAULT_HOST = "0.0.0.0" - - # default TCP listen port (8080) - DEFAULT_PORT = 8080 - - # default TCP listen address and port (0.0.0.0:8080) - DEFAULT_LISTEN = "#{DEFAULT_HOST}:#{DEFAULT_PORT}" - - # The basic request body size we'll try to read at once (16 kilobytes). - CHUNK_SIZE = 16 * 1024 - - # Maximum request body size before it is moved out of memory and into a - # temporary file for reading (112 kilobytes). This is the default - # value of client_body_buffer_size. - MAX_BODY = 1024 * 112 - - # :stopdoc: - # common errors we'll send back - # (N.B. these are not used by unicorn, but we won't drop them until - # unicorn 5.x to avoid breaking Rainbows!). - ERROR_400_RESPONSE = "HTTP/1.1 400 Bad Request\r\n\r\n" - ERROR_414_RESPONSE = "HTTP/1.1 414 Request-URI Too Long\r\n\r\n" - ERROR_413_RESPONSE = "HTTP/1.1 413 Request Entity Too Large\r\n\r\n" - ERROR_500_RESPONSE = "HTTP/1.1 500 Internal Server Error\r\n\r\n" - - EXPECT_100_RESPONSE = "HTTP/1.1 100 Continue\r\n\r\n" - EXPECT_100_RESPONSE_SUFFIXED = "100 Continue\r\n\r\nHTTP/1.1 " - - HTTP_RESPONSE_START = ['HTTP', '/1.1 '] - HTTP_EXPECT = "HTTP_EXPECT" - - # :startdoc: -end -require 'unicorn/version' diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_request.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_request.rb deleted file mode 100644 index 6b20431..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_request.rb +++ /dev/null @@ -1,122 +0,0 @@ -# -*- encoding: binary -*- -# :enddoc: -# no stable API here -require 'unicorn_http' - -# TODO: remove redundant names -Unicorn.const_set(:HttpRequest, Unicorn::HttpParser) -class Unicorn::HttpParser - - # default parameters we merge into the request env for Rack handlers - DEFAULTS = { - "rack.errors" => $stderr, - "rack.multiprocess" => true, - "rack.multithread" => false, - "rack.run_once" => false, - "rack.version" => [1, 1], - "SCRIPT_NAME" => "", - - # this is not in the Rack spec, but some apps may rely on it - "SERVER_SOFTWARE" => "Unicorn #{Unicorn::Const::UNICORN_VERSION}" - } - - NULL_IO = StringIO.new("") - - attr_accessor :response_start_sent - - # :stopdoc: - # A frozen format for this is about 15% faster - REMOTE_ADDR = 'REMOTE_ADDR'.freeze - RACK_INPUT = 'rack.input'.freeze - @@input_class = Unicorn::TeeInput - @@check_client_connection = false - - def self.input_class - @@input_class - end - - def self.input_class=(klass) - @@input_class = klass - end - - def self.check_client_connection - @@check_client_connection - end - - def self.check_client_connection=(bool) - @@check_client_connection = bool - end - - # :startdoc: - - # Does the majority of the IO processing. It has been written in - # Ruby using about 8 different IO processing strategies. - # - # It is currently carefully constructed to make sure that it gets - # the best possible performance for the common case: GET requests - # that are fully complete after a single read(2) - # - # Anyone who thinks they can make it faster is more than welcome to - # take a crack at it. - # - # returns an environment hash suitable for Rack if successful - # This does minimal exception trapping and it is up to the caller - # to handle any socket errors (e.g. user aborted upload). - def read(socket) - clear - e = env - - # From http://www.ietf.org/rfc/rfc3875: - # "Script authors should be aware that the REMOTE_ADDR and - # REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9) - # may not identify the ultimate source of the request. They - # identify the client for the immediate request to the server; - # that client may be a proxy, gateway, or other intermediary - # acting on behalf of the actual source client." - e[REMOTE_ADDR] = socket.kgio_addr - - # short circuit the common case with small GET requests first - socket.kgio_read!(16384, buf) - if parse.nil? - # Parser is not done, queue up more data to read and continue parsing - # an Exception thrown from the parser will throw us out of the loop - false until add_parse(socket.kgio_read!(16384)) - end - - # detect if the socket is valid by writing a partial response: - if @@check_client_connection && headers? - @response_start_sent = true - Unicorn::Const::HTTP_RESPONSE_START.each { |c| socket.write(c) } - end - - e[RACK_INPUT] = 0 == content_length ? - NULL_IO : @@input_class.new(socket, self) - hijack_setup(e, socket) - e.merge!(DEFAULTS) - end - - # Rack 1.5.0 (protocol version 1.2) adds hijack request support - if ((Rack::VERSION[0] << 8) | Rack::VERSION[1]) >= 0x0102 - DEFAULTS["rack.hijack?"] = true - DEFAULTS["rack.version"] = [1, 2] - - RACK_HIJACK = "rack.hijack".freeze - RACK_HIJACK_IO = "rack.hijack_io".freeze - - def hijacked? - env.include?(RACK_HIJACK_IO) - end - - def hijack_setup(e, socket) - e[RACK_HIJACK] = proc { e[RACK_HIJACK_IO] = socket } - end - else - # old Rack, do nothing. - def hijack_setup(e, _) - end - - def hijacked? - false - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_response.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_response.rb deleted file mode 100644 index 083951c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_response.rb +++ /dev/null @@ -1,75 +0,0 @@ -# -*- encoding: binary -*- -# :enddoc: -# Writes a Rack response to your client using the HTTP/1.1 specification. -# You use it by simply doing: -# -# status, headers, body = rack_app.call(env) -# http_response_write(socket, status, headers, body) -# -# Most header correctness (including Content-Length and Content-Type) -# is the job of Rack, with the exception of the "Date" and "Status" header. -module Unicorn::HttpResponse - - # Every standard HTTP code mapped to the appropriate message. - CODES = Rack::Utils::HTTP_STATUS_CODES.inject({}) { |hash,(code,msg)| - hash[code] = "#{code} #{msg}" - hash - } - CRLF = "\r\n" - - def err_response(code, response_start_sent) - "#{response_start_sent ? '' : 'HTTP/1.1 '}#{CODES[code]}\r\n\r\n" - end - - # writes the rack_response to socket as an HTTP response - def http_response_write(socket, status, headers, body, - response_start_sent=false) - status = CODES[status.to_i] || status - hijack = nil - - http_response_start = response_start_sent ? '' : 'HTTP/1.1 ' - if headers - buf = "#{http_response_start}#{status}\r\n" \ - "Date: #{httpdate}\r\n" \ - "Status: #{status}\r\n" \ - "Connection: close\r\n" - headers.each do |key, value| - case key - when %r{\A(?:Date\z|Connection\z)}i - next - when "rack.hijack" - # this was an illegal key in Rack < 1.5, so it should be - # OK to silently discard it for those older versions - hijack = hijack_prepare(value) - else - if value =~ /\n/ - # avoiding blank, key-only cookies with /\n+/ - buf << value.split(/\n+/).map! { |v| "#{key}: #{v}\r\n" }.join - else - buf << "#{key}: #{value}\r\n" - end - end - end - socket.write(buf << CRLF) - end - - if hijack - body = nil # ensure we do not close body - hijack.call(socket) - else - body.each { |chunk| socket.write(chunk) } - end - ensure - body.respond_to?(:close) and body.close - end - - # Rack 1.5.0 (protocol version 1.2) adds response hijacking support - if ((Rack::VERSION[0] << 8) | Rack::VERSION[1]) >= 0x0102 - def hijack_prepare(value) - value - end - else - def hijack_prepare(_) - end - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_server.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_server.rb deleted file mode 100644 index a0ca302..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/http_server.rb +++ /dev/null @@ -1,813 +0,0 @@ -# -*- encoding: binary -*- -require "unicorn/ssl_server" - -# This is the process manager of Unicorn. This manages worker -# processes which in turn handle the I/O and application process. -# Listener sockets are started in the master process and shared with -# forked worker children. -# -# Users do not need to know the internals of this class, but reading the -# {source}[http://bogomips.org/unicorn.git/tree/lib/unicorn/http_server.rb] -# is education for programmers wishing to learn how \Unicorn works. -# See Unicorn::Configurator for information on how to configure \Unicorn. -class Unicorn::HttpServer - # :stopdoc: - attr_accessor :app, :request, :timeout, :worker_processes, - :before_fork, :after_fork, :before_exec, - :listener_opts, :preload_app, - :reexec_pid, :orig_app, :init_listeners, - :master_pid, :config, :ready_pipe, :user - - attr_reader :pid, :logger - include Unicorn::SocketHelper - include Unicorn::HttpResponse - include Unicorn::SSLServer - - # backwards compatibility with 1.x - Worker = Unicorn::Worker - - # all bound listener sockets - LISTENERS = [] - - # listeners we have yet to bind - NEW_LISTENERS = [] - - # This hash maps PIDs to Workers - WORKERS = {} - - # We use SELF_PIPE differently in the master and worker processes: - # - # * The master process never closes or reinitializes this once - # initialized. Signal handlers in the master process will write to - # it to wake up the master from IO.select in exactly the same manner - # djb describes in http://cr.yp.to/docs/selfpipe.html - # - # * The workers immediately close the pipe they inherit. See the - # Unicorn::Worker class for the pipe workers use. - SELF_PIPE = [] - - # signal queue used for self-piping - SIG_QUEUE = [] - - # list of signals we care about and trap in master. - QUEUE_SIGS = [ :WINCH, :QUIT, :INT, :TERM, :USR1, :USR2, :HUP, :TTIN, :TTOU ] - - # :startdoc: - # We populate this at startup so we can figure out how to reexecute - # and upgrade the currently running instance of Unicorn - # This Hash is considered a stable interface and changing its contents - # will allow you to switch between different installations of Unicorn - # or even different installations of the same applications without - # downtime. Keys of this constant Hash are described as follows: - # - # * 0 - the path to the unicorn/unicorn_rails executable - # * :argv - a deep copy of the ARGV array the executable originally saw - # * :cwd - the working directory of the application, this is where - # you originally started Unicorn. - # - # To change your unicorn executable to a different path without downtime, - # you can set the following in your Unicorn config file, HUP and then - # continue with the traditional USR2 + QUIT upgrade steps: - # - # Unicorn::HttpServer::START_CTX[0] = "/home/bofh/1.9.2/bin/unicorn" - START_CTX = { - :argv => ARGV.map { |arg| arg.dup }, - 0 => $0.dup, - } - # We favor ENV['PWD'] since it is (usually) symlink aware for Capistrano - # and like systems - START_CTX[:cwd] = begin - a = File.stat(pwd = ENV['PWD']) - b = File.stat(Dir.pwd) - a.ino == b.ino && a.dev == b.dev ? pwd : Dir.pwd - rescue - Dir.pwd - end - # :stopdoc: - - # Creates a working server on host:port (strange things happen if - # port isn't a Number). Use HttpServer::run to start the server and - # HttpServer.run.join to join the thread that's processing - # incoming requests on the socket. - def initialize(app, options = {}) - @app = app - @request = Unicorn::HttpRequest.new - self.reexec_pid = 0 - options = options.dup - @ready_pipe = options.delete(:ready_pipe) - @init_listeners = options[:listeners] ? options[:listeners].dup : [] - options[:use_defaults] = true - self.config = Unicorn::Configurator.new(options) - self.listener_opts = {} - - # we try inheriting listeners first, so we bind them later. - # we don't write the pid file until we've bound listeners in case - # unicorn was started twice by mistake. Even though our #pid= method - # checks for stale/existing pid files, race conditions are still - # possible (and difficult/non-portable to avoid) and can be likely - # to clobber the pid if the second start was in quick succession - # after the first, so we rely on the listener binding to fail in - # that case. Some tests (in and outside of this source tree) and - # monitoring tools may also rely on pid files existing before we - # attempt to connect to the listener(s) - config.commit!(self, :skip => [:listeners, :pid]) - self.orig_app = app - end - - # Runs the thing. Returns self so you can run join on it - def start - inherit_listeners! - # this pipe is used to wake us up from select(2) in #join when signals - # are trapped. See trap_deferred. - SELF_PIPE.replace(Unicorn.pipe) - @master_pid = $$ - - # setup signal handlers before writing pid file in case people get - # trigger happy and send signals as soon as the pid file exists. - # Note that signals don't actually get handled until the #join method - QUEUE_SIGS.each { |sig| trap(sig) { SIG_QUEUE << sig; awaken_master } } - trap(:CHLD) { awaken_master } - - # write pid early for Mongrel compatibility if we're not inheriting sockets - # This is needed for compatibility some Monit setups at least. - # This unfortunately has the side effect of clobbering valid PID if - # we upgrade and the upgrade breaks during preload_app==true && build_app! - self.pid = config[:pid] - - build_app! if preload_app - bind_new_listeners! - - spawn_missing_workers - self - end - - # replaces current listener set with +listeners+. This will - # close the socket if it will not exist in the new listener set - def listeners=(listeners) - cur_names, dead_names = [], [] - listener_names.each do |name| - if ?/ == name[0] - # mark unlinked sockets as dead so we can rebind them - (File.socket?(name) ? cur_names : dead_names) << name - else - cur_names << name - end - end - set_names = listener_names(listeners) - dead_names.concat(cur_names - set_names).uniq! - - LISTENERS.delete_if do |io| - if dead_names.include?(sock_name(io)) - IO_PURGATORY.delete_if do |pio| - pio.fileno == io.fileno && (pio.close rescue nil).nil? # true - end - (io.close rescue nil).nil? # true - else - set_server_sockopt(io, listener_opts[sock_name(io)]) - false - end - end - - (set_names - cur_names).each { |addr| listen(addr) } - end - - def stdout_path=(path); redirect_io($stdout, path); end - def stderr_path=(path); redirect_io($stderr, path); end - - def logger=(obj) - Unicorn::HttpRequest::DEFAULTS["rack.logger"] = @logger = obj - end - - def clobber_pid(path) - unlink_pid_safe(@pid) if @pid - if path - fp = begin - tmp = "#{File.dirname(path)}/#{rand}.#$$" - File.open(tmp, File::RDWR|File::CREAT|File::EXCL, 0644) - rescue Errno::EEXIST - retry - end - fp.syswrite("#$$\n") - File.rename(fp.path, path) - fp.close - end - end - - # sets the path for the PID file of the master process - def pid=(path) - if path - if x = valid_pid?(path) - return path if pid && path == pid && x == $$ - if x == reexec_pid && pid =~ /\.oldbin\z/ - logger.warn("will not set pid=#{path} while reexec-ed "\ - "child is running PID:#{x}") - return - end - raise ArgumentError, "Already running on PID:#{x} " \ - "(or pid=#{path} is stale)" - end - end - - # rename the old pid if possible - if @pid && path - begin - File.rename(@pid, path) - rescue Errno::ENOENT, Errno::EXDEV - # a user may have accidentally removed the original, - # obviously cross-FS renames don't work, either. - clobber_pid(path) - end - else - clobber_pid(path) - end - @pid = path - end - - # add a given address to the +listeners+ set, idempotently - # Allows workers to add a private, per-process listener via the - # after_fork hook. Very useful for debugging and testing. - # +:tries+ may be specified as an option for the number of times - # to retry, and +:delay+ may be specified as the time in seconds - # to delay between retries. - # A negative value for +:tries+ indicates the listen will be - # retried indefinitely, this is useful when workers belonging to - # different masters are spawned during a transparent upgrade. - def listen(address, opt = {}.merge(listener_opts[address] || {})) - address = config.expand_addr(address) - return if String === address && listener_names.include?(address) - - delay = opt[:delay] || 0.5 - tries = opt[:tries] || 5 - begin - io = bind_listen(address, opt) - unless Kgio::TCPServer === io || Kgio::UNIXServer === io - prevent_autoclose(io) - io = server_cast(io) - end - logger.info "listening on addr=#{sock_name(io)} fd=#{io.fileno}" - LISTENERS << io - io - rescue Errno::EADDRINUSE => err - logger.error "adding listener failed addr=#{address} (in use)" - raise err if tries == 0 - tries -= 1 - logger.error "retrying in #{delay} seconds " \ - "(#{tries < 0 ? 'infinite' : tries} tries left)" - sleep(delay) - retry - rescue => err - logger.fatal "error adding listener addr=#{address}" - raise err - end - end - - # monitors children and receives signals forever - # (or until a termination signal is sent). This handles signals - # one-at-a-time time and we'll happily drop signals in case somebody - # is signalling us too often. - def join - respawn = true - last_check = Time.now - - proc_name 'master' - logger.info "master process ready" # test_exec.rb relies on this message - if @ready_pipe - begin - @ready_pipe.syswrite($$.to_s) - rescue => e - logger.warn("grandparent died too soon?: #{e.message} (#{e.class})") - end - @ready_pipe = @ready_pipe.close rescue nil - end - begin - reap_all_workers - case SIG_QUEUE.shift - when nil - # avoid murdering workers after our master process (or the - # machine) comes out of suspend/hibernation - if (last_check + @timeout) >= (last_check = Time.now) - sleep_time = murder_lazy_workers - else - sleep_time = @timeout/2.0 + 1 - @logger.debug("waiting #{sleep_time}s after suspend/hibernation") - end - maintain_worker_count if respawn - master_sleep(sleep_time) - when :QUIT # graceful shutdown - break - when :TERM, :INT # immediate shutdown - stop(false) - break - when :USR1 # rotate logs - logger.info "master reopening logs..." - Unicorn::Util.reopen_logs - logger.info "master done reopening logs" - soft_kill_each_worker(:USR1) - when :USR2 # exec binary, stay alive in case something went wrong - reexec - when :WINCH - if Unicorn::Configurator::RACKUP[:daemonized] - respawn = false - logger.info "gracefully stopping all workers" - soft_kill_each_worker(:QUIT) - self.worker_processes = 0 - else - logger.info "SIGWINCH ignored because we're not daemonized" - end - when :TTIN - respawn = true - self.worker_processes += 1 - when :TTOU - self.worker_processes -= 1 if self.worker_processes > 0 - when :HUP - respawn = true - if config.config_file - load_config! - else # exec binary and exit if there's no config file - logger.info "config_file not present, reexecuting binary" - reexec - end - end - rescue => e - Unicorn.log_error(@logger, "master loop error", e) - end while true - stop # gracefully shutdown all workers on our way out - logger.info "master complete" - unlink_pid_safe(pid) if pid - end - - # Terminates all workers, but does not exit master process - def stop(graceful = true) - self.listeners = [] - limit = Time.now + timeout - until WORKERS.empty? || Time.now > limit - if graceful - soft_kill_each_worker(:QUIT) - else - kill_each_worker(:TERM) - end - sleep(0.1) - reap_all_workers - end - kill_each_worker(:KILL) - end - - def rewindable_input - Unicorn::HttpRequest.input_class.method_defined?(:rewind) - end - - def rewindable_input=(bool) - Unicorn::HttpRequest.input_class = bool ? - Unicorn::TeeInput : Unicorn::StreamInput - end - - def client_body_buffer_size - Unicorn::TeeInput.client_body_buffer_size - end - - def client_body_buffer_size=(bytes) - Unicorn::TeeInput.client_body_buffer_size = bytes - end - - def trust_x_forwarded - Unicorn::HttpParser.trust_x_forwarded? - end - - def trust_x_forwarded=(bool) - Unicorn::HttpParser.trust_x_forwarded = bool - end - - def check_client_connection - Unicorn::HttpRequest.check_client_connection - end - - def check_client_connection=(bool) - Unicorn::HttpRequest.check_client_connection = bool - end - - private - - # wait for a signal hander to wake us up and then consume the pipe - def master_sleep(sec) - IO.select([ SELF_PIPE[0] ], nil, nil, sec) or return - SELF_PIPE[0].kgio_tryread(11) - end - - def awaken_master - return if $$ != @master_pid - SELF_PIPE[1].kgio_trywrite('.') # wakeup master process from select - end - - # reaps all unreaped workers - def reap_all_workers - begin - wpid, status = Process.waitpid2(-1, Process::WNOHANG) - wpid or return - if reexec_pid == wpid - logger.error "reaped #{status.inspect} exec()-ed" - self.reexec_pid = 0 - self.pid = pid.chomp('.oldbin') if pid - proc_name 'master' - else - worker = WORKERS.delete(wpid) and worker.close rescue nil - m = "reaped #{status.inspect} worker=#{worker.nr rescue 'unknown'}" - status.success? ? logger.info(m) : logger.error(m) - end - rescue Errno::ECHILD - break - end while true - end - - # reexecutes the START_CTX with a new binary - def reexec - if reexec_pid > 0 - begin - Process.kill(0, reexec_pid) - logger.error "reexec-ed child already running PID:#{reexec_pid}" - return - rescue Errno::ESRCH - self.reexec_pid = 0 - end - end - - if pid - old_pid = "#{pid}.oldbin" - begin - self.pid = old_pid # clear the path for a new pid file - rescue ArgumentError - logger.error "old PID:#{valid_pid?(old_pid)} running with " \ - "existing pid=#{old_pid}, refusing rexec" - return - rescue => e - logger.error "error writing pid=#{old_pid} #{e.class} #{e.message}" - return - end - end - - self.reexec_pid = fork do - listener_fds = {} - LISTENERS.each do |sock| - # IO#close_on_exec= will be available on any future version of - # Ruby that sets FD_CLOEXEC by default on new file descriptors - # ref: http://redmine.ruby-lang.org/issues/5041 - sock.close_on_exec = false if sock.respond_to?(:close_on_exec=) - listener_fds[sock.fileno] = sock - end - ENV['UNICORN_FD'] = listener_fds.keys.join(',') - Dir.chdir(START_CTX[:cwd]) - cmd = [ START_CTX[0] ].concat(START_CTX[:argv]) - - # avoid leaking FDs we don't know about, but let before_exec - # unset FD_CLOEXEC, if anything else in the app eventually - # relies on FD inheritence. - (3..1024).each do |io| - next if listener_fds.include?(io) - io = IO.for_fd(io) rescue next - prevent_autoclose(io) - io.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) - end - - # exec(command, hash) works in at least 1.9.1+, but will only be - # required in 1.9.4/2.0.0 at earliest. - cmd << listener_fds if RUBY_VERSION >= "1.9.1" - logger.info "executing #{cmd.inspect} (in #{Dir.pwd})" - before_exec.call(self) - exec(*cmd) - end - proc_name 'master (old)' - end - - # forcibly terminate all workers that haven't checked in in timeout seconds. The timeout is implemented using an unlinked File - def murder_lazy_workers - next_sleep = @timeout - 1 - now = Time.now.to_i - WORKERS.dup.each_pair do |wpid, worker| - tick = worker.tick - 0 == tick and next # skip workers that haven't processed any clients - diff = now - tick - tmp = @timeout - diff - if tmp >= 0 - next_sleep > tmp and next_sleep = tmp - next - end - next_sleep = 0 - logger.error "worker=#{worker.nr} PID:#{wpid} timeout " \ - "(#{diff}s > #{@timeout}s), killing" - kill_worker(:KILL, wpid) # take no prisoners for timeout violations - end - next_sleep <= 0 ? 1 : next_sleep - end - - def after_fork_internal - SELF_PIPE.each { |io| io.close }.clear # this is master-only, now - @ready_pipe.close if @ready_pipe - Unicorn::Configurator::RACKUP.clear - @ready_pipe = @init_listeners = @before_exec = @before_fork = nil - - srand # http://redmine.ruby-lang.org/issues/4338 - - # The OpenSSL PRNG is seeded with only the pid, and apps with frequently - # dying workers can recycle pids - OpenSSL::Random.seed(rand.to_s) if defined?(OpenSSL::Random) - end - - def spawn_missing_workers - worker_nr = -1 - until (worker_nr += 1) == @worker_processes - WORKERS.value?(worker_nr) and next - worker = Worker.new(worker_nr) - before_fork.call(self, worker) - if pid = fork - WORKERS[pid] = worker - worker.atfork_parent - else - after_fork_internal - worker_loop(worker) - exit - end - end - rescue => e - @logger.error(e) rescue nil - exit! - end - - def maintain_worker_count - (off = WORKERS.size - worker_processes) == 0 and return - off < 0 and return spawn_missing_workers - WORKERS.each_value { |w| w.nr >= worker_processes and w.soft_kill(:QUIT) } - end - - # if we get any error, try to write something back to the client - # assuming we haven't closed the socket, but don't get hung up - # if the socket is already closed or broken. We'll always ensure - # the socket is closed at the end of this function - def handle_error(client, e) - code = case e - when EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::ENOTCONN - # client disconnected on us and there's nothing we can do - when Unicorn::RequestURITooLongError - 414 - when Unicorn::RequestEntityTooLargeError - 413 - when Unicorn::HttpParserError # try to tell the client they're bad - 400 - else - Unicorn.log_error(@logger, "app error", e) - 500 - end - if code - client.kgio_trywrite(err_response(code, @request.response_start_sent)) - end - client.close - rescue - end - - def expect_100_response - if @request.response_start_sent - Unicorn::Const::EXPECT_100_RESPONSE_SUFFIXED - else - Unicorn::Const::EXPECT_100_RESPONSE - end - end - - # once a client is accepted, it is processed in its entirety here - # in 3 easy steps: read request, call app, write app response - def process_client(client) - status, headers, body = @app.call(env = @request.read(client)) - return if @request.hijacked? - - if 100 == status.to_i - client.write(expect_100_response) - env.delete(Unicorn::Const::HTTP_EXPECT) - status, headers, body = @app.call(env) - return if @request.hijacked? - end - @request.headers? or headers = nil - http_response_write(client, status, headers, body, - @request.response_start_sent) - unless client.closed? # rack.hijack may've close this for us - client.shutdown # in case of fork() in Rack app - client.close # flush and uncork socket immediately, no keepalive - end - rescue => e - handle_error(client, e) - end - - EXIT_SIGS = [ :QUIT, :TERM, :INT ] - WORKER_QUEUE_SIGS = QUEUE_SIGS - EXIT_SIGS - - def nuke_listeners!(readers) - # only called from the worker, ordering is important here - tmp = readers.dup - readers.replace([false]) # ensure worker does not continue ASAP - tmp.each { |io| io.close rescue nil } # break out of IO.select - end - - # gets rid of stuff the worker has no business keeping track of - # to free some resources and drops all sig handlers. - # traps for USR1, USR2, and HUP may be set in the after_fork Proc - # by the user. - def init_worker_process(worker) - worker.atfork_child - # we'll re-trap :QUIT later for graceful shutdown iff we accept clients - EXIT_SIGS.each { |sig| trap(sig) { exit!(0) } } - exit!(0) if (SIG_QUEUE & EXIT_SIGS)[0] - WORKER_QUEUE_SIGS.each { |sig| trap(sig, nil) } - trap(:CHLD, 'DEFAULT') - SIG_QUEUE.clear - proc_name "worker[#{worker.nr}]" - START_CTX.clear - WORKERS.clear - - after_fork.call(self, worker) # can drop perms and create listeners - LISTENERS.each { |sock| sock.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) } - - worker.user(*user) if user.kind_of?(Array) && ! worker.switched - self.timeout /= 2.0 # halve it for select() - @config = nil - build_app! unless preload_app - ssl_enable! - @after_fork = @listener_opts = @orig_app = nil - readers = LISTENERS.dup - readers << worker - trap(:QUIT) { nuke_listeners!(readers) } - readers - end - - def reopen_worker_logs(worker_nr) - logger.info "worker=#{worker_nr} reopening logs..." - Unicorn::Util.reopen_logs - logger.info "worker=#{worker_nr} done reopening logs" - rescue => e - logger.error(e) rescue nil - exit!(77) # EX_NOPERM in sysexits.h - end - - # runs inside each forked worker, this sits around and waits - # for connections and doesn't die until the parent dies (or is - # given a INT, QUIT, or TERM signal) - def worker_loop(worker) - ppid = master_pid - readers = init_worker_process(worker) - nr = 0 # this becomes negative if we need to reopen logs - - # this only works immediately if the master sent us the signal - # (which is the normal case) - trap(:USR1) { nr = -65536 } - - ready = readers.dup - @logger.info "worker=#{worker.nr} ready" - - begin - nr < 0 and reopen_worker_logs(worker.nr) - nr = 0 - worker.tick = Time.now.to_i - tmp = ready.dup - while sock = tmp.shift - # Unicorn::Worker#kgio_tryaccept is not like accept(2) at all, - # but that will return false - if client = sock.kgio_tryaccept - process_client(client) - nr += 1 - worker.tick = Time.now.to_i - end - break if nr < 0 - end - - # make the following bet: if we accepted clients this round, - # we're probably reasonably busy, so avoid calling select() - # and do a speculative non-blocking accept() on ready listeners - # before we sleep again in select(). - unless nr == 0 - tmp = ready.dup - redo - end - - ppid == Process.ppid or return - - # timeout used so we can detect parent death: - worker.tick = Time.now.to_i - ret = IO.select(readers, nil, nil, @timeout) and ready = ret[0] - rescue => e - redo if nr < 0 && readers[0] - Unicorn.log_error(@logger, "listen loop error", e) if readers[0] - end while readers[0] - end - - # delivers a signal to a worker and fails gracefully if the worker - # is no longer running. - def kill_worker(signal, wpid) - Process.kill(signal, wpid) - rescue Errno::ESRCH - worker = WORKERS.delete(wpid) and worker.close rescue nil - end - - # delivers a signal to each worker - def kill_each_worker(signal) - WORKERS.keys.each { |wpid| kill_worker(signal, wpid) } - end - - def soft_kill_each_worker(signal) - WORKERS.each_value { |worker| worker.soft_kill(signal) } - end - - # unlinks a PID file at given +path+ if it contains the current PID - # still potentially racy without locking the directory (which is - # non-portable and may interact badly with other programs), but the - # window for hitting the race condition is small - def unlink_pid_safe(path) - (File.read(path).to_i == $$ and File.unlink(path)) rescue nil - end - - # returns a PID if a given path contains a non-stale PID file, - # nil otherwise. - def valid_pid?(path) - wpid = File.read(path).to_i - wpid <= 0 and return - Process.kill(0, wpid) - wpid - rescue Errno::EPERM - logger.info "pid=#{path} possibly stale, got EPERM signalling PID:#{wpid}" - nil - rescue Errno::ESRCH, Errno::ENOENT - # don't unlink stale pid files, racy without non-portable locking... - end - - def load_config! - loaded_app = app - logger.info "reloading config_file=#{config.config_file}" - config[:listeners].replace(@init_listeners) - config.reload - config.commit!(self) - soft_kill_each_worker(:QUIT) - Unicorn::Util.reopen_logs - self.app = orig_app - build_app! if preload_app - logger.info "done reloading config_file=#{config.config_file}" - rescue StandardError, LoadError, SyntaxError => e - Unicorn.log_error(@logger, - "error reloading config_file=#{config.config_file}", e) - self.app = loaded_app - end - - # returns an array of string names for the given listener array - def listener_names(listeners = LISTENERS) - listeners.map { |io| sock_name(io) } - end - - def build_app! - if app.respond_to?(:arity) && app.arity == 0 - if defined?(Gem) && Gem.respond_to?(:refresh) - logger.info "Refreshing Gem list" - Gem.refresh - end - self.app = app.call - end - end - - def proc_name(tag) - $0 = ([ File.basename(START_CTX[0]), tag - ]).concat(START_CTX[:argv]).join(' ') - end - - def redirect_io(io, path) - File.open(path, 'ab') { |fp| io.reopen(fp) } if path - io.sync = true - end - - def inherit_listeners! - # inherit sockets from parents, they need to be plain Socket objects - # before they become Kgio::UNIXServer or Kgio::TCPServer - inherited = ENV['UNICORN_FD'].to_s.split(/,/).map do |fd| - io = Socket.for_fd(fd.to_i) - set_server_sockopt(io, listener_opts[sock_name(io)]) - prevent_autoclose(io) - logger.info "inherited addr=#{sock_name(io)} fd=#{fd}" - server_cast(io) - end - - config_listeners = config[:listeners].dup - LISTENERS.replace(inherited) - - # we start out with generic Socket objects that get cast to either - # Kgio::TCPServer or Kgio::UNIXServer objects; but since the Socket - # objects share the same OS-level file descriptor as the higher-level - # *Server objects; we need to prevent Socket objects from being - # garbage-collected - config_listeners -= listener_names - if config_listeners.empty? && LISTENERS.empty? - config_listeners << Unicorn::Const::DEFAULT_LISTEN - @init_listeners << Unicorn::Const::DEFAULT_LISTEN - START_CTX[:argv] << "-l#{Unicorn::Const::DEFAULT_LISTEN}" - end - NEW_LISTENERS.replace(config_listeners) - end - - # call only after calling inherit_listeners! - # This binds any listeners we did NOT inherit from the parent - def bind_new_listeners! - NEW_LISTENERS.each { |addr| listen(addr) } - raise ArgumentError, "no listeners" if LISTENERS.empty? - NEW_LISTENERS.clear - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/launcher.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/launcher.rb deleted file mode 100644 index 5eafe5b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/launcher.rb +++ /dev/null @@ -1,62 +0,0 @@ -# -*- encoding: binary -*- - -# :enddoc: -$stdout.sync = $stderr.sync = true -$stdin.binmode -$stdout.binmode -$stderr.binmode - -require 'unicorn' - -module Unicorn::Launcher - - # We don't do a lot of standard daemonization stuff: - # * umask is whatever was set by the parent process at startup - # and can be set in config.ru and config_file, so making it - # 0000 and potentially exposing sensitive log data can be bad - # policy. - # * don't bother to chdir("/") here since unicorn is designed to - # run inside APP_ROOT. Unicorn will also re-chdir() to - # the directory it was started in when being re-executed - # to pickup code changes if the original deployment directory - # is a symlink or otherwise got replaced. - def self.daemonize!(options) - cfg = Unicorn::Configurator - $stdin.reopen("/dev/null") - - # We only start a new process group if we're not being reexecuted - # and inheriting file descriptors from our parent - unless ENV['UNICORN_FD'] - # grandparent - reads pipe, exits when master is ready - # \_ parent - exits immediately ASAP - # \_ unicorn master - writes to pipe when ready - - rd, wr = IO.pipe - grandparent = $$ - if fork - wr.close # grandparent does not write - else - rd.close # unicorn master does not read - Process.setsid - exit if fork # parent dies now - end - - if grandparent == $$ - # this will block until HttpServer#join runs (or it dies) - master_pid = (rd.readpartial(16) rescue nil).to_i - unless master_pid > 1 - warn "master failed to start, check stderr log for details" - exit!(1) - end - exit 0 - else # unicorn master process - options[:ready_pipe] = wr - end - end - # $stderr/$stderr can/will be redirected separately in the Unicorn config - cfg::DEFAULTS[:stderr_path] ||= "/dev/null" - cfg::DEFAULTS[:stdout_path] ||= "/dev/null" - cfg::RACKUP[:daemonized] = true - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/oob_gc.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/oob_gc.rb deleted file mode 100644 index a07978b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/oob_gc.rb +++ /dev/null @@ -1,81 +0,0 @@ -# -*- encoding: binary -*- - -# Strongly consider https://github.com/tmm1/gctools if using Ruby 2.1+ -# It is built on new APIs in Ruby 2.1, so it is more intelligent than -# this historical implementation. -# -# Users on Ruby 2.0 (not 2.1+) may also want to check out -# lib/middleware/unicorn_oobgc.rb from the Discourse project -# (https://github.com/discourse/discourse) -# -# The following information is only for historical versions of Ruby. -# -# Runs GC after requests, after closing the client socket and -# before attempting to accept more connections. -# -# This shouldn't hurt overall performance as long as the server cluster -# is at <50% CPU capacity, and improves the performance of most memory -# intensive requests. This serves to improve _client-visible_ -# performance (possibly at the cost of overall performance). -# -# Increasing the number of +worker_processes+ may be necessary to -# improve average client response times because some of your workers -# will be busy doing GC and unable to service clients. Think of -# using more workers with this module as a poor man's concurrent GC. -# -# We'll call GC after each request is been written out to the socket, so -# the client never sees the extra GC hit it. -# -# This middleware is _only_ effective for applications that use a lot -# of memory, and will hurt simpler apps/endpoints that can process -# multiple requests before incurring GC. -# -# This middleware is only designed to work with unicorn, as it harms -# performance with keepalive-enabled servers. -# -# Example (in config.ru): -# -# require 'unicorn/oob_gc' -# -# # GC ever two requests that hit /expensive/foo or /more_expensive/foo -# # in your app. By default, this will GC once every 5 requests -# # for all endpoints in your app -# use Unicorn::OobGC, 2, %r{\A/(?:expensive/foo|more_expensive/foo)} -# -# Feedback from users of early implementations of this module: -# * http://comments.gmane.org/gmane.comp.lang.ruby.unicorn.general/486 -# * http://article.gmane.org/gmane.comp.lang.ruby.unicorn.general/596 -module Unicorn::OobGC - - # this pretends to be Rack middleware because it used to be - # But we need to hook into unicorn internals so we need to close - # the socket before clearing the request env. - # - # +interval+ is the number of requests matching the +path+ regular - # expression before invoking GC. - def self.new(app, interval = 5, path = %r{\A/}) - @@nr = interval - self.const_set :OOBGC_PATH, path - self.const_set :OOBGC_INTERVAL, interval - ObjectSpace.each_object(Unicorn::HttpServer) do |s| - s.extend(self) - self.const_set :OOBGC_ENV, s.instance_variable_get(:@request).env - end - app # pretend to be Rack middleware since it was in the past - end - - #:stopdoc: - PATH_INFO = "PATH_INFO" - def process_client(client) - super(client) # Unicorn::HttpServer#process_client - if OOBGC_PATH =~ OOBGC_ENV[PATH_INFO] && ((@@nr -= 1) <= 0) - @@nr = OOBGC_INTERVAL - OOBGC_ENV.clear - disabled = GC.enable - GC.start - GC.disable if disabled - end - end - - # :startdoc: -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/preread_input.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/preread_input.rb deleted file mode 100644 index 12eb3e8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/preread_input.rb +++ /dev/null @@ -1,33 +0,0 @@ -# -*- encoding: binary -*- - -module Unicorn -# This middleware is used to ensure input is buffered to memory -# or disk (depending on size) before the application is dispatched -# by entirely consuming it (from TeeInput) beforehand. -# -# Usage (in config.ru): -# -# require 'unicorn/preread_input' -# if defined?(Unicorn) -# use Unicorn::PrereadInput -# end -# run YourApp.new -class PrereadInput - - # :stopdoc: - def initialize(app) - @app = app - end - - def call(env) - buf = "" - input = env["rack.input"] - if input.respond_to?(:rewind) - true while input.read(16384, buf) - input.rewind - end - @app.call(env) - end - # :startdoc: -end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/socket_helper.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/socket_helper.rb deleted file mode 100644 index 820b778..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/socket_helper.rb +++ /dev/null @@ -1,231 +0,0 @@ -# -*- encoding: binary -*- -# :enddoc: -require 'socket' - -module Unicorn - module SocketHelper - # :stopdoc: - include Socket::Constants - - # prevents IO objects in here from being GC-ed - # kill this when we drop 1.8 support - IO_PURGATORY = [] - - # internal interface, only used by Rainbows!/Zbatery - DEFAULTS = { - # The semantics for TCP_DEFER_ACCEPT changed in Linux 2.6.32+ - # with commit d1b99ba41d6c5aa1ed2fc634323449dd656899e9 - # This change shouldn't affect Unicorn users behind nginx (a - # value of 1 remains an optimization), but Rainbows! users may - # want to use a higher value on Linux 2.6.32+ to protect against - # denial-of-service attacks - :tcp_defer_accept => 1, - - # FreeBSD, we need to override this to 'dataready' if we - # eventually get HTTPS support - :accept_filter => 'httpready', - - # same default value as Mongrel - :backlog => 1024, - - # favor latency over bandwidth savings - :tcp_nopush => nil, - :tcp_nodelay => true, - } - #:startdoc: - - # configure platform-specific options (only tested on Linux 2.6 so far) - case RUBY_PLATFORM - when /linux/ - # from /usr/include/linux/tcp.h - TCP_DEFER_ACCEPT = 9 unless defined?(TCP_DEFER_ACCEPT) - - # do not send out partial frames (Linux) - TCP_CORK = 3 unless defined?(TCP_CORK) - - # Linux got SO_REUSEPORT in 3.9, BSDs have had it for ages - unless defined?(SO_REUSEPORT) - if RUBY_PLATFORM =~ /(?:alpha|mips|parisc|sparc)/ - SO_REUSEPORT = 0x0200 # untested - else - SO_REUSEPORT = 15 # only tested on x86_64 and i686 - end - end - when /freebsd/ - # do not send out partial frames (FreeBSD) - TCP_NOPUSH = 4 unless defined?(TCP_NOPUSH) - - def accf_arg(af_name) - [ af_name, nil ].pack('a16a240') - end if defined?(SO_ACCEPTFILTER) - end - - def prevent_autoclose(io) - if io.respond_to?(:autoclose=) - io.autoclose = false - else - IO_PURGATORY << io - end - end - - def set_tcp_sockopt(sock, opt) - # just in case, even LANs can break sometimes. Linux sysadmins - # can lower net.ipv4.tcp_keepalive_* sysctl knobs to very low values. - sock.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1) if defined?(SO_KEEPALIVE) - - if defined?(TCP_NODELAY) - val = opt[:tcp_nodelay] - val = DEFAULTS[:tcp_nodelay] if nil == val - sock.setsockopt(IPPROTO_TCP, TCP_NODELAY, val ? 1 : 0) - end - - val = opt[:tcp_nopush] - unless val.nil? - if defined?(TCP_CORK) # Linux - sock.setsockopt(IPPROTO_TCP, TCP_CORK, val) - elsif defined?(TCP_NOPUSH) # TCP_NOPUSH is lightly tested (FreeBSD) - sock.setsockopt(IPPROTO_TCP, TCP_NOPUSH, val) - end - end - - # No good reason to ever have deferred accepts off - # (except maybe benchmarking) - if defined?(TCP_DEFER_ACCEPT) - # this differs from nginx, since nginx doesn't allow us to - # configure the the timeout... - seconds = opt[:tcp_defer_accept] - seconds = DEFAULTS[:tcp_defer_accept] if [true,nil].include?(seconds) - seconds = 0 unless seconds # nil/false means disable this - sock.setsockopt(SOL_TCP, TCP_DEFER_ACCEPT, seconds) - elsif respond_to?(:accf_arg) - name = opt[:accept_filter] - name = DEFAULTS[:accept_filter] if nil == name - begin - sock.setsockopt(SOL_SOCKET, SO_ACCEPTFILTER, accf_arg(name)) - rescue => e - logger.error("#{sock_name(sock)} " \ - "failed to set accept_filter=#{name} (#{e.inspect})") - end - end - end - - def set_server_sockopt(sock, opt) - opt = DEFAULTS.merge(opt || {}) - - TCPSocket === sock and set_tcp_sockopt(sock, opt) - - if opt[:rcvbuf] || opt[:sndbuf] - log_buffer_sizes(sock, "before: ") - sock.setsockopt(SOL_SOCKET, SO_RCVBUF, opt[:rcvbuf]) if opt[:rcvbuf] - sock.setsockopt(SOL_SOCKET, SO_SNDBUF, opt[:sndbuf]) if opt[:sndbuf] - log_buffer_sizes(sock, " after: ") - end - sock.listen(opt[:backlog]) - rescue => e - Unicorn.log_error(logger, "#{sock_name(sock)} #{opt.inspect}", e) - end - - def log_buffer_sizes(sock, pfx = '') - rcvbuf = sock.getsockopt(SOL_SOCKET, SO_RCVBUF).unpack('i') - sndbuf = sock.getsockopt(SOL_SOCKET, SO_SNDBUF).unpack('i') - logger.info "#{pfx}#{sock_name(sock)} rcvbuf=#{rcvbuf} sndbuf=#{sndbuf}" - end - - # creates a new server, socket. address may be a HOST:PORT or - # an absolute path to a UNIX socket. address can even be a Socket - # object in which case it is immediately returned - def bind_listen(address = '0.0.0.0:8080', opt = {}) - return address unless String === address - - sock = if address[0] == ?/ - if File.exist?(address) - if File.socket?(address) - begin - UNIXSocket.new(address).close - # fall through, try to bind(2) and fail with EADDRINUSE - # (or succeed from a small race condition we can't sanely avoid). - rescue Errno::ECONNREFUSED - logger.info "unlinking existing socket=#{address}" - File.unlink(address) - end - else - raise ArgumentError, - "socket=#{address} specified but it is not a socket!" - end - end - old_umask = File.umask(opt[:umask] || 0) - begin - Kgio::UNIXServer.new(address) - ensure - File.umask(old_umask) - end - elsif /\A\[([a-fA-F0-9:]+)\]:(\d+)\z/ =~ address - new_tcp_server($1, $2.to_i, opt.merge(:ipv6=>true)) - elsif /\A(\d+\.\d+\.\d+\.\d+):(\d+)\z/ =~ address - new_tcp_server($1, $2.to_i, opt) - else - raise ArgumentError, "Don't know how to bind: #{address}" - end - set_server_sockopt(sock, opt) - sock - end - - def new_tcp_server(addr, port, opt) - # n.b. we set FD_CLOEXEC in the workers - sock = Socket.new(opt[:ipv6] ? AF_INET6 : AF_INET, SOCK_STREAM, 0) - if opt.key?(:ipv6only) - defined?(IPV6_V6ONLY) or - abort "Socket::IPV6_V6ONLY not defined, upgrade Ruby and/or your OS" - sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, opt[:ipv6only] ? 1 : 0) - end - sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) - if defined?(SO_REUSEPORT) && opt[:reuseport] - sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1) - end - sock.bind(Socket.pack_sockaddr_in(port, addr)) - prevent_autoclose(sock) - Kgio::TCPServer.for_fd(sock.fileno) - end - - # returns rfc2732-style (e.g. "[::1]:666") addresses for IPv6 - def tcp_name(sock) - port, addr = Socket.unpack_sockaddr_in(sock.getsockname) - /:/ =~ addr ? "[#{addr}]:#{port}" : "#{addr}:#{port}" - end - module_function :tcp_name - - # Returns the configuration name of a socket as a string. sock may - # be a string value, in which case it is returned as-is - # Warning: TCP sockets may not always return the name given to it. - def sock_name(sock) - case sock - when String then sock - when UNIXServer - Socket.unpack_sockaddr_un(sock.getsockname) - when TCPServer - tcp_name(sock) - when Socket - begin - tcp_name(sock) - rescue ArgumentError - Socket.unpack_sockaddr_un(sock.getsockname) - end - else - raise ArgumentError, "Unhandled class #{sock.class}: #{sock.inspect}" - end - end - - module_function :sock_name - - # casts a given Socket to be a TCPServer or UNIXServer - def server_cast(sock) - begin - Socket.unpack_sockaddr_in(sock.getsockname) - Kgio::TCPServer.for_fd(sock.fileno) - rescue ArgumentError - Kgio::UNIXServer.for_fd(sock.fileno) - end - end - - end # module SocketHelper -end # module Unicorn diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_client.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_client.rb deleted file mode 100644 index a8c79e3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_client.rb +++ /dev/null @@ -1,11 +0,0 @@ -# -*- encoding: binary -*- -# :stopdoc: -class Unicorn::SSLClient < Kgio::SSL - alias write kgio_write - alias close kgio_close - - # this is no-op for now, to be fixed in kgio-monkey if people care - # about SSL support... - def shutdown(how = nil) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_configurator.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_configurator.rb deleted file mode 100644 index 34f09ec..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_configurator.rb +++ /dev/null @@ -1,104 +0,0 @@ -# -*- encoding: binary -*- -# :stopdoc: -# This module is included in Unicorn::Configurator -# :startdoc: -# -module Unicorn::SSLConfigurator - def ssl(&block) - ssl_require! - before = @set[:listeners].dup - opts = @set[:ssl_opts] = {} - yield - (@set[:listeners] - before).each do |address| - (@set[:listener_opts][address] ||= {})[:ssl_opts] = opts - end - ensure - @set.delete(:ssl_opts) - end - - def ssl_certificate(file) - ssl_set(:ssl_certificate, file) - end - - def ssl_certificate_key(file) - ssl_set(:ssl_certificate_key, file) - end - - def ssl_client_certificate(file) - ssl_set(:ssl_client_certificate, file) - end - - def ssl_dhparam(file) - ssl_set(:ssl_dhparam, file) - end - - def ssl_ciphers(openssl_cipherlist_spec) - ssl_set(:ssl_ciphers, openssl_cipherlist_spec) - end - - def ssl_crl(file) - ssl_set(:ssl_crl, file) - end - - def ssl_prefer_server_ciphers(bool) - ssl_set(:ssl_prefer_server_ciphers, check_bool(bool)) - end - - def ssl_protocols(list) - ssl_set(:ssl_protocols, list) - end - - def ssl_verify_client(on_off_optional) - ssl_set(:ssl_verify_client, on_off_optional) - end - - def ssl_session_timeout(seconds) - ssl_set(:ssl_session_timeout, seconds) - end - - def ssl_verify_depth(depth) - ssl_set(:ssl_verify_depth, depth) - end - - # Allows specifying an engine for OpenSSL to use. We have not been - # able to successfully test this feature due to a lack of hardware, - # Reports of success or patches to unicorn-public@bogomips.org is - # greatly appreciated. - def ssl_engine(engine) - ssl_warn_global(:ssl_engine) - ssl_require! - OpenSSL::Engine.load - OpenSSL::Engine.by_id(engine) - @set[:ssl_engine] = engine - end - - def ssl_compression(bool) - # OpenSSL uses the SSL_OP_NO_COMPRESSION flag, Flipper follows suit - # with :ssl_no_compression, but we negate it to avoid exposing double - # negatives to the user. - ssl_set(:ssl_no_compression, check_bool(:ssl_compression, ! bool)) - end - -private - - def ssl_warn_global(func) # :nodoc: - Hash === @set[:ssl_opts] or return - warn("`#{func}' affects all SSL contexts in this process, " \ - "not just this block") - end - - def ssl_set(key, value) # :nodoc: - cur = @set[:ssl_opts] - Hash === cur or - raise ArgumentError, "#{key} must be called inside an `ssl' block" - cur[key] = value - end - - def ssl_require! # :nodoc: - require "flipper" - require "unicorn/ssl_client" - rescue LoadError - warn "install 'kgio-monkey' for SSL support" - raise - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_server.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_server.rb deleted file mode 100644 index c00c3ae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/ssl_server.rb +++ /dev/null @@ -1,42 +0,0 @@ -# -*- encoding: binary -*- -# :stopdoc: -# this module is meant to be included in Unicorn::HttpServer -# It is an implementation detail and NOT meant for users. -module Unicorn::SSLServer - attr_accessor :ssl_engine - - def ssl_enable! - sni_hostnames = rack_sni_hostnames(@app) - seen = {} # we map a single SSLContext to multiple listeners - listener_ctx = {} - @listener_opts.each do |address, address_opts| - ssl_opts = address_opts[:ssl_opts] or next - listener_ctx[address] = seen[ssl_opts.object_id] ||= begin - unless sni_hostnames.empty? - ssl_opts = ssl_opts.dup - ssl_opts[:sni_hostnames] = sni_hostnames - end - ctx = Flipper.ssl_context(ssl_opts) - # FIXME: make configurable - ctx.session_cache_mode = OpenSSL::SSL::SSLContext::SESSION_CACHE_OFF - ctx - end - end - Unicorn::HttpServer::LISTENERS.each do |listener| - ctx = listener_ctx[sock_name(listener)] or next - listener.extend(Kgio::SSLServer) - listener.ssl_ctx = ctx - listener.kgio_ssl_class = Unicorn::SSLClient - end - end - - # ugh, this depends on Rack internals... - def rack_sni_hostnames(rack_app) # :nodoc: - hostnames = {} - if Rack::URLMap === rack_app - mapping = rack_app.instance_variable_get(:@mapping) - mapping.each { |hostname,_,_,_| hostnames[hostname] = true } - end - hostnames.keys - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/stream_input.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/stream_input.rb deleted file mode 100644 index 9278f47..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/stream_input.rb +++ /dev/null @@ -1,146 +0,0 @@ -# -*- encoding: binary -*- - -# When processing uploads, Unicorn may expose a StreamInput object under -# "rack.input" of the (future) Rack (2.x) environment. -class Unicorn::StreamInput - # The I/O chunk size (in +bytes+) for I/O operations where - # the size cannot be user-specified when a method is called. - # The default is 16 kilobytes. - @@io_chunk_size = Unicorn::Const::CHUNK_SIZE - - # Initializes a new StreamInput object. You normally do not have to call - # this unless you are writing an HTTP server. - def initialize(socket, request) - @chunked = request.content_length.nil? - @socket = socket - @parser = request - @buf = request.buf - @rbuf = '' - @bytes_read = 0 - filter_body(@rbuf, @buf) unless @buf.empty? - end - - # :call-seq: - # ios.read([length [, buffer ]]) => string, buffer, or nil - # - # Reads at most length bytes from the I/O stream, or to the end of - # file if length is omitted or is nil. length must be a non-negative - # integer or nil. If the optional buffer argument is present, it - # must reference a String, which will receive the data. - # - # At end of file, it returns nil or '' depend on length. - # ios.read() and ios.read(nil) returns ''. - # ios.read(length [, buffer]) returns nil. - # - # If the Content-Length of the HTTP request is known (as is the common - # case for POST requests), then ios.read(length [, buffer]) will block - # until the specified length is read (or it is the last chunk). - # Otherwise, for uncommon "Transfer-Encoding: chunked" requests, - # ios.read(length [, buffer]) will return immediately if there is - # any data and only block when nothing is available (providing - # IO#readpartial semantics). - def read(length = nil, rv = '') - if length - if length <= @rbuf.size - length < 0 and raise ArgumentError, "negative length #{length} given" - rv.replace(@rbuf.slice!(0, length)) - else - to_read = length - @rbuf.size - rv.replace(@rbuf.slice!(0, @rbuf.size)) - until to_read == 0 || eof? || (rv.size > 0 && @chunked) - @socket.kgio_read(to_read, @buf) or eof! - filter_body(@rbuf, @buf) - rv << @rbuf - to_read -= @rbuf.size - end - @rbuf.replace('') - end - rv = nil if rv.empty? && length != 0 - else - read_all(rv) - end - rv - end - - # :call-seq: - # ios.gets => string or nil - # - # Reads the next ``line'' from the I/O stream; lines are separated - # by the global record separator ($/, typically "\n"). A global - # record separator of nil reads the entire unread contents of ios. - # Returns nil if called at the end of file. - # This takes zero arguments for strict Rack::Lint compatibility, - # unlike IO#gets. - def gets - sep = $/ - if sep.nil? - read_all(rv = '') - return rv.empty? ? nil : rv - end - re = /\A(.*?#{Regexp.escape(sep)})/ - - begin - @rbuf.sub!(re, '') and return $1 - return @rbuf.empty? ? nil : @rbuf.slice!(0, @rbuf.size) if eof? - @socket.kgio_read(@@io_chunk_size, @buf) or eof! - filter_body(once = '', @buf) - @rbuf << once - end while true - end - - # :call-seq: - # ios.each { |line| block } => ios - # - # Executes the block for every ``line'' in *ios*, where lines are - # separated by the global record separator ($/, typically "\n"). - def each - while line = gets - yield line - end - - self # Rack does not specify what the return value is here - end - -private - - def eof? - if @parser.body_eof? - while @chunked && ! @parser.parse - once = @socket.kgio_read(@@io_chunk_size) or eof! - @buf << once - end - @socket = nil - true - else - false - end - end - - def filter_body(dst, src) - rv = @parser.filter_body(dst, src) - @bytes_read += dst.size - rv - end - - def read_all(dst) - dst.replace(@rbuf) - @socket or return - until eof? - @socket.kgio_read(@@io_chunk_size, @buf) or eof! - filter_body(@rbuf, @buf) - dst << @rbuf - end - ensure - @rbuf.replace('') - end - - def eof! - # in case client only did a premature shutdown(SHUT_WR) - # we do support clients that shutdown(SHUT_WR) after the - # _entire_ request has been sent, and those will not have - # raised EOFError on us. - @socket.shutdown if @socket - ensure - raise Unicorn::ClientShutdown, "bytes_read=#{@bytes_read}", [] - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/tee_input.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/tee_input.rb deleted file mode 100644 index 637c583..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/tee_input.rb +++ /dev/null @@ -1,126 +0,0 @@ -# -*- encoding: binary -*- - -# acts like tee(1) on an input input to provide a input-like stream -# while providing rewindable semantics through a File/StringIO backing -# store. On the first pass, the input is only read on demand so your -# Rack application can use input notification (upload progress and -# like). This should fully conform to the Rack::Lint::InputWrapper -# specification on the public API. This class is intended to be a -# strict interpretation of Rack::Lint::InputWrapper functionality and -# will not support any deviations from it. -# -# When processing uploads, Unicorn exposes a TeeInput object under -# "rack.input" of the Rack environment. -class Unicorn::TeeInput < Unicorn::StreamInput - # The maximum size (in +bytes+) to buffer in memory before - # resorting to a temporary file. Default is 112 kilobytes. - @@client_body_buffer_size = Unicorn::Const::MAX_BODY - - # sets the maximum size of request bodies to buffer in memory, - # amounts larger than this are buffered to the filesystem - def self.client_body_buffer_size=(bytes) - @@client_body_buffer_size = bytes - end - - # returns the maximum size of request bodies to buffer in memory, - # amounts larger than this are buffered to the filesystem - def self.client_body_buffer_size - @@client_body_buffer_size - end - - # Initializes a new TeeInput object. You normally do not have to call - # this unless you are writing an HTTP server. - def initialize(socket, request) - @len = request.content_length - super - @tmp = @len && @len <= @@client_body_buffer_size ? - StringIO.new("") : Unicorn::TmpIO.new - end - - # :call-seq: - # ios.size => Integer - # - # Returns the size of the input. For requests with a Content-Length - # header value, this will not read data off the socket and just return - # the value of the Content-Length header as an Integer. - # - # For Transfer-Encoding:chunked requests, this requires consuming - # all of the input stream before returning since there's no other - # way to determine the size of the request body beforehand. - # - # This method is no longer part of the Rack specification as of - # Rack 1.2, so its use is not recommended. This method only exists - # for compatibility with Rack applications designed for Rack 1.1 and - # earlier. Most applications should only need to call +read+ with a - # specified +length+ in a loop until it returns +nil+. - def size - @len and return @len - pos = @tmp.pos - consume! - @tmp.pos = pos - @len = @tmp.size - end - - # :call-seq: - # ios.read([length [, buffer ]]) => string, buffer, or nil - # - # Reads at most length bytes from the I/O stream, or to the end of - # file if length is omitted or is nil. length must be a non-negative - # integer or nil. If the optional buffer argument is present, it - # must reference a String, which will receive the data. - # - # At end of file, it returns nil or "" depend on length. - # ios.read() and ios.read(nil) returns "". - # ios.read(length [, buffer]) returns nil. - # - # If the Content-Length of the HTTP request is known (as is the common - # case for POST requests), then ios.read(length [, buffer]) will block - # until the specified length is read (or it is the last chunk). - # Otherwise, for uncommon "Transfer-Encoding: chunked" requests, - # ios.read(length [, buffer]) will return immediately if there is - # any data and only block when nothing is available (providing - # IO#readpartial semantics). - def read(*args) - @socket ? tee(super) : @tmp.read(*args) - end - - # :call-seq: - # ios.gets => string or nil - # - # Reads the next ``line'' from the I/O stream; lines are separated - # by the global record separator ($/, typically "\n"). A global - # record separator of nil reads the entire unread contents of ios. - # Returns nil if called at the end of file. - # This takes zero arguments for strict Rack::Lint compatibility, - # unlike IO#gets. - def gets - @socket ? tee(super) : @tmp.gets - end - - # :call-seq: - # ios.rewind => 0 - # - # Positions the *ios* pointer to the beginning of input, returns - # the offset (zero) of the +ios+ pointer. Subsequent reads will - # start from the beginning of the previously-buffered input. - def rewind - return 0 if 0 == @tmp.size - consume! if @socket - @tmp.rewind # Rack does not specify what the return value is here - end - -private - - # consumes the stream of the socket - def consume! - junk = "" - nil while read(@@io_chunk_size, junk) - end - - def tee(buffer) - if buffer && buffer.size > 0 - @tmp.write(buffer) - end - buffer - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/tmpio.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/tmpio.rb deleted file mode 100644 index 2da05a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/tmpio.rb +++ /dev/null @@ -1,29 +0,0 @@ -# -*- encoding: binary -*- -# :stopdoc: -require 'tmpdir' - -# some versions of Ruby had a broken Tempfile which didn't work -# well with unlinked files. This one is much shorter, easier -# to understand, and slightly faster. -class Unicorn::TmpIO < File - - # creates and returns a new File object. The File is unlinked - # immediately, switched to binary mode, and userspace output - # buffering is disabled - def self.new - fp = begin - super("#{Dir::tmpdir}/#{rand}", RDWR|CREAT|EXCL, 0600) - rescue Errno::EEXIST - retry - end - unlink(fp.path) - fp.binmode - fp.sync = true - fp - end - - # for easier env["rack.input"] compatibility with Rack <= 1.1 - def size - stat.size - end unless File.method_defined?(:size) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/util.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/util.rb deleted file mode 100644 index 94c4e37..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/util.rb +++ /dev/null @@ -1,89 +0,0 @@ -# -*- encoding: binary -*- - -module Unicorn::Util - -# :stopdoc: - def self.is_log?(fp) - append_flags = File::WRONLY | File::APPEND - - ! fp.closed? && - fp.stat.file? && - fp.sync && - (fp.fcntl(Fcntl::F_GETFL) & append_flags) == append_flags - rescue IOError, Errno::EBADF - false - end - - def self.chown_logs(uid, gid) - ObjectSpace.each_object(File) do |fp| - fp.chown(uid, gid) if is_log?(fp) - end - end -# :startdoc: - - # This reopens ALL logfiles in the process that have been rotated - # using logrotate(8) (without copytruncate) or similar tools. - # A +File+ object is considered for reopening if it is: - # 1) opened with the O_APPEND and O_WRONLY flags - # 2) the current open file handle does not match its original open path - # 3) unbuffered (as far as userspace buffering goes, not O_SYNC) - # Returns the number of files reopened - # - # In Unicorn 3.5.x and earlier, files must be opened with an absolute - # path to be considered a log file. - def self.reopen_logs - to_reopen = [] - nr = 0 - ObjectSpace.each_object(File) { |fp| is_log?(fp) and to_reopen << fp } - - to_reopen.each do |fp| - orig_st = begin - fp.stat - rescue IOError, Errno::EBADF # race - next - end - - begin - b = File.stat(fp.path) - next if orig_st.ino == b.ino && orig_st.dev == b.dev - rescue Errno::ENOENT - end - - begin - # stdin, stdout, stderr are special. The following dance should - # guarantee there is no window where `fp' is unwritable in MRI - # (or any correct Ruby implementation). - # - # Fwiw, GVL has zero bearing here. This is tricky because of - # the unavoidable existence of stdio FILE * pointers for - # std{in,out,err} in all programs which may use the standard C library - if fp.fileno <= 2 - # We do not want to hit fclose(3)->dup(2) window for std{in,out,err} - # MRI will use freopen(3) here internally on std{in,out,err} - fp.reopen(fp.path, "a") - else - # We should not need this workaround, Ruby can be fixed: - # http://bugs.ruby-lang.org/issues/9036 - # MRI will not call call fclose(3) or freopen(3) here - # since there's no associated std{in,out,err} FILE * pointer - # This should atomically use dup3(2) (or dup2(2)) syscall - File.open(fp.path, "a") { |tmpfp| fp.reopen(tmpfp) } - end - - fp.sync = true - fp.flush # IO#sync=true may not implicitly flush - new_st = fp.stat - - # this should only happen in the master: - if orig_st.uid != new_st.uid || orig_st.gid != new_st.gid - fp.chown(orig_st.uid, orig_st.gid) - end - - nr += 1 - rescue IOError, Errno::EBADF - # not much we can do... - end - end - nr - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/worker.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/worker.rb deleted file mode 100644 index e74a1c9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/lib/unicorn/worker.rb +++ /dev/null @@ -1,152 +0,0 @@ -# -*- encoding: binary -*- -require "raindrops" - -# This class and its members can be considered a stable interface -# and will not change in a backwards-incompatible fashion between -# releases of \Unicorn. Knowledge of this class is generally not -# not needed for most users of \Unicorn. -# -# Some users may want to access it in the before_fork/after_fork hooks. -# See the Unicorn::Configurator RDoc for examples. -class Unicorn::Worker - # :stopdoc: - attr_accessor :nr, :switched - attr_writer :tmp - attr_reader :to_io # IO.select-compatible - - PER_DROP = Raindrops::PAGE_SIZE / Raindrops::SIZE - DROPS = [] - - def initialize(nr) - drop_index = nr / PER_DROP - @raindrop = DROPS[drop_index] ||= Raindrops.new(PER_DROP) - @offset = nr % PER_DROP - @raindrop[@offset] = 0 - @nr = nr - @tmp = @switched = false - @to_io, @master = Unicorn.pipe - end - - def atfork_child # :nodoc: - # we _must_ close in child, parent just holds this open to signal - @master = @master.close - end - - # master fakes SIGQUIT using this - def quit # :nodoc: - @master = @master.close if @master - end - - # parent does not read - def atfork_parent # :nodoc: - @to_io = @to_io.close - end - - # call a signal handler immediately without triggering EINTR - # We do not use the more obvious Process.kill(sig, $$) here since - # that signal delivery may be deferred. We want to avoid signal delivery - # while the Rack app.call is running because some database drivers - # (e.g. ruby-pg) may cancel pending requests. - def fake_sig(sig) # :nodoc: - old_cb = trap(sig, "IGNORE") - old_cb.call - ensure - trap(sig, old_cb) - end - - # master sends fake signals to children - def soft_kill(sig) # :nodoc: - case sig - when Integer - signum = sig - else - signum = Signal.list[sig.to_s] or - raise ArgumentError, "BUG: bad signal: #{sig.inspect}" - end - # writing and reading 4 bytes on a pipe is atomic on all POSIX platforms - # Do not care in the odd case the buffer is full, here. - @master.kgio_trywrite([signum].pack('l')) - rescue Errno::EPIPE - # worker will be reaped soon - end - - # this only runs when the Rack app.call is not running - # act like a listener - def kgio_tryaccept # :nodoc: - case buf = @to_io.kgio_tryread(4) - when String - # unpack the buffer and trigger the signal handler - signum = buf.unpack('l') - fake_sig(signum[0]) - # keep looping, more signals may be queued - when nil # EOF: master died, but we are at a safe place to exit - fake_sig(:QUIT) - when :wait_readable # keep waiting - return false - end while true # loop, as multiple signals may be sent - end - - # worker objects may be compared to just plain Integers - def ==(other_nr) # :nodoc: - @nr == other_nr - end - - # called in the worker process - def tick=(value) # :nodoc: - @raindrop[@offset] = value - end - - # called in the master process - def tick # :nodoc: - @raindrop[@offset] - end - - # only exists for compatibility - def tmp # :nodoc: - @tmp ||= begin - tmp = Unicorn::TmpIO.new - tmp.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) - tmp - end - end - - # called in both the master (reaping worker) and worker (SIGQUIT handler) - def close # :nodoc: - @tmp.close if @tmp - @master.close if @master - @to_io.close if @to_io - end - - # :startdoc: - - # In most cases, you should be using the Unicorn::Configurator#user - # directive instead. This method should only be used if you need - # fine-grained control of exactly when you want to change permissions - # in your after_fork hooks. - # - # Changes the worker process to the specified +user+ and +group+ - # This is only intended to be called from within the worker - # process from the +after_fork+ hook. This should be called in - # the +after_fork+ hook after any privileged functions need to be - # run (e.g. to set per-worker CPU affinity, niceness, etc) - # - # Any and all errors raised within this method will be propagated - # directly back to the caller (usually the +after_fork+ hook. - # These errors commonly include ArgumentError for specifying an - # invalid user/group and Errno::EPERM for insufficient privileges - def user(user, group = nil) - # we do not protect the caller, checking Process.euid == 0 is - # insufficient because modern systems have fine-grained - # capabilities. Let the caller handle any and all errors. - uid = Etc.getpwnam(user).uid - gid = Etc.getgrnam(group).gid if group - Unicorn::Util.chown_logs(uid, gid) - @tmp.chown(uid, gid) if @tmp - if gid && Process.egid != gid - Process.initgroups(user, gid) - Process::GID.change_privilege(gid) - end - Process.euid != uid and Process::UID.change_privilege(uid) - @switched = true - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/local.mk.sample b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/local.mk.sample deleted file mode 100644 index 25bca5d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/local.mk.sample +++ /dev/null @@ -1,59 +0,0 @@ -# this is the local.mk file used by Eric Wong on his dev boxes. -# GNUmakefile will source local.mk in the top-level source tree -# if it is present. -# -# This is depends on a bunch of GNU-isms from bash, sed, touch. - -DLEXT := so - -# Avoid loading rubygems to speed up tests because gmake is -# fork+exec heavy with Ruby. -prefix = $(HOME) - -# XXX clean this up -ifeq ($(r192),) - ifeq ($(r19),) - ifeq ($(rbx),) - ifeq ($(r186),) - RUBY := $(prefix)/bin/ruby - else - prefix := $(prefix)/r186-p114 - export PATH := $(prefix)/bin:$(PATH) - RUBY := $(prefix)/bin/ruby - endif - else - prefix := $(prefix)/rbx - export PATH := $(prefix)/bin:$(PATH) - RUBY := $(prefix)/bin/rbx - endif - else - prefix := $(prefix)/ruby-1.9 - export PATH := $(prefix)/bin:$(PATH) - RUBY := $(prefix)/bin/ruby --disable-gems - endif -else - prefix := $(prefix)/ruby-1.9.2 - export PATH := $(prefix)/bin:$(PATH) - RUBY := $(prefix)/bin/ruby --disable-gems -endif - -# pipefail is THE reason to use bash (v3+) or never revisions of ksh93 -# SHELL := /bin/bash -e -o pipefail -SHELL := /bin/ksh93 -e -o pipefail - -full-test: test-18 test-191 test-192 test-rbx test-186 - -# FIXME: keep eye on Rubinius activity and wait for fixes from upstream -# so we don't need RBX_SKIP anymore -test-rbx: export RBX_SKIP := 1 -test-rbx: export RUBY := $(RUBY) -test-rbx: - $(MAKE) test test-integration rbx=T 2>&1 |sed -e 's!^!rbx !' -test-186: - $(MAKE) test-all r186=1 2>&1 |sed 's!^!1.8.6 !' -test-18: - $(MAKE) test-all 2>&1 |sed 's!^!1.8 !' -test-191: - $(MAKE) test-all r19=1 2>&1 |sed 's!^!1.9.1 !' -test-192: - $(MAKE) test-all r192=1 2>&1 |sed 's!^!1.9.2 !' diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/script/isolate_for_tests b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/script/isolate_for_tests deleted file mode 100755 index 6f5dced..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/script/isolate_for_tests +++ /dev/null @@ -1,31 +0,0 @@ -#!/usr/bin/env ruby -# scripts/Makefiles can read and eval the output of this script and -# use it as RUBYLIB -require 'rubygems' -require 'isolate' -fp = File.open(__FILE__, "rb") -fp.flock(File::LOCK_EX) - -ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby' -opts = { - :system => false, - # we want "ruby-1.8.7" and not "ruby-1.8", so disable :multiruby - :multiruby => false, - :path => "tmp/isolate/#{ruby_engine}-#{RUBY_VERSION}", -} - -pid = fork do - Isolate.now!(opts) do - gem 'raindrops', '0.13.0' - gem 'kgio', '2.9.2' - gem 'rack', '1.5.2' - end -end -_, status = Process.waitpid2(pid) -status.success? or abort status.inspect -lib_paths = Dir["#{opts[:path]}/gems/*-*/lib"].map { |x| File.expand_path(x) } -dst = "tmp/isolate/#{ruby_engine}-#{RUBY_VERSION}.mk" -File.open("#{dst}.#$$", "w") do |fp| - fp.puts "ISOLATE_LIBS=#{lib_paths.join(':')}" -end -File.rename("#{dst}.#$$", dst) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/setup.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/setup.rb deleted file mode 100644 index cf1abd9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/setup.rb +++ /dev/null @@ -1,1586 +0,0 @@ -# -*- encoding: binary -*- -# -# setup.rb -# -# Copyright (c) 2000-2005 Minero Aoki -# -# This program is free software. -# You can distribute/modify this program under the terms of -# the GNU LGPL, Lesser General Public License version 2.1. -# - -unless Enumerable.method_defined?(:map) # Ruby 1.4.6 - module Enumerable - alias map collect - end -end - -unless File.respond_to?(:read) # Ruby 1.6 - def File.read(fname) - open(fname) {|f| - return f.read - } - end -end - -unless Errno.const_defined?(:ENOTEMPTY) # Windows? - module Errno - class ENOTEMPTY - # We do not raise this exception, implementation is not needed. - end - end -end - -def File.binread(fname) - open(fname, 'rb') {|f| - return f.read - } -end - -# for corrupted Windows' stat(2) -def File.dir?(path) - File.directory?((path[-1,1] == '/') ? path : path + '/') -end - - -class ConfigTable - - include Enumerable - - def initialize(rbconfig) - @rbconfig = rbconfig - @items = [] - @table = {} - # options - @install_prefix = nil - @config_opt = nil - @verbose = true - @no_harm = false - end - - attr_accessor :install_prefix - attr_accessor :config_opt - - attr_writer :verbose - - def verbose? - @verbose - end - - attr_writer :no_harm - - def no_harm? - @no_harm - end - - def [](key) - lookup(key).resolve(self) - end - - def []=(key, val) - lookup(key).set val - end - - def names - @items.map {|i| i.name } - end - - def each(&block) - @items.each(&block) - end - - def key?(name) - @table.key?(name) - end - - def lookup(name) - @table[name] or setup_rb_error "no such config item: #{name}" - end - - def add(item) - @items.push item - @table[item.name] = item - end - - def remove(name) - item = lookup(name) - @items.delete_if {|i| i.name == name } - @table.delete_if {|name, i| i.name == name } - item - end - - def load_script(path, inst = nil) - if File.file?(path) - MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path - end - end - - def savefile - '.config' - end - - def load_savefile - begin - File.foreach(savefile()) do |line| - k, v = *line.split(/=/, 2) - self[k] = v.strip - end - rescue Errno::ENOENT - setup_rb_error $!.message + "\n#{File.basename($0)} config first" - end - end - - def save - @items.each {|i| i.value } - File.open(savefile(), 'w') {|f| - @items.each do |i| - f.printf "%s=%s\n", i.name, i.value if i.value? and i.value - end - } - end - - def load_standard_entries - standard_entries(@rbconfig).each do |ent| - add ent - end - end - - def standard_entries(rbconfig) - c = rbconfig - - rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) - - major = c['MAJOR'].to_i - minor = c['MINOR'].to_i - teeny = c['TEENY'].to_i - version = "#{major}.#{minor}" - - # ruby ver. >= 1.4.4? - newpath_p = ((major >= 2) or - ((major == 1) and - ((minor >= 5) or - ((minor == 4) and (teeny >= 4))))) - - if c['rubylibdir'] - # V > 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = c['rubylibdir'] - librubyverarch = c['archdir'] - siteruby = c['sitedir'] - siterubyver = c['sitelibdir'] - siterubyverarch = c['sitearchdir'] - elsif newpath_p - # 1.4.4 <= V <= 1.6.3 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = c['sitedir'] - siterubyver = "$siteruby/#{version}" - siterubyverarch = "$siterubyver/#{c['arch']}" - else - # V < 1.4.4 - libruby = "#{c['prefix']}/lib/ruby" - librubyver = "#{c['prefix']}/lib/ruby/#{version}" - librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" - siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" - siterubyver = siteruby - siterubyverarch = "$siterubyver/#{c['arch']}" - end - parameterize = lambda {|path| - path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') - } - - if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } - makeprog = arg.sub(/'/, '').split(/=/, 2)[1] - else - makeprog = 'make' - end - - [ - ExecItem.new('installdirs', 'std/site/home', - 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ - {|val, table| - case val - when 'std' - table['rbdir'] = '$librubyver' - table['sodir'] = '$librubyverarch' - when 'site' - table['rbdir'] = '$siterubyver' - table['sodir'] = '$siterubyverarch' - when 'home' - setup_rb_error '$HOME was not set' unless ENV['HOME'] - table['prefix'] = ENV['HOME'] - table['rbdir'] = '$libdir/ruby' - table['sodir'] = '$libdir/ruby' - end - }, - PathItem.new('prefix', 'path', c['prefix'], - 'path prefix of target environment'), - PathItem.new('bindir', 'path', parameterize.call(c['bindir']), - 'the directory for commands'), - PathItem.new('libdir', 'path', parameterize.call(c['libdir']), - 'the directory for libraries'), - PathItem.new('datadir', 'path', parameterize.call(c['datadir']), - 'the directory for shared data'), - PathItem.new('mandir', 'path', parameterize.call(c['mandir']), - 'the directory for man pages'), - PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), - 'the directory for system configuration files'), - PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), - 'the directory for local state data'), - PathItem.new('libruby', 'path', libruby, - 'the directory for ruby libraries'), - PathItem.new('librubyver', 'path', librubyver, - 'the directory for standard ruby libraries'), - PathItem.new('librubyverarch', 'path', librubyverarch, - 'the directory for standard ruby extensions'), - PathItem.new('siteruby', 'path', siteruby, - 'the directory for version-independent aux ruby libraries'), - PathItem.new('siterubyver', 'path', siterubyver, - 'the directory for aux ruby libraries'), - PathItem.new('siterubyverarch', 'path', siterubyverarch, - 'the directory for aux ruby binaries'), - PathItem.new('rbdir', 'path', '$siterubyver', - 'the directory for ruby scripts'), - PathItem.new('sodir', 'path', '$siterubyverarch', - 'the directory for ruby extentions'), - PathItem.new('rubypath', 'path', rubypath, - 'the path to set to #! line'), - ProgramItem.new('rubyprog', 'name', rubypath, - 'the ruby program using for installation'), - ProgramItem.new('makeprog', 'name', makeprog, - 'the make program to compile ruby extentions'), - SelectItem.new('shebang', 'all/ruby/never', 'ruby', - 'shebang line (#!) editing mode'), - BoolItem.new('without-ext', 'yes/no', 'no', - 'does not compile/install ruby extentions') - ] - end - private :standard_entries - - def load_multipackage_entries - multipackage_entries().each do |ent| - add ent - end - end - - def multipackage_entries - [ - PackageSelectionItem.new('with', 'name,name...', '', 'ALL', - 'package names that you want to install'), - PackageSelectionItem.new('without', 'name,name...', '', 'NONE', - 'package names that you do not want to install') - ] - end - private :multipackage_entries - - ALIASES = { - 'std-ruby' => 'librubyver', - 'stdruby' => 'librubyver', - 'rubylibdir' => 'librubyver', - 'archdir' => 'librubyverarch', - 'site-ruby-common' => 'siteruby', # For backward compatibility - 'site-ruby' => 'siterubyver', # For backward compatibility - 'bin-dir' => 'bindir', - 'bin-dir' => 'bindir', - 'rb-dir' => 'rbdir', - 'so-dir' => 'sodir', - 'data-dir' => 'datadir', - 'ruby-path' => 'rubypath', - 'ruby-prog' => 'rubyprog', - 'ruby' => 'rubyprog', - 'make-prog' => 'makeprog', - 'make' => 'makeprog' - } - - def fixup - ALIASES.each do |ali, name| - @table[ali] = @table[name] - end - @items.freeze - @table.freeze - @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ - end - - def parse_opt(opt) - m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" - m.to_a[1,2] - end - - def dllext - @rbconfig['DLEXT'] - end - - def value_config?(name) - lookup(name).value? - end - - class Item - def initialize(name, template, default, desc) - @name = name.freeze - @template = template - @value = default - @default = default - @description = desc - end - - attr_reader :name - attr_reader :description - - attr_accessor :default - alias help_default default - - def help_opt - "--#{@name}=#{@template}" - end - - def value? - true - end - - def value - @value - end - - def resolve(table) - @value.gsub(%r<\$([^/]+)>) { table[$1] } - end - - def set(val) - @value = check(val) - end - - private - - def check(val) - setup_rb_error "config: --#{name} requires argument" unless val - val - end - end - - class BoolItem < Item - def config_type - 'bool' - end - - def help_opt - "--#{@name}" - end - - private - - def check(val) - return 'yes' unless val - case val - when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' - when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' - else - setup_rb_error "config: --#{@name} accepts only yes/no for argument" - end - end - end - - class PathItem < Item - def config_type - 'path' - end - - private - - def check(path) - setup_rb_error "config: --#{@name} requires argument" unless path - path[0,1] == '$' ? path : File.expand_path(path) - end - end - - class ProgramItem < Item - def config_type - 'program' - end - end - - class SelectItem < Item - def initialize(name, selection, default, desc) - super - @ok = selection.split('/') - end - - def config_type - 'select' - end - - private - - def check(val) - unless @ok.include?(val.strip) - setup_rb_error "config: use --#{@name}=#{@template} (#{val})" - end - val.strip - end - end - - class ExecItem < Item - def initialize(name, selection, desc, &block) - super name, selection, nil, desc - @ok = selection.split('/') - @action = block - end - - def config_type - 'exec' - end - - def value? - false - end - - def resolve(table) - setup_rb_error "$#{name()} wrongly used as option value" - end - - undef set - - def evaluate(val, table) - v = val.strip.downcase - unless @ok.include?(v) - setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" - end - @action.call v, table - end - end - - class PackageSelectionItem < Item - def initialize(name, template, default, help_default, desc) - super name, template, default, desc - @help_default = help_default - end - - attr_reader :help_default - - def config_type - 'package' - end - - private - - def check(val) - unless File.dir?("packages/#{val}") - setup_rb_error "config: no such package: #{val}" - end - val - end - end - - class MetaConfigEnvironment - def initialize(config, installer) - @config = config - @installer = installer - end - - def config_names - @config.names - end - - def config?(name) - @config.key?(name) - end - - def bool_config?(name) - @config.lookup(name).config_type == 'bool' - end - - def path_config?(name) - @config.lookup(name).config_type == 'path' - end - - def value_config?(name) - @config.lookup(name).config_type != 'exec' - end - - def add_config(item) - @config.add item - end - - def add_bool_config(name, default, desc) - @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) - end - - def add_path_config(name, default, desc) - @config.add PathItem.new(name, 'path', default, desc) - end - - def set_config_default(name, default) - @config.lookup(name).default = default - end - - def remove_config(name) - @config.remove(name) - end - - # For only multipackage - def packages - raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer - @installer.packages - end - - # For only multipackage - def declare_packages(list) - raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer - @installer.packages = list - end - end - -end # class ConfigTable - - -# This module requires: #verbose?, #no_harm? -module FileOperations - - def mkdir_p(dirname, prefix = nil) - dirname = prefix + File.expand_path(dirname) if prefix - $stderr.puts "mkdir -p #{dirname}" if verbose? - return if no_harm? - - # Does not check '/', it's too abnormal. - dirs = File.expand_path(dirname).split(%r<(?=/)>) - if /\A[a-z]:\z/i =~ dirs[0] - disk = dirs.shift - dirs[0] = disk + dirs[0] - end - dirs.each_index do |idx| - path = dirs[0..idx].join('') - Dir.mkdir path unless File.dir?(path) - end - end - - def rm_f(path) - $stderr.puts "rm -f #{path}" if verbose? - return if no_harm? - force_remove_file path - end - - def rm_rf(path) - $stderr.puts "rm -rf #{path}" if verbose? - return if no_harm? - remove_tree path - end - - def remove_tree(path) - if File.symlink?(path) - remove_file path - elsif File.dir?(path) - remove_tree0 path - else - force_remove_file path - end - end - - def remove_tree0(path) - Dir.foreach(path) do |ent| - next if ent == '.' - next if ent == '..' - entpath = "#{path}/#{ent}" - if File.symlink?(entpath) - remove_file entpath - elsif File.dir?(entpath) - remove_tree0 entpath - else - force_remove_file entpath - end - end - begin - Dir.rmdir path - rescue Errno::ENOTEMPTY - # directory may not be empty - end - end - - def move_file(src, dest) - force_remove_file dest - begin - File.rename src, dest - rescue - File.open(dest, 'wb') {|f| - f.write File.binread(src) - } - File.chmod File.stat(src).mode, dest - File.unlink src - end - end - - def force_remove_file(path) - begin - remove_file path - rescue - end - end - - def remove_file(path) - File.chmod 0777, path - File.unlink path - end - - def install(from, dest, mode, prefix = nil) - $stderr.puts "install #{from} #{dest}" if verbose? - return if no_harm? - - realdest = prefix ? prefix + File.expand_path(dest) : dest - realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) - str = File.binread(from) - if diff?(str, realdest) - verbose_off { - rm_f realdest if File.exist?(realdest) - } - File.open(realdest, 'wb') {|f| - f.write str - } - File.chmod mode, realdest - - File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| - if prefix - f.puts realdest.sub(prefix, '') - else - f.puts realdest - end - } - end - end - - def diff?(new_content, path) - return true unless File.exist?(path) - new_content != File.binread(path) - end - - def command(*args) - $stderr.puts args.join(' ') if verbose? - system(*args) or raise RuntimeError, - "system(#{args.map{|a| a.inspect }.join(' ')}) failed" - end - - def ruby(*args) - command config('rubyprog'), *args - end - - def make(task = nil) - command(*[config('makeprog'), task].compact) - end - - def extdir?(dir) - File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") - end - - def files_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.file?("#{dir}/#{ent}") } - } - end - - DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) - - def directories_of(dir) - Dir.open(dir) {|d| - return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT - } - end - -end - - -# This module requires: #srcdir_root, #objdir_root, #relpath -module HookScriptAPI - - def get_config(key) - @config[key] - end - - alias config get_config - - # obsolete: use metaconfig to change configuration - def set_config(key, val) - @config[key] = val - end - - # - # srcdir/objdir (works only in the package directory) - # - - def curr_srcdir - "#{srcdir_root()}/#{relpath()}" - end - - def curr_objdir - "#{objdir_root()}/#{relpath()}" - end - - def srcfile(path) - "#{curr_srcdir()}/#{path}" - end - - def srcexist?(path) - File.exist?(srcfile(path)) - end - - def srcdirectory?(path) - File.dir?(srcfile(path)) - end - - def srcfile?(path) - File.file?(srcfile(path)) - end - - def srcentries(path = '.') - Dir.open("#{curr_srcdir()}/#{path}") {|d| - return d.to_a - %w(. ..) - } - end - - def srcfiles(path = '.') - srcentries(path).select {|fname| - File.file?(File.join(curr_srcdir(), path, fname)) - } - end - - def srcdirectories(path = '.') - srcentries(path).select {|fname| - File.dir?(File.join(curr_srcdir(), path, fname)) - } - end - -end - - -class ToplevelInstaller - - Version = '3.4.1' - Copyright = 'Copyright (c) 2000-2005 Minero Aoki' - - TASKS = [ - [ 'all', 'do config, setup, then install' ], - [ 'config', 'saves your configurations' ], - [ 'show', 'shows current configuration' ], - [ 'setup', 'compiles ruby extentions and others' ], - [ 'install', 'installs files' ], - [ 'test', 'run all tests in test/' ], - [ 'clean', "does `make clean' for each extention" ], - [ 'distclean',"does `make distclean' for each extention" ] - ] - - def ToplevelInstaller.invoke - config = ConfigTable.new(load_rbconfig()) - config.load_standard_entries - config.load_multipackage_entries if multipackage? - config.fixup - klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) - klass.new(File.dirname($0), config).invoke - end - - def ToplevelInstaller.multipackage? - File.dir?(File.dirname($0) + '/packages') - end - - def ToplevelInstaller.load_rbconfig - if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } - ARGV.delete(arg) - load File.expand_path(arg.split(/=/, 2)[1]) - $".push 'rbconfig.rb' - else - require 'rbconfig' - end - ::Config::CONFIG - end - - def initialize(ardir_root, config) - @ardir = File.expand_path(ardir_root) - @config = config - # cache - @valid_task_re = nil - end - - def config(key) - @config[key] - end - - def inspect - "#<#{self.class} #{__id__()}>" - end - - def invoke - run_metaconfigs - case task = parsearg_global() - when nil, 'all' - parsearg_config - init_installers - exec_config - exec_setup - exec_install - else - case task - when 'config', 'test' - ; - when 'clean', 'distclean' - @config.load_savefile if File.exist?(@config.savefile) - else - @config.load_savefile - end - __send__ "parsearg_#{task}" - init_installers - __send__ "exec_#{task}" - end - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig" - end - - def init_installers - @installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - # - # Hook Script API bases - # - - def srcdir_root - @ardir - end - - def objdir_root - '.' - end - - def relpath - '.' - end - - # - # Option Parsing - # - - def parsearg_global - while arg = ARGV.shift - case arg - when /\A\w+\z/ - setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) - return arg - when '-q', '--quiet' - @config.verbose = false - when '--verbose' - @config.verbose = true - when '--help' - print_usage $stdout - exit 0 - when '--version' - puts "#{File.basename($0)} version #{Version}" - exit 0 - when '--copyright' - puts Copyright - exit 0 - else - setup_rb_error "unknown global option '#{arg}'" - end - end - nil - end - - def valid_task?(t) - valid_task_re() =~ t - end - - def valid_task_re - @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ - end - - def parsearg_no_options - unless ARGV.empty? - task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) - setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" - end - end - - alias parsearg_show parsearg_no_options - alias parsearg_setup parsearg_no_options - alias parsearg_test parsearg_no_options - alias parsearg_clean parsearg_no_options - alias parsearg_distclean parsearg_no_options - - def parsearg_config - evalopt = [] - set = [] - @config.config_opt = [] - while i = ARGV.shift - if /\A--?\z/ =~ i - @config.config_opt = ARGV.dup - break - end - name, value = *@config.parse_opt(i) - if @config.value_config?(name) - @config[name] = value - else - evalopt.push [name, value] - end - set.push name - end - evalopt.each do |name, value| - @config.lookup(name).evaluate value, @config - end - # Check if configuration is valid - set.each do |n| - @config[n] if @config.value_config?(n) - end - end - - def parsearg_install - @config.no_harm = false - @config.install_prefix = '' - while a = ARGV.shift - case a - when '--no-harm' - @config.no_harm = true - when /\A--prefix=/ - path = a.split(/=/, 2)[1] - path = File.expand_path(path) unless path[0,1] == '/' - @config.install_prefix = path - else - setup_rb_error "install: unknown option #{a}" - end - end - end - - def print_usage(out) - out.puts 'Typical Installation Procedure:' - out.puts " $ ruby #{File.basename $0} config" - out.puts " $ ruby #{File.basename $0} setup" - out.puts " # ruby #{File.basename $0} install (may require root privilege)" - out.puts - out.puts 'Detailed Usage:' - out.puts " ruby #{File.basename $0} " - out.puts " ruby #{File.basename $0} [] []" - - fmt = " %-24s %s\n" - out.puts - out.puts 'Global options:' - out.printf fmt, '-q,--quiet', 'suppress message outputs' - out.printf fmt, ' --verbose', 'output messages verbosely' - out.printf fmt, ' --help', 'print this message' - out.printf fmt, ' --version', 'print version and quit' - out.printf fmt, ' --copyright', 'print copyright and quit' - out.puts - out.puts 'Tasks:' - TASKS.each do |name, desc| - out.printf fmt, name, desc - end - - fmt = " %-24s %s [%s]\n" - out.puts - out.puts 'Options for CONFIG or ALL:' - @config.each do |item| - out.printf fmt, item.help_opt, item.description, item.help_default - end - out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" - out.puts - out.puts 'Options for INSTALL:' - out.printf fmt, '--no-harm', 'only display what to do if given', 'off' - out.printf fmt, '--prefix=path', 'install path prefix', '' - out.puts - end - - # - # Task Handlers - # - - def exec_config - @installer.exec_config - @config.save # must be final - end - - def exec_setup - @installer.exec_setup - end - - def exec_install - @installer.exec_install - end - - def exec_test - @installer.exec_test - end - - def exec_show - @config.each do |i| - printf "%-20s %s\n", i.name, i.value if i.value? - end - end - - def exec_clean - @installer.exec_clean - end - - def exec_distclean - @installer.exec_distclean - end - -end # class ToplevelInstaller - - -class ToplevelInstallerMulti < ToplevelInstaller - - include FileOperations - - def initialize(ardir_root, config) - super - @packages = directories_of("#{@ardir}/packages") - raise 'no package exists' if @packages.empty? - @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) - end - - def run_metaconfigs - @config.load_script "#{@ardir}/metaconfig", self - @packages.each do |name| - @config.load_script "#{@ardir}/packages/#{name}/metaconfig" - end - end - - attr_reader :packages - - def packages=(list) - raise 'package list is empty' if list.empty? - list.each do |name| - raise "directory packages/#{name} does not exist"\ - unless File.dir?("#{@ardir}/packages/#{name}") - end - @packages = list - end - - def init_installers - @installers = {} - @packages.each do |pack| - @installers[pack] = Installer.new(@config, - "#{@ardir}/packages/#{pack}", - "packages/#{pack}") - end - with = extract_selection(config('with')) - without = extract_selection(config('without')) - @selected = @installers.keys.select {|name| - (with.empty? or with.include?(name)) \ - and not without.include?(name) - } - end - - def extract_selection(list) - a = list.split(/,/) - a.each do |name| - setup_rb_error "no such package: #{name}" unless @installers.key?(name) - end - a - end - - def print_usage(f) - super - f.puts 'Inluded packages:' - f.puts ' ' + @packages.sort.join(' ') - f.puts - end - - # - # Task Handlers - # - - def exec_config - run_hook 'pre-config' - each_selected_installers {|inst| inst.exec_config } - run_hook 'post-config' - @config.save # must be final - end - - def exec_setup - run_hook 'pre-setup' - each_selected_installers {|inst| inst.exec_setup } - run_hook 'post-setup' - end - - def exec_install - run_hook 'pre-install' - each_selected_installers {|inst| inst.exec_install } - run_hook 'post-install' - end - - def exec_test - run_hook 'pre-test' - each_selected_installers {|inst| inst.exec_test } - run_hook 'post-test' - end - - def exec_clean - rm_f @config.savefile - run_hook 'pre-clean' - each_selected_installers {|inst| inst.exec_clean } - run_hook 'post-clean' - end - - def exec_distclean - rm_f @config.savefile - run_hook 'pre-distclean' - each_selected_installers {|inst| inst.exec_distclean } - run_hook 'post-distclean' - end - - # - # lib - # - - def each_selected_installers - Dir.mkdir 'packages' unless File.dir?('packages') - @selected.each do |pack| - $stderr.puts "Processing the package `#{pack}' ..." if verbose? - Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") - Dir.chdir "packages/#{pack}" - yield @installers[pack] - Dir.chdir '../..' - end - end - - def run_hook(id) - @root_installer.run_hook id - end - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - -end # class ToplevelInstallerMulti - - -class Installer - - FILETYPES = %w( bin lib ext data conf man ) - - include FileOperations - include HookScriptAPI - - def initialize(config, srcroot, objroot) - @config = config - @srcdir = File.expand_path(srcroot) - @objdir = File.expand_path(objroot) - @currdir = '.' - end - - def inspect - "#<#{self.class} #{File.basename(@srcdir)}>" - end - - def noop(rel) - end - - # - # Hook Script API base methods - # - - def srcdir_root - @srcdir - end - - def objdir_root - @objdir - end - - def relpath - @currdir - end - - # - # Config Access - # - - # module FileOperations requires this - def verbose? - @config.verbose? - end - - # module FileOperations requires this - def no_harm? - @config.no_harm? - end - - def verbose_off - begin - save, @config.verbose = @config.verbose?, false - yield - ensure - @config.verbose = save - end - end - - # - # TASK config - # - - def exec_config - exec_task_traverse 'config' - end - - alias config_dir_bin noop - alias config_dir_lib noop - - def config_dir_ext(rel) - extconf if extdir?(curr_srcdir()) - end - - alias config_dir_data noop - alias config_dir_conf noop - alias config_dir_man noop - - def extconf - ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt - end - - # - # TASK setup - # - - def exec_setup - exec_task_traverse 'setup' - end - - def setup_dir_bin(rel) - files_of(curr_srcdir()).each do |fname| - update_shebang_line "#{curr_srcdir()}/#{fname}" - end - end - - alias setup_dir_lib noop - - def setup_dir_ext(rel) - make if extdir?(curr_srcdir()) - end - - alias setup_dir_data noop - alias setup_dir_conf noop - alias setup_dir_man noop - - def update_shebang_line(path) - return if no_harm? - return if config('shebang') == 'never' - old = Shebang.load(path) - if old - $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 - new = new_shebang(old) - return if new.to_s == old.to_s - else - return unless config('shebang') == 'all' - new = Shebang.new(config('rubypath')) - end - $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? - open_atomic_writer(path) {|output| - File.open(path, 'rb') {|f| - f.gets if old # discard - output.puts new.to_s - output.print f.read - } - } - end - - def new_shebang(old) - if /\Aruby/ =~ File.basename(old.cmd) - Shebang.new(config('rubypath'), old.args) - elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' - Shebang.new(config('rubypath'), old.args[1..-1]) - else - return old unless config('shebang') == 'all' - Shebang.new(config('rubypath')) - end - end - - def open_atomic_writer(path, &block) - tmpfile = File.basename(path) + '.tmp' - begin - File.open(tmpfile, 'wb', &block) - File.rename tmpfile, File.basename(path) - ensure - File.unlink tmpfile if File.exist?(tmpfile) - end - end - - class Shebang - def Shebang.load(path) - line = nil - File.open(path) {|f| - line = f.gets - } - return nil unless /\A#!/ =~ line - parse(line) - end - - def Shebang.parse(line) - cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') - new(cmd, args) - end - - def initialize(cmd, args = []) - @cmd = cmd - @args = args - end - - attr_reader :cmd - attr_reader :args - - def to_s - "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") - end - end - - # - # TASK install - # - - def exec_install - rm_f 'InstalledFiles' - exec_task_traverse 'install' - end - - def install_dir_bin(rel) - install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 - end - - def install_dir_lib(rel) - install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 - end - - def install_dir_ext(rel) - return unless extdir?(curr_srcdir()) - install_files rubyextentions('.'), - "#{config('sodir')}/#{File.dirname(rel)}", - 0555 - end - - def install_dir_data(rel) - install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 - end - - def install_dir_conf(rel) - # FIXME: should not remove current config files - # (rename previous file to .old/.org) - install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 - end - - def install_dir_man(rel) - install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 - end - - def install_files(list, dest, mode) - mkdir_p dest, @config.install_prefix - list.each do |fname| - install fname, dest, mode, @config.install_prefix - end - end - - def libfiles - glob_reject(%w(*.y *.output), targetfiles()) - end - - def rubyextentions(dir) - ents = glob_select("*.#{@config.dllext}", targetfiles()) - if ents.empty? - setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" - end - ents - end - - def targetfiles - mapdir(existfiles() - hookfiles()) - end - - def mapdir(ents) - ents.map {|ent| - if File.exist?(ent) - then ent # objdir - else "#{curr_srcdir()}/#{ent}" # srcdir - end - } - end - - # picked up many entries from cvs-1.11.1/src/ignore.c - JUNK_FILES = %w( - core RCSLOG tags TAGS .make.state - .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb - *~ *.old *.bak *.BAK *.orig *.rej _$* *$ - - *.org *.in .* - ) - - def existfiles - glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) - end - - def hookfiles - %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt| - %w( config setup install clean ).map {|t| sprintf(fmt, t) } - }.flatten - end - - def glob_select(pat, ents) - re = globs2re([pat]) - ents.select {|ent| re =~ ent } - end - - def glob_reject(pats, ents) - re = globs2re(pats) - ents.reject {|ent| re =~ ent } - end - - GLOB2REGEX = { - '.' => '\.', - '$' => '\$', - '#' => '\#', - '*' => '.*' - } - - def globs2re(pats) - /\A(?:#{ - pats.map {|pat| pat.gsub(/[\.\$\#\*]/) {|ch| GLOB2REGEX[ch] } }.join('|') - })\z/ - end - - # - # TASK test - # - - TESTDIR = 'test' - - def exec_test - unless File.directory?('test') - $stderr.puts 'no test in this package' if verbose? - return - end - $stderr.puts 'Running tests...' if verbose? - begin - require 'test/unit' - rescue LoadError - setup_rb_error 'test/unit cannot loaded. You need Ruby 1.8 or later to invoke this task.' - end - runner = Test::Unit::AutoRunner.new(true) - runner.to_run << TESTDIR - runner.run - end - - # - # TASK clean - # - - def exec_clean - exec_task_traverse 'clean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias clean_dir_bin noop - alias clean_dir_lib noop - alias clean_dir_data noop - alias clean_dir_conf noop - alias clean_dir_man noop - - def clean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'clean' if File.file?('Makefile') - end - - # - # TASK distclean - # - - def exec_distclean - exec_task_traverse 'distclean' - rm_f @config.savefile - rm_f 'InstalledFiles' - end - - alias distclean_dir_bin noop - alias distclean_dir_lib noop - - def distclean_dir_ext(rel) - return unless extdir?(curr_srcdir()) - make 'distclean' if File.file?('Makefile') - end - - alias distclean_dir_data noop - alias distclean_dir_conf noop - alias distclean_dir_man noop - - # - # Traversing - # - - def exec_task_traverse(task) - run_hook "pre-#{task}" - FILETYPES.each do |type| - if type == 'ext' and config('without-ext') == 'yes' - $stderr.puts 'skipping ext/* by user option' if verbose? - next - end - traverse task, type, "#{task}_dir_#{type}" - end - run_hook "post-#{task}" - end - - def traverse(task, rel, mid) - dive_into(rel) { - run_hook "pre-#{task}" - __send__ mid, rel.sub(%r[\A.*?(?:/|\z)], '') - directories_of(curr_srcdir()).each do |d| - traverse task, "#{rel}/#{d}", mid - end - run_hook "post-#{task}" - } - end - - def dive_into(rel) - return unless File.dir?("#{@srcdir}/#{rel}") - - dir = File.basename(rel) - Dir.mkdir dir unless File.dir?(dir) - prevdir = Dir.pwd - Dir.chdir dir - $stderr.puts '---> ' + rel if verbose? - @currdir = rel - yield - Dir.chdir prevdir - $stderr.puts '<--- ' + rel if verbose? - @currdir = File.dirname(rel) - end - - def run_hook(id) - path = [ "#{curr_srcdir()}/#{id}", - "#{curr_srcdir()}/#{id}.rb" ].detect {|cand| File.file?(cand) } - return unless path - begin - instance_eval File.read(path), path, 1 - rescue - raise if $DEBUG - setup_rb_error "hook #{path} failed:\n" + $!.message - end - end - -end # class Installer - - -class SetupError < StandardError; end - -def setup_rb_error(msg) - raise SetupError, msg -end - -if $0 == __FILE__ - begin - ToplevelInstaller.invoke - rescue SetupError - raise if $DEBUG - $stderr.puts $!.message - $stderr.puts "Try 'ruby #{$0} --help' for detailed usage." - exit 1 - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/.gitignore b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/.gitignore deleted file mode 100644 index 2312321..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/random_blob -/.dep+* -/*.crt -/*.key diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/GNUmakefile b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/GNUmakefile deleted file mode 100644 index 8f2668c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/GNUmakefile +++ /dev/null @@ -1,78 +0,0 @@ -# we can run tests in parallel with GNU make -all:: - -pid := $(shell echo $$PPID) - -RUBY = ruby -RAKE = rake --include ../local.mk -ifeq ($(RUBY_VERSION),) - RUBY_VERSION := $(shell $(RUBY) -e 'puts RUBY_VERSION') -endif - -ifeq ($(RUBY_VERSION),) - $(error unable to detect RUBY_VERSION) -endif - -RUBY_ENGINE := $(shell $(RUBY) -e 'puts((RUBY_ENGINE rescue "ruby"))') -export RUBY_ENGINE - -isolate_libs := ../tmp/isolate/$(RUBY_ENGINE)-$(RUBY_VERSION).mk -$(isolate_libs): ../script/isolate_for_tests - @cd .. && $(RUBY) script/isolate_for_tests --include $(isolate_libs) -MYLIBS := $(RUBYLIB):$(ISOLATE_LIBS) - -T = $(wildcard t[0-9][0-9][0-9][0-9]-*.sh) - -all:: $(T) - -# can't rely on "set -o pipefail" since we don't require bash or ksh93 :< -t_pfx = trash/$@-$(RUBY_ENGINE)-$(RUBY_VERSION) -TEST_OPTS = -# TRACER = strace -f -o $(t_pfx).strace -s 100000 -# TRACER = /usr/bin/time -o $(t_pfx).time - -ifdef V - ifeq ($(V),2) - TEST_OPTS += --trace - else - TEST_OPTS += --verbose - endif -endif - -random_blob: - dd if=/dev/urandom bs=1M count=30 of=$@.$(pid) - mv $@.$(pid) $@ - -$(T): random_blob - -dependencies := socat curl -deps := $(addprefix .dep+,$(dependencies)) -$(deps): dep_bin = $(lastword $(subst +, ,$@)) -$(deps): - @which $(dep_bin) > $@.$(pid) 2>/dev/null || : - @test -s $@.$(pid) || \ - { echo >&2 "E '$(dep_bin)' not found in PATH=$(PATH)"; exit 1; } - @mv $@.$(pid) $@ -dep: $(deps) - -test_prefix := $(CURDIR)/../test/$(RUBY_ENGINE)-$(RUBY_VERSION) -$(test_prefix)/.stamp: - $(MAKE) -C .. test-install - -$(T): export RUBY := $(RUBY) -$(T): export RAKE := $(RAKE) -$(T): export PATH := $(test_prefix)/bin:$(PATH) -$(T): export RUBYLIB := $(test_prefix)/lib:$(MYLIBS) -$(T): dep $(test_prefix)/.stamp trash/.gitignore - $(TRACER) $(SHELL) $(SH_TEST_OPTS) $@ $(TEST_OPTS) - -trash/.gitignore: - mkdir -p $(@D) - echo '*' > $@ - -clean: - $(RM) -r trash/* - -.PHONY: $(T) clean diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/README b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/README deleted file mode 100644 index 095f106..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/README +++ /dev/null @@ -1,42 +0,0 @@ -= Unicorn integration test suite - -These are all integration tests that start the server on random, unused -TCP ports or Unix domain sockets. They're all designed to run -concurrently with other tests to minimize test time, but tests may be -run independently as well. - -We write our tests in Bourne shell because that's what we're -comfortable writing integration tests with. - -== Requirements - -* {Ruby 1.8 or 1.9}[http://www.ruby-lang.org/] (duh!) -* {GNU make}[http://www.gnu.org/software/make/] -* {socat}[http://www.dest-unreach.org/socat/] -* {curl}[http://curl.haxx.se/] -* standard UNIX shell utilities (Bourne sh, awk, sed, grep, ...) - -We do not use bashisms or any non-portable, non-POSIX constructs -in our shell code. We use the "pipefail" option if available and -mainly test with {ksh}[http://kornshell.com/], but occasionally -with {dash}[http://gondor.apana.org.au/~herbert/dash/] and -{bash}[http://www.gnu.org/software/bash/], too. - -== Running Tests - -To run the entire test suite with 8 tests running at once: - - make -j8 - -To run one individual test: - - make t0000-simple-http.sh - -You may also increase verbosity by setting the "V" variable for -GNU make. To disable trapping of stdout/stderr: - - make V=1 - -To enable the "set -x" option in shell scripts to trace execution - - make V=2 diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/content-md5-put b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/content-md5-put deleted file mode 100755 index 01da0bb..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/content-md5-put +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env ruby -# -*- encoding: binary -*- -# simple chunked HTTP PUT request generator (and just that), -# it reads stdin and writes to stdout so socat can write to a -# UNIX or TCP socket (or to another filter or file) along with -# a Content-MD5 trailer. -require 'digest/md5' -$stdout.sync = $stderr.sync = true -$stdout.binmode -$stdin.binmode - -bs = ENV['bs'] ? ENV['bs'].to_i : 4096 - -if ARGV.grep("--no-headers").empty? - $stdout.write( - "PUT / HTTP/1.1\r\n" \ - "Host: example.com\r\n" \ - "Transfer-Encoding: chunked\r\n" \ - "Trailer: Content-MD5\r\n" \ - "\r\n" - ) -end - -digest = Digest::MD5.new -if buf = $stdin.readpartial(bs) - begin - digest.update(buf) - $stdout.write("%x\r\n" % [ buf.size ]) - $stdout.write(buf) - $stdout.write("\r\n") - end while $stdin.read(bs, buf) -end - -digest = [ digest.digest ].pack('m').strip -$stdout.write("0\r\n") -$stdout.write("Content-MD5: #{digest}\r\n\r\n") diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/sha1sum.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/sha1sum.rb deleted file mode 100755 index 53d68ce..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/sha1sum.rb +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env ruby -# -*- encoding: binary -*- -# Reads from stdin and outputs the SHA1 hex digest of the input - -require 'digest/sha1' -$stdout.sync = $stderr.sync = true -$stdout.binmode -$stdin.binmode -bs = 16384 -digest = Digest::SHA1.new -if buf = $stdin.read(bs) - begin - digest.update(buf) - end while $stdin.read(bs, buf) -end - -$stdout.syswrite("#{digest.hexdigest}\n") diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/unused_listen b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/unused_listen deleted file mode 100755 index b638f54..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/bin/unused_listen +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env ruby -# -*- encoding: binary -*- -# this is to remain compatible with the unused_port function in the -# Unicorn test/test_helper.rb file -require 'socket' -require 'tmpdir' - -default_port = 8080 -addr = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' -retries = 100 -base = 5000 -port = sock = lock_path = nil - -begin - begin - port = base + rand(32768 - base) - while port == default_port - port = base + rand(32768 - base) - end - - sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) - sock.bind(Socket.pack_sockaddr_in(port, addr)) - sock.listen(5) - rescue Errno::EADDRINUSE, Errno::EACCES - sock.close rescue nil - retry if (retries -= 1) >= 0 - end - - # since we'll end up closing the random port we just got, there's a race - # condition could allow the random port we just chose to reselect itself - # when running tests in parallel with gmake. Create a lock file while - # we have the port here to ensure that does not happen. - lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock" - lock = File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600) -rescue Errno::EEXIST - sock.close rescue nil - retry -end -sock.close rescue nil -puts %Q(listen=#{addr}:#{port} T_RM_LIST="$T_RM_LIST #{lock_path}") diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/broken-app.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/broken-app.ru deleted file mode 100644 index d05d7ab..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/broken-app.ru +++ /dev/null @@ -1,12 +0,0 @@ -# we do not want Rack::Lint or anything to protect us -use Rack::ContentLength -use Rack::ContentType, "text/plain" -map "/" do - run lambda { |env| [ 200, {}, [ "OK\n" ] ] } -end -map "/raise" do - run lambda { |env| raise "BAD" } -end -map "/nil" do - run lambda { |env| nil } -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/detach.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/detach.ru deleted file mode 100644 index bbd998e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/detach.ru +++ /dev/null @@ -1,11 +0,0 @@ -use Rack::ContentType, "text/plain" -fifo_path = ENV["TEST_FIFO"] or abort "TEST_FIFO not set" -run lambda { |env| - pid = fork do - File.open(fifo_path, "wb") do |fp| - fp.write "HIHI" - end - end - Process.detach(pid) - [ 200, {}, [ pid.to_s ] ] -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/env.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/env.ru deleted file mode 100644 index 388412e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/env.ru +++ /dev/null @@ -1,3 +0,0 @@ -use Rack::ContentLength -use Rack::ContentType, "text/plain" -run lambda { |env| [ 200, {}, [ env.inspect << "\n" ] ] } diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/fails-rack-lint.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/fails-rack-lint.ru deleted file mode 100644 index 82bfb5f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/fails-rack-lint.ru +++ /dev/null @@ -1,5 +0,0 @@ -# This rack app returns an invalid status code, which will cause -# Rack::Lint to throw an exception if it is present. This -# is used to check whether Rack::Lint is in the stack or not. - -run lambda {|env| return [42, {}, ["Rack::Lint wasn't there if you see this"]]} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/heartbeat-timeout.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/heartbeat-timeout.ru deleted file mode 100644 index d9904e8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/heartbeat-timeout.ru +++ /dev/null @@ -1,12 +0,0 @@ -use Rack::ContentLength -headers = { 'Content-Type' => 'text/plain' } -run lambda { |env| - case env['PATH_INFO'] - when "/block-forever" - Process.kill(:STOP, $$) - sleep # in case STOP signal is not received in time - [ 500, headers, [ "Should never get here\n" ] ] - else - [ 200, headers, [ "#$$\n" ] ] - end -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/hijack.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/hijack.ru deleted file mode 100644 index fcb0b6d..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/hijack.ru +++ /dev/null @@ -1,42 +0,0 @@ -use Rack::Lint -use Rack::ContentLength -use Rack::ContentType, "text/plain" -class DieIfUsed - def each - abort "body.each called after response hijack\n" - end - - def close - abort "body.close called after response hijack\n" - end -end -run lambda { |env| - case env["PATH_INFO"] - when "/hijack_req" - if env["rack.hijack?"] - io = env["rack.hijack"].call - if io.respond_to?(:read_nonblock) && - env["rack.hijack_io"].respond_to?(:read_nonblock) - - # exercise both, since we Rack::Lint may use different objects - env["rack.hijack_io"].write("HTTP/1.0 200 OK\r\n\r\n") - io.write("request.hijacked") - io.close - return [ 500, {}, DieIfUsed.new ] - end - end - [ 500, {}, [ "hijack BAD\n" ] ] - when "/hijack_res" - r = "response.hijacked" - [ 200, - { - "Content-Length" => r.bytesize.to_s, - "rack.hijack" => proc do |io| - io.write(r) - io.close - end - }, - DieIfUsed.new - ] - end -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/listener_names.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/listener_names.ru deleted file mode 100644 index edb4e6a..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/listener_names.ru +++ /dev/null @@ -1,4 +0,0 @@ -use Rack::ContentLength -use Rack::ContentType, "text/plain" -names = Unicorn.listener_names.inspect # rely on preload_app=true -run(lambda { |_| [ 200, {}, [ names ] ] }) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/my-tap-lib.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/my-tap-lib.sh deleted file mode 100644 index eced1e0..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/my-tap-lib.sh +++ /dev/null @@ -1,201 +0,0 @@ -#!/bin/sh -# Copyright (c) 2009, 2010 Eric Wong -# -# TAP-producing shell library for POSIX-compliant Bourne shells We do -# not _rely_ on Bourne Again features, though we will use "set -o -# pipefail" from ksh93 or bash 3 if available -# -# Only generic, non-project/non-language-specific stuff goes here. We -# only have POSIX dependencies for the core tests (without --verbose), -# though we'll enable useful non-POSIX things if they're available. -# -# This test library is intentionally unforgiving, it does not support -# skipping tests nor continuing after any failure. Any failures -# immediately halt execution as do any references to undefined -# variables. -# -# When --verbose is specified, we always prefix stdout/stderr -# output with "#" to avoid confusing TAP consumers. Otherwise -# the normal stdout/stderr streams are redirected to /dev/null - -# dup normal stdout(fd=1) and stderr (fd=2) to fd=3 and fd=4 respectively -# normal TAP output goes to fd=3, nothing should go to fd=4 -exec 3>&1 4>&2 - -# ensure a sane environment -TZ=UTC LC_ALL=C LANG=C -export LANG LC_ALL TZ -unset CDPATH - -# pipefail is non-POSIX, but very useful in ksh93/bash -( set -o pipefail 2>/dev/null ) && set -o pipefail - -SED=${SED-sed} - -# Unlike other test frameworks, we are unforgiving and bail immediately -# on any failures. We do this because we're lazy about error handling -# and also because we believe anything broken should not be allowed to -# propagate throughout the rest of the test -set -e -set -u - -# name of our test -T=${0##*/} - -t_expect_nr=-1 -t_nr=0 -t_current= -t_complete=false - -# list of files to remove unconditionally on exit -T_RM_LIST= - -# list of files to remove only on successful exit -T_OK_RM_LIST= - -# emit output to stdout, it'll be parsed by the TAP consumer -# so it must be TAP-compliant output -t_echo () { - echo >&3 "$@" -} - -# emits non-parsed information to stdout, it will be prefixed with a '#' -# to not throw off TAP consumers -t_info () { - t_echo '#' "$@" -} - -# exit with an error and print a diagnostic -die () { - echo >&2 "$@" - exit 1 -} - -# our at_exit handler, it'll fire for all exits except SIGKILL (unavoidable) -t_at_exit () { - code=$? - set +e - if test $code -eq 0 - then - $t_complete || { - t_info "t_done not called" - code=1 - } - elif test -n "$t_current" - then - t_echo "not ok $t_nr - $t_current" - fi - if test $t_expect_nr -ne -1 - then - test $t_expect_nr -eq $t_nr || { - t_info "planned $t_expect_nr tests but ran $t_nr" - test $code -ne 0 || code=1 - } - fi - $t_complete || { - t_info "unexpected test failure" - test $code -ne 0 || code=1 - } - rm -f $T_RM_LIST - test $code -eq 0 && rm -f $T_OK_RM_LIST - set +x - exec >&3 2>&4 - t_close_fds - exit $code -} - -# close test-specific extra file descriptors -t_close_fds () { - exec 3>&- 4>&- -} - -# call this at the start of your test to specify the number of tests -# you plan to run -t_plan () { - test "$1" -ge 1 || die "must plan at least one test" - test $t_expect_nr -eq -1 || die "tried to plan twice in one test" - t_expect_nr=$1 - shift - t_echo 1..$t_expect_nr "#" "$@" - trap t_at_exit EXIT -} - -_t_checkup () { - test $t_expect_nr -le 0 && die "no tests planned" - test -n "$t_current" && t_echo "ok $t_nr - $t_current" - true -} - -# finalizes any previously test and starts a new one -t_begin () { - _t_checkup - t_nr=$(( $t_nr + 1 )) - t_current="$1" - - # just in case somebody wanted to cheat us: - set -e -} - -# finalizes the current test without starting a new one -t_end () { - _t_checkup - t_current= -} - -# run this to signify the end of your test -t_done () { - _t_checkup - t_current= - t_complete=true - test $t_expect_nr -eq $t_nr || exit 1 - exit 0 -} - -# create and assign named-pipes to variable _names_ passed to this function -t_fifos () { - for _id in "$@" - do - _name=$_id - _tmp=$(mktemp -t $T.$$.$_id.XXXXXXXX) - eval "$_id=$_tmp" - rm -f $_tmp - mkfifo $_tmp - T_RM_LIST="$T_RM_LIST $_tmp" - done -} - -t_verbose=false t_trace=false - -while test "$#" -ne 0 -do - arg="$1" - shift - case $arg in - -v|--verbose) t_verbose=true ;; - --trace) t_trace=true t_verbose=true ;; - *) die "Unknown option: $arg" ;; - esac -done - -# we always only setup stdout, nothing should end up in the "real" stderr -if $t_verbose -then - if test x"$(which mktemp 2>/dev/null)" = x - then - die "mktemp(1) not available for --verbose" - fi - t_fifos t_stdout t_stderr - - ( - # use a subshell so seds are not waitable - $SED -e 's/^/#: /' < $t_stdout & - $SED -e 's/^/#! /' < $t_stderr & - ) & - wait - exec > $t_stdout 2> $t_stderr -else - exec > /dev/null 2> /dev/null -fi - -$t_trace && set -x -true diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/oob_gc.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/oob_gc.ru deleted file mode 100644 index c253540..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/oob_gc.ru +++ /dev/null @@ -1,20 +0,0 @@ -#\-E none -require 'unicorn/oob_gc' -use Rack::ContentLength -use Rack::ContentType, "text/plain" -use Unicorn::OobGC -$gc_started = false - -# Mock GC.start -def GC.start - ObjectSpace.each_object(Kgio::Socket) do |x| - x.closed? or abort "not closed #{x}" - end - $gc_started = true -end -run lambda { |env| - if "/gc_reset" == env["PATH_INFO"] && "POST" == env["REQUEST_METHOD"] - $gc_started = false - end - [ 200, {}, [ "#$gc_started\n" ] ] -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/oob_gc_path.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/oob_gc_path.ru deleted file mode 100644 index af8e3b9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/oob_gc_path.ru +++ /dev/null @@ -1,20 +0,0 @@ -#\-E none -require 'unicorn/oob_gc' -use Rack::ContentLength -use Rack::ContentType, "text/plain" -use Unicorn::OobGC, 5, /BAD/ -$gc_started = false - -# Mock GC.start -def GC.start - ObjectSpace.each_object(Kgio::Socket) do |x| - x.closed? or abort "not closed #{x}" - end - $gc_started = true -end -run lambda { |env| - if "/gc_reset" == env["PATH_INFO"] && "POST" == env["REQUEST_METHOD"] - $gc_started = false - end - [ 200, {}, [ "#$gc_started\n" ] ] -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/pid.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/pid.ru deleted file mode 100644 index f5fd31f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/pid.ru +++ /dev/null @@ -1,3 +0,0 @@ -use Rack::ContentLength -use Rack::ContentType, "text/plain" -run lambda { |env| [ 200, {}, [ "#$$\n" ] ] } diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/preread_input.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/preread_input.ru deleted file mode 100644 index 79685c4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/preread_input.ru +++ /dev/null @@ -1,17 +0,0 @@ -#\-E none -require 'digest/sha1' -require 'unicorn/preread_input' -use Rack::ContentLength -use Rack::ContentType, "text/plain" -use Unicorn::PrereadInput -nr = 0 -run lambda { |env| - $stderr.write "app dispatch: #{nr += 1}\n" - input = env["rack.input"] - dig = Digest::SHA1.new - while buf = input.read(16384) - dig.update(buf) - end - - [ 200, {}, [ "#{dig.hexdigest}\n" ] ] -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/rack-input-tests.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/rack-input-tests.ru deleted file mode 100644 index 8c35630..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/rack-input-tests.ru +++ /dev/null @@ -1,21 +0,0 @@ -# SHA1 checksum generator -require 'digest/sha1' -use Rack::ContentLength -cap = 16384 -app = lambda do |env| - /\A100-continue\z/i =~ env['HTTP_EXPECT'] and - return [ 100, {}, [] ] - digest = Digest::SHA1.new - input = env['rack.input'] - input.size if env["PATH_INFO"] == "/size_first" - input.rewind if env["PATH_INFO"] == "/rewind_first" - if buf = input.read(rand(cap)) - begin - raise "#{buf.size} > #{cap}" if buf.size > cap - digest.update(buf) - end while input.read(rand(cap), buf) - end - - [ 200, {'Content-Type' => 'text/plain'}, [ digest.hexdigest << "\n" ] ] -end -run app diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0000-http-basic.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0000-http-basic.sh deleted file mode 100755 index 8ab58ac..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0000-http-basic.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 8 "simple HTTP connection tests" - -t_begin "setup and start" && { - unicorn_setup - unicorn -D -c $unicorn_config env.ru - unicorn_wait_start -} - -t_begin "single request" && { - curl -sSfv http://$listen/ -} - -t_begin "check stderr has no errors" && { - check_stderr -} - -t_begin "HTTP/0.9 request should not return headers" && { - ( - printf 'GET /\r\n' - cat $fifo > $tmp & - wait - echo ok > $ok - ) | socat - TCP:$listen > $fifo -} - -t_begin "env.inspect should've put everything on one line" && { - test 1 -eq $(count_lines < $tmp) -} - -t_begin "no headers in output" && { - if grep ^Connection: $tmp - then - die "Connection header found in $tmp" - elif grep ^HTTP/ $tmp - then - die "HTTP/ found in $tmp" - fi -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr has no errors" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0001-reload-bad-config.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0001-reload-bad-config.sh deleted file mode 100755 index 55bb355..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0001-reload-bad-config.sh +++ /dev/null @@ -1,53 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 7 "reload config.ru error with preload_app true" - -t_begin "setup and start" && { - unicorn_setup - rtmpfiles ru - - cat > $ru <<\EOF -use Rack::ContentLength -use Rack::ContentType, "text/plain" -x = { "hello" => "world" } -run lambda { |env| [ 200, {}, [ x.inspect << "\n" ] ] } -EOF - echo 'preload_app true' >> $unicorn_config - unicorn -D -c $unicorn_config $ru - unicorn_wait_start -} - -t_begin "hit with curl" && { - out=$(curl -sSf http://$listen/) - test x"$out" = x'{"hello"=>"world"}' -} - -t_begin "introduce syntax error in rackup file" && { - echo '...' >> $ru -} - -t_begin "reload signal succeeds" && { - kill -HUP $unicorn_pid - while ! egrep '(done|error) reloading' $r_err >/dev/null - do - sleep 1 - done - - grep 'error reloading' $r_err >/dev/null - > $r_err -} - -t_begin "hit with curl" && { - out=$(curl -sSf http://$listen/) - test x"$out" = x'{"hello"=>"world"}' -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0002-config-conflict.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0002-config-conflict.sh deleted file mode 100755 index d7b2181..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0002-config-conflict.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 6 "config variables conflict with preload_app" - -t_begin "setup and start" && { - unicorn_setup - rtmpfiles ru rutmp - - cat > $ru <<\EOF -use Rack::ContentLength -use Rack::ContentType, "text/plain" -config = ru = { "hello" => "world" } -run lambda { |env| [ 200, {}, [ ru.inspect << "\n" ] ] } -EOF - echo 'preload_app true' >> $unicorn_config - unicorn -D -c $unicorn_config $ru - unicorn_wait_start -} - -t_begin "hit with curl" && { - out=$(curl -sSf http://$listen/) - test x"$out" = x'{"hello"=>"world"}' -} - -t_begin "modify rackup file" && { - sed -e 's/world/WORLD/' < $ru > $rutmp - mv $rutmp $ru -} - -t_begin "reload signal succeeds" && { - kill -HUP $unicorn_pid - while ! egrep '(done|error) reloading' < $r_err >/dev/null - do - sleep 1 - done - - grep 'done reloading' $r_err >/dev/null -} - -t_begin "hit with curl" && { - out=$(curl -sSf http://$listen/) - test x"$out" = x'{"hello"=>"WORLD"}' -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0002-parser-error.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0002-parser-error.sh deleted file mode 100755 index 9fa5a31..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0002-parser-error.sh +++ /dev/null @@ -1,94 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 11 "parser error test" - -t_begin "setup and startup" && { - unicorn_setup - unicorn -D env.ru -c $unicorn_config - unicorn_wait_start -} - -t_begin "send a bad request" && { - ( - printf 'GET / HTTP/1/1\r\nHost: example.com\r\n\r\n' - cat $fifo > $tmp & - wait - echo ok > $ok - ) | socat - TCP:$listen > $fifo - test xok = x$(cat $ok) -} - -dbgcat tmp - -t_begin "response should be a 400" && { - grep -F 'HTTP/1.1 400 Bad Request' $tmp -} - -t_begin "send a huge Request URI (REQUEST_PATH > (12 * 1024))" && { - rm -f $tmp - cat $fifo > $tmp & - ( - set -e - trap 'echo ok > $ok' EXIT - printf 'GET /' - for i in $(awk $fifo || : - test xok = x$(cat $ok) - wait -} - -t_begin "response should be a 414 (REQUEST_PATH)" && { - grep -F 'HTTP/1.1 414 Request-URI Too Long' $tmp -} - -t_begin "send a huge Request URI (QUERY_STRING > (10 * 1024))" && { - rm -f $tmp - cat $fifo > $tmp & - ( - set -e - trap 'echo ok > $ok' EXIT - printf 'GET /hello-world?a' - for i in $(awk $fifo || : - test xok = x$(cat $ok) - wait -} - -t_begin "response should be a 414 (QUERY_STRING)" && { - grep -F 'HTTP/1.1 414 Request-URI Too Long' $tmp -} - -t_begin "send a huge Request URI (FRAGMENT > 1024)" && { - rm -f $tmp - cat $fifo > $tmp & - ( - set -e - trap 'echo ok > $ok' EXIT - printf 'GET /hello-world#a' - for i in $(awk $fifo || : - test xok = x$(cat $ok) - wait -} - -t_begin "response should be a 414 (FRAGMENT)" && { - grep -F 'HTTP/1.1 414 Request-URI Too Long' $tmp -} - -t_begin "server stderr should be clean" && check_stderr - -t_begin "term signal sent" && kill $unicorn_pid - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0003-working_directory.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0003-working_directory.sh deleted file mode 100755 index 79988d8..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0003-working_directory.sh +++ /dev/null @@ -1,51 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 4 "config.ru inside alt working_directory" - -t_begin "setup and start" && { - unicorn_setup - rtmpfiles unicorn_config_tmp - rm -rf $t_pfx.app - mkdir $t_pfx.app - - cat > $t_pfx.app/config.ru < $unicorn_config_tmp - - # the whole point of this exercise - echo "working_directory '$t_pfx.app'" >> $unicorn_config_tmp - - # allows ppid to be 1 in before_fork - echo "preload_app true" >> $unicorn_config_tmp - cat >> $unicorn_config_tmp <<\EOF -before_fork do |server,worker| - $master_ppid = Process.ppid # should be zero to detect daemonization -end -EOF - - mv $unicorn_config_tmp $unicorn_config - - # rely on --daemonize switch, no & or -D - unicorn -c $unicorn_config - unicorn_wait_start -} - -t_begin "hit with curl" && { - body=$(curl -sSf http://$listen/) -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "response body ppid == 1 (daemonized)" && { - test "$body" -eq 1 -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0004-heartbeat-timeout.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0004-heartbeat-timeout.sh deleted file mode 100755 index 2965283..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0004-heartbeat-timeout.sh +++ /dev/null @@ -1,69 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 11 "heartbeat/timeout test" - -t_begin "setup and startup" && { - unicorn_setup - echo timeout 3 >> $unicorn_config - echo preload_app true >> $unicorn_config - unicorn -D heartbeat-timeout.ru -c $unicorn_config - unicorn_wait_start -} - -t_begin "read worker PID" && { - worker_pid=$(curl -sSf http://$listen/) - t_info "worker_pid=$worker_pid" -} - -t_begin "sleep for a bit, ensure worker PID does not change" && { - sleep 4 - test $(curl -sSf http://$listen/) -eq $worker_pid -} - -t_begin "block the worker process to force it to die" && { - rm $ok - t0=$(unix_time) - err="$(curl -sSf http://$listen/block-forever 2>&1 || > $ok)" - t1=$(unix_time) - elapsed=$(($t1 - $t0)) - t_info "elapsed=$elapsed err=$err" - test x"$err" != x"Should never get here" - test x"$err" != x"$worker_pid" -} - -t_begin "ensure worker was killed" && { - test -e $ok - test 1 -eq $(grep timeout $r_err | grep killing | count_lines) -} - -t_begin "ensure timeout took at least 3 seconds" && { - test $elapsed -ge 3 -} - -t_begin "we get a fresh new worker process" && { - new_worker_pid=$(curl -sSf http://$listen/) - test $new_worker_pid -ne $worker_pid -} - -t_begin "truncate the server error log" && { - > $r_err -} - -t_begin "SIGSTOP and SIGCONT on unicorn master does not kill worker" && { - kill -STOP $unicorn_pid - sleep 4 - kill -CONT $unicorn_pid - sleep 2 - test $new_worker_pid -eq $(curl -sSf http://$listen/) -} - -t_begin "stop server" && { - kill -QUIT $unicorn_pid -} - -t_begin "check stderr" && check_stderr - -dbgcat r_err - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0004-working_directory_broken.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0004-working_directory_broken.sh deleted file mode 100755 index ca9d382..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0004-working_directory_broken.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 3 "config.ru is missing inside alt working_directory" - -t_begin "setup" && { - unicorn_setup - rtmpfiles unicorn_config_tmp ok - rm -rf $t_pfx.app - mkdir $t_pfx.app - - # the whole point of this exercise - echo "working_directory '$t_pfx.app'" >> $unicorn_config_tmp -} - -t_begin "fails to start up w/o config.ru" && { - unicorn -c $unicorn_config_tmp || echo ok > $ok -} - -t_begin "fallback code was run" && { - test x"$(cat $ok)" = xok -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0005-working_directory_app.rb.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0005-working_directory_app.rb.sh deleted file mode 100755 index 0fbab4f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0005-working_directory_app.rb.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 4 "fooapp.rb inside alt working_directory" - -t_begin "setup and start" && { - unicorn_setup - rm -rf $t_pfx.app - mkdir $t_pfx.app - - cat > $t_pfx.app/fooapp.rb <<\EOF -class Fooapp - def self.call(env) - # Rack::Lint in 1.5.0 requires headers to be a hash - h = [%w(Content-Type text/plain), %w(Content-Length 2)] - h = Rack::Utils::HeaderHash.new(h) - [ 200, h, %w(HI) ] - end -end -EOF - # the whole point of this exercise - echo "working_directory '$t_pfx.app'" >> $unicorn_config - cd / - unicorn -D -c $unicorn_config -I. fooapp.rb - unicorn_wait_start -} - -t_begin "hit with curl" && { - body=$(curl -sSf http://$listen/) -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "response body expected" && { - test x"$body" = xHI -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0006-reopen-logs.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0006-reopen-logs.sh deleted file mode 100755 index a6e7a17..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0006-reopen-logs.sh +++ /dev/null @@ -1,83 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 15 "reopen rotated logs" - -t_begin "setup and startup" && { - rtmpfiles curl_out curl_err r_rot - unicorn_setup - unicorn -D t0006.ru -c $unicorn_config - unicorn_wait_start -} - -t_begin "ensure server is responsive" && { - test xtrue = x$(curl -sSf http://$listen/ 2> $curl_err) -} - -t_begin "ensure stderr log is clean" && check_stderr - -t_begin "external log rotation" && { - rm -f $r_rot - mv $r_err $r_rot -} - -t_begin "send reopen log signal (USR1)" && { - kill -USR1 $unicorn_pid -} - -t_begin "wait for rotated log to reappear" && { - nr=60 - while ! test -f $r_err && test $nr -ge 0 - do - sleep 1 - nr=$(( $nr - 1 )) - done -} - -t_begin "ensure server is still responsive" && { - test xtrue = x$(curl -sSf http://$listen/ 2> $curl_err) -} - -t_begin "wait for worker to reopen logs" && { - nr=60 - re="worker=.* done reopening logs" - while ! grep "$re" < $r_err >/dev/null && test $nr -ge 0 - do - sleep 1 - nr=$(( $nr - 1 )) - done -} - -dbgcat r_rot -dbgcat r_err - -t_begin "ensure no errors from curl" && { - test ! -s $curl_err -} - -t_begin "current server stderr is clean" && check_stderr - -t_begin "rotated stderr is clean" && { - check_stderr $r_rot -} - -t_begin "server is now writing logs to new stderr" && { - before_rot=$(count_bytes < $r_rot) - before_err=$(count_bytes < $r_err) - test xtrue = x$(curl -sSf http://$listen/ 2> $curl_err) - after_rot=$(count_bytes < $r_rot) - after_err=$(count_bytes < $r_err) - test $after_rot -eq $before_rot - test $after_err -gt $before_err -} - -t_begin "stop server" && { - kill $unicorn_pid -} - -dbgcat r_err - -t_begin "current server stderr is clean" && check_stderr -t_begin "rotated stderr is clean" && check_stderr $r_rot - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0006.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0006.ru deleted file mode 100644 index c39e8f6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0006.ru +++ /dev/null @@ -1,13 +0,0 @@ -use Rack::ContentLength -use Rack::ContentType, "text/plain" -run lambda { |env| - - # our File objects for stderr/stdout should always have #path - # and be sync=true - ok = $stderr.sync && - $stdout.sync && - String === $stderr.path && - String === $stdout.path - - [ 200, {}, [ "#{ok}\n" ] ] -} diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0007-working_directory_no_embed_cli.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0007-working_directory_no_embed_cli.sh deleted file mode 100755 index 77d6707..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0007-working_directory_no_embed_cli.sh +++ /dev/null @@ -1,44 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 4 "config.ru inside alt working_directory (no embedded switches)" - -t_begin "setup and start" && { - unicorn_setup - rm -rf $t_pfx.app - mkdir $t_pfx.app - - cat > $t_pfx.app/config.ru <> $unicorn_config - - # allows ppid to be 1 in before_fork - echo "preload_app true" >> $unicorn_config - cat >> $unicorn_config <<\EOF -before_fork do |server,worker| - $master_ppid = Process.ppid # should be zero to detect daemonization -end -EOF - - cd / - unicorn -D -c $unicorn_config - unicorn_wait_start -} - -t_begin "hit with curl" && { - body=$(curl -sSf http://$listen/) -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "response body ppid == 1 (daemonized)" && { - test "$body" -eq 1 -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0008-back_out_of_upgrade.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0008-back_out_of_upgrade.sh deleted file mode 100755 index 96d4057..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0008-back_out_of_upgrade.sh +++ /dev/null @@ -1,110 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 13 "backout of USR2 upgrade" - -worker_wait_start () { - test xSTART = x"$(cat $fifo)" - unicorn_pid=$(cat $pid) -} - -t_begin "setup and start" && { - unicorn_setup - rm -f $pid.oldbin - -cat >> $unicorn_config </dev/null - do - i=$(( $i + 1 )) - test $i -lt 600 || die "timed out" - sleep 1 - done -} - -t_begin "capture pid of new worker" && { - new_worker_pid=$(curl -sSf http://$listen/) -} - -t_begin "reload old master process" && { - kill -HUP $orig_master_pid - worker_wait_start -} - -t_begin "gracefully kill new master and ensure it dies" && { - kill -QUIT $new_master_pid - i=0 - while kill -0 $new_worker_pid 2>/dev/null - do - i=$(( $i + 1 )) - test $i -lt 600 || die "timed out" - sleep 1 - done -} - -t_begin "ensure $pid.oldbin does not exist" && { - i=0 - while test -s $pid.oldbin - do - i=$(( $i + 1 )) - test $i -lt 600 || die "timed out" - sleep 1 - done - while ! test -s $pid - do - i=$(( $i + 1 )) - test $i -lt 600 || die "timed out" - sleep 1 - done -} - -t_begin "ensure $pid is correct" && { - cur_master_pid=$(cat $pid) - test $orig_master_pid -eq $cur_master_pid -} - -t_begin "killing succeeds" && { - kill $orig_master_pid -} - -dbgcat r_err - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0009-broken-app.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0009-broken-app.sh deleted file mode 100755 index 895b178..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0009-broken-app.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 9 "graceful handling of broken apps" - -t_begin "setup and start" && { - unicorn_setup - unicorn -E none -D broken-app.ru -c $unicorn_config - unicorn_wait_start -} - -t_begin "normal response is alright" && { - test xOK = x"$(curl -sSf http://$listen/)" -} - -t_begin "app raised exception" && { - curl -sSf http://$listen/raise 2> $tmp || : - grep -F 500 $tmp - > $tmp -} - -t_begin "app exception logged and backtrace not swallowed" && { - grep -F 'app error' $r_err - grep -A1 -F 'app error' $r_err | tail -1 | grep broken-app.ru: - dbgcat r_err - > $r_err -} - -t_begin "trigger bad response" && { - curl -sSf http://$listen/nil 2> $tmp || : - grep -F 500 $tmp - > $tmp -} - -t_begin "app exception logged" && { - grep -F 'app error' $r_err - > $r_err -} - -t_begin "normal responses alright afterwards" && { - > $tmp - curl -sSf http://$listen/ >> $tmp & - curl -sSf http://$listen/ >> $tmp & - curl -sSf http://$listen/ >> $tmp & - curl -sSf http://$listen/ >> $tmp & - wait - test xOK = x$(sort < $tmp | uniq) -} - -t_begin "teardown" && { - kill $unicorn_pid -} - -t_begin "check stderr" && check_stderr - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0009-winch_ttin.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0009-winch_ttin.sh deleted file mode 100755 index 6e56e30..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0009-winch_ttin.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 8 "SIGTTIN succeeds after SIGWINCH" - -t_begin "setup and start" && { - unicorn_setup -cat >> $unicorn_config </dev/null - do - i=$(( $i + 1 )) - test $i -lt 600 || die "timed out" - sleep 1 - done -} - -t_begin "start one worker back up" && { - kill -TTIN $unicorn_pid -} - -t_begin "wait for new worker to start" && { - test 0 -eq $(cat $fifo) || die "worker.nr != 0" - new_worker_pid=$(curl -sSf http://$listen/) - test -n "$new_worker_pid" && kill -0 $new_worker_pid - test $orig_worker_pid -ne $new_worker_pid || \ - die "worker wasn't replaced" -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && check_stderr - -dbgcat r_err - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0010-reap-logging.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0010-reap-logging.sh deleted file mode 100755 index 93d8c60..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0010-reap-logging.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 9 "reap worker logging messages" - -t_begin "setup and start" && { - unicorn_setup - cat >> $unicorn_config < $r_err -} - -t_begin "kill 2nd worker gracefully" && { - pid_2=$(curl http://$listen/) - kill -QUIT $pid_2 -} - -t_begin "wait for 3rd worker=0 to start " && { - test '.' = $(cat $fifo) -} - -t_begin "ensure log of 2nd reap is a INFO" && { - grep 'INFO.*reaped.*worker=0' $r_err | grep $pid_2 - > $r_err -} - -t_begin "killing succeeds" && { - kill $unicorn_pid - wait - kill -0 $unicorn_pid && false -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0011-active-unix-socket.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0011-active-unix-socket.sh deleted file mode 100755 index d256f5c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0011-active-unix-socket.sh +++ /dev/null @@ -1,79 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 11 "existing UNIX domain socket check" - -read_pid_unix () { - x=$(printf 'GET / HTTP/1.0\r\n\r\n' | \ - socat - UNIX:$unix_socket | \ - tail -1) - test -n "$x" - y="$(expr "$x" : '\([0-9][0-9]*\)')" - test x"$x" = x"$y" - test -n "$y" - echo "$y" -} - -t_begin "setup and start" && { - rtmpfiles unix_socket unix_config - rm -f $unix_socket - unicorn_setup - grep -v ^listen < $unicorn_config > $unix_config - echo "listen '$unix_socket'" >> $unix_config - unicorn -D -c $unix_config pid.ru - unicorn_wait_start - orig_master_pid=$unicorn_pid -} - -t_begin "get pid of worker" && { - worker_pid=$(read_pid_unix) - t_info "worker_pid=$worker_pid" -} - -t_begin "fails to start with existing pid file" && { - rm -f $ok - unicorn -D -c $unix_config pid.ru || echo ok > $ok - test x"$(cat $ok)" = xok -} - -t_begin "worker pid unchanged" && { - test x"$(read_pid_unix)" = x$worker_pid - > $r_err -} - -t_begin "fails to start with listening UNIX domain socket bound" && { - rm $ok $pid - unicorn -D -c $unix_config pid.ru || echo ok > $ok - test x"$(cat $ok)" = xok - > $r_err -} - -t_begin "worker pid unchanged (again)" && { - test x"$(read_pid_unix)" = x$worker_pid -} - -t_begin "nuking the existing Unicorn succeeds" && { - kill -9 $unicorn_pid $worker_pid - while kill -0 $unicorn_pid - do - sleep 1 - done - check_stderr -} - -t_begin "succeeds in starting with leftover UNIX domain socket bound" && { - test -S $unix_socket - unicorn -D -c $unix_config pid.ru - unicorn_wait_start -} - -t_begin "worker pid changed" && { - test x"$(read_pid_unix)" != x$worker_pid -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "no errors" && check_stderr - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0012-reload-empty-config.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0012-reload-empty-config.sh deleted file mode 100755 index 81e1fb3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0012-reload-empty-config.sh +++ /dev/null @@ -1,85 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 9 "reloading unset config resets defaults" - -t_begin "setup and start" && { - unicorn_setup - rtmpfiles unicorn_config_orig before_reload after_reload - cat $unicorn_config > $unicorn_config_orig - cat >> $unicorn_config < $tmp -} - -t_begin "replace config file with original(-ish)" && { - grep -v ^pid < $unicorn_config_orig > $unicorn_config - cat >> $unicorn_config </dev/null - do - sleep 1 - done - while ! grep reaped < $r_err >/dev/null - do - sleep 1 - done - grep 'done reloading' $r_err >/dev/null -} - -t_begin "ensure worker is started" && { - curl -sSf http://$listen/ > $tmp -} - -t_begin "pid file no longer exists" && { - if test -f $pid - then - die "pid=$pid should not exist" - fi -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_begin "ensure reloading restored settings" && { - awk < $after_reload -F'|' ' -$1 != "before_fork" && $2 != $3 { print $0; exit(1) } -' -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0013-rewindable-input-false.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0013-rewindable-input-false.sh deleted file mode 100755 index 0e89631..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0013-rewindable-input-false.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 4 "rewindable_input toggled to false" - -t_begin "setup and start" && { - unicorn_setup - echo rewindable_input false >> $unicorn_config - unicorn -D -c $unicorn_config t0013.ru - unicorn_wait_start -} - -t_begin "ensure worker is started" && { - test xOK = x$(curl -T t0013.ru -H Expect: -vsSf http://$listen/) -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0013.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0013.ru deleted file mode 100644 index 48a3a34..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0013.ru +++ /dev/null @@ -1,12 +0,0 @@ -#\ -E none -use Rack::ContentLength -use Rack::ContentType, 'text/plain' -app = lambda do |env| - case env['rack.input'] - when Unicorn::StreamInput - [ 200, {}, %w(OK) ] - else - [ 500, {}, %w(NO) ] - end -end -run app diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0014-rewindable-input-true.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0014-rewindable-input-true.sh deleted file mode 100755 index dd48bc6..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0014-rewindable-input-true.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 4 "rewindable_input toggled to true" - -t_begin "setup and start" && { - unicorn_setup - echo rewindable_input true >> $unicorn_config - unicorn -D -c $unicorn_config t0014.ru - unicorn_wait_start -} - -t_begin "ensure worker is started" && { - test xOK = x$(curl -T t0014.ru -sSf http://$listen/) -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0014.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0014.ru deleted file mode 100644 index b0bd2b7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0014.ru +++ /dev/null @@ -1,12 +0,0 @@ -#\ -E none -use Rack::ContentLength -use Rack::ContentType, 'text/plain' -app = lambda do |env| - case env['rack.input'] - when Unicorn::TeeInput - [ 200, {}, %w(OK) ] - else - [ 500, {}, %w(NO) ] - end -end -run app diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0015-configurator-internals.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0015-configurator-internals.sh deleted file mode 100755 index 4e3acbe..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0015-configurator-internals.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 4 "configurator internals tests (from FAQ)" - -t_begin "setup and start" && { - unicorn_setup - cat >> $unicorn_config <"https"' -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "no errors" && check_stderr - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0016-trust-x-forwarded-false.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0016-trust-x-forwarded-false.sh deleted file mode 100755 index 3163690..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0016-trust-x-forwarded-false.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 5 "trust_x_forwarded=false configuration test" - -t_begin "setup and start" && { - unicorn_setup - echo "trust_x_forwarded false" >> $unicorn_config - unicorn -D -c $unicorn_config env.ru - unicorn_wait_start -} - -t_begin "spoofed request with X-Forwarded-Proto does not trigger" && { - curl -H 'X-Forwarded-Proto: https' http://$listen/ | \ - grep -F '"rack.url_scheme"=>"http"' -} - -t_begin "spoofed request with X-Forwarded-SSL does not trigger" && { - curl -H 'X-Forwarded-SSL: on' http://$listen/ | \ - grep -F '"rack.url_scheme"=>"http"' -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr has no errors" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0017-trust-x-forwarded-true.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0017-trust-x-forwarded-true.sh deleted file mode 100755 index 11103c5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0017-trust-x-forwarded-true.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 5 "trust_x_forwarded=true configuration test" - -t_begin "setup and start" && { - unicorn_setup - echo "trust_x_forwarded true " >> $unicorn_config - unicorn -D -c $unicorn_config env.ru - unicorn_wait_start -} - -t_begin "spoofed request with X-Forwarded-Proto sets 'https'" && { - curl -H 'X-Forwarded-Proto: https' http://$listen/ | \ - grep -F '"rack.url_scheme"=>"https"' -} - -t_begin "spoofed request with X-Forwarded-SSL sets 'https'" && { - curl -H 'X-Forwarded-SSL: on' http://$listen/ | \ - grep -F '"rack.url_scheme"=>"https"' -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr has no errors" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0018-write-on-close.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0018-write-on-close.sh deleted file mode 100755 index 3afefea..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0018-write-on-close.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 4 "write-on-close tests for funky response-bodies" - -t_begin "setup and start" && { - unicorn_setup - unicorn -D -c $unicorn_config write-on-close.ru - unicorn_wait_start -} - -t_begin "write-on-close response body succeeds" && { - test xGoodbye = x"$(curl -sSf http://$listen/)" -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0019-max_header_len.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0019-max_header_len.sh deleted file mode 100755 index 6a355b4..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0019-max_header_len.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 5 "max_header_len setting (only intended for Rainbows!)" - -t_begin "setup and start" && { - unicorn_setup - req='GET / HTTP/1.0\r\n\r\n' - len=$(printf "$req" | count_bytes) - echo Unicorn::HttpParser.max_header_len = $len >> $unicorn_config - unicorn -D -c $unicorn_config env.ru - unicorn_wait_start -} - -t_begin "minimal request succeeds" && { - rm -f $tmp - ( - cat $fifo > $tmp & - printf "$req" - wait - echo ok > $ok - ) | socat - TCP:$listen > $fifo - test xok = x$(cat $ok) - - fgrep "HTTP/1.1 200 OK" $tmp -} - -t_begin "big request fails" && { - rm -f $tmp - ( - cat $fifo > $tmp & - printf 'GET /xxxxxx HTTP/1.0\r\n\r\n' - wait - echo ok > $ok - ) | socat - TCP:$listen > $fifo - test xok = x$(cat $ok) - fgrep "HTTP/1.1 413" $tmp -} - -dbgcat tmp - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0020-at_exit-handler.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0020-at_exit-handler.sh deleted file mode 100755 index fda14b5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0020-at_exit-handler.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 5 "at_exit/END handlers work as expected" - -t_begin "setup and startup" && { - unicorn_setup - cat >> $unicorn_config </dev/null 2>&1 - do - sleep 1 - done -} - -t_begin "check stderr" && check_stderr - -dbgcat r_err -dbgcat r_out - -t_begin "all at_exit handlers ran" && { - grep "$worker_pid BOTH" $r_out - grep "$unicorn_pid BOTH" $r_out - grep "$worker_pid END BOTH" $r_out - grep "$unicorn_pid END BOTH" $r_out - grep "$worker_pid WORKER ONLY" $r_out - grep "$worker_pid END WORKER ONLY" $r_out -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0021-process_detach.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0021-process_detach.sh deleted file mode 100755 index f03c497..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0021-process_detach.sh +++ /dev/null @@ -1,29 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -t_plan 5 "Process.detach on forked background process works" - -t_begin "setup and startup" && { - t_fifos process_detach - unicorn_setup - TEST_FIFO=$process_detach \ - unicorn -E none -D detach.ru -c $unicorn_config - unicorn_wait_start -} - -t_begin "read detached PID with HTTP/1.0" && { - detached_pid=$(curl -0 -sSf http://$listen/) - t_info "detached_pid=$detached_pid" -} - -t_begin "read background FIFO" && { - test xHIHI = x"$(cat $process_detach)" -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && check_stderr - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0022-listener_names-preload_app.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0022-listener_names-preload_app.sh deleted file mode 100644 index d07a26c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0022-listener_names-preload_app.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh -. ./test-lib.sh - -# Raindrops::Middleware depends on Unicorn.listener_names, -# ensure we don't break Raindrops::Middleware when preload_app is true - -t_plan 4 "Unicorn.listener_names available with preload_app=true" - -t_begin "setup and startup" && { - unicorn_setup - echo preload_app true >> $unicorn_config - unicorn -E none -D listener_names.ru -c $unicorn_config - unicorn_wait_start -} - -t_begin "read listener names includes listener" && { - resp=$(curl -sSf http://$listen/) - ok=false - t_info "resp=$resp" - case $resp in - *\"$listen\"*) ok=true ;; - esac - $ok -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && check_stderr - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0100-rack-input-tests.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0100-rack-input-tests.sh deleted file mode 100755 index ee7a437..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0100-rack-input-tests.sh +++ /dev/null @@ -1,124 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -test -r random_blob || die "random_blob required, run with 'make $0'" - -t_plan 10 "rack.input read tests" - -t_begin "setup and startup" && { - rtmpfiles curl_out curl_err - unicorn_setup - unicorn -E none -D rack-input-tests.ru -c $unicorn_config - blob_sha1=$(rsha1 < random_blob) - blob_size=$(count_bytes < random_blob) - t_info "blob_sha1=$blob_sha1" - unicorn_wait_start -} - -t_begin "corked identity request" && { - rm -f $tmp - ( - cat $fifo > $tmp & - printf 'PUT / HTTP/1.0\r\n' - printf 'Content-Length: %d\r\n\r\n' $blob_size - cat random_blob - wait - echo ok > $ok - ) | ( sleep 1 && socat - TCP4:$listen > $fifo ) - test 1 -eq $(grep $blob_sha1 $tmp |count_lines) - test x"$(cat $ok)" = xok -} - -t_begin "corked chunked request" && { - rm -f $tmp - ( - cat $fifo > $tmp & - content-md5-put < random_blob - wait - echo ok > $ok - ) | ( sleep 1 && socat - TCP4:$listen > $fifo ) - test 1 -eq $(grep $blob_sha1 $tmp |count_lines) - test x"$(cat $ok)" = xok -} - -t_begin "corked identity request (input#size first)" && { - rm -f $tmp - ( - cat $fifo > $tmp & - printf 'PUT /size_first HTTP/1.0\r\n' - printf 'Content-Length: %d\r\n\r\n' $blob_size - cat random_blob - wait - echo ok > $ok - ) | ( sleep 1 && socat - TCP4:$listen > $fifo ) - test 1 -eq $(grep $blob_sha1 $tmp |count_lines) - test x"$(cat $ok)" = xok -} - -t_begin "corked identity request (input#rewind first)" && { - rm -f $tmp - ( - cat $fifo > $tmp & - printf 'PUT /rewind_first HTTP/1.0\r\n' - printf 'Content-Length: %d\r\n\r\n' $blob_size - cat random_blob - wait - echo ok > $ok - ) | ( sleep 1 && socat - TCP4:$listen > $fifo ) - test 1 -eq $(grep $blob_sha1 $tmp |count_lines) - test x"$(cat $ok)" = xok -} - -t_begin "corked chunked request (input#size first)" && { - rm -f $tmp - ( - cat $fifo > $tmp & - printf 'PUT /size_first HTTP/1.1\r\n' - printf 'Host: example.com\r\n' - printf 'Transfer-Encoding: chunked\r\n' - printf 'Trailer: Content-MD5\r\n' - printf '\r\n' - content-md5-put --no-headers < random_blob - wait - echo ok > $ok - ) | ( sleep 1 && socat - TCP4:$listen > $fifo ) - test 1 -eq $(grep $blob_sha1 $tmp |count_lines) - test 1 -eq $(grep $blob_sha1 $tmp |count_lines) - test x"$(cat $ok)" = xok -} - -t_begin "corked chunked request (input#rewind first)" && { - rm -f $tmp - ( - cat $fifo > $tmp & - printf 'PUT /rewind_first HTTP/1.1\r\n' - printf 'Host: example.com\r\n' - printf 'Transfer-Encoding: chunked\r\n' - printf 'Trailer: Content-MD5\r\n' - printf '\r\n' - content-md5-put --no-headers < random_blob - wait - echo ok > $ok - ) | ( sleep 1 && socat - TCP4:$listen > $fifo ) - test 1 -eq $(grep $blob_sha1 $tmp |count_lines) - test x"$(cat $ok)" = xok -} - -t_begin "regular request" && { - curl -sSf -T random_blob http://$listen/ > $curl_out 2> $curl_err - test x$blob_sha1 = x$(cat $curl_out) - test ! -s $curl_err -} - -t_begin "chunked request" && { - curl -sSf -T- < random_blob http://$listen/ > $curl_out 2> $curl_err - test x$blob_sha1 = x$(cat $curl_out) - test ! -s $curl_err -} - -dbgcat r_err - -t_begin "shutdown" && { - kill $unicorn_pid -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0116-client_body_buffer_size.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0116-client_body_buffer_size.sh deleted file mode 100755 index c9e17c7..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0116-client_body_buffer_size.sh +++ /dev/null @@ -1,80 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 12 "client_body_buffer_size settings" - -t_begin "setup and start" && { - unicorn_setup - rtmpfiles unicorn_config_tmp one_meg - dd if=/dev/zero bs=1M count=1 of=$one_meg - cat >> $unicorn_config < $unicorn_config_tmp - echo client_body_buffer_size 0 >> $unicorn_config - unicorn -D -c $unicorn_config t0116.ru - unicorn_wait_start - fs_class=Unicorn::TmpIO - mem_class=StringIO - - test x"$(cat $fifo)" = xSTART -} - -t_begin "class for a zero-byte file should be StringIO" && { - > $tmp - test xStringIO = x"$(curl -T $tmp -sSf http://$listen/input_class)" -} - -t_begin "class for a 1 byte file should be filesystem-backed" && { - echo > $tmp - test x$fs_class = x"$(curl -T $tmp -sSf http://$listen/tmp_class)" -} - -t_begin "reload with default client_body_buffer_size" && { - mv $unicorn_config_tmp $unicorn_config - kill -HUP $unicorn_pid - test x"$(cat $fifo)" = xSTART -} - -t_begin "class for a 1 byte file should be memory-backed" && { - echo > $tmp - test x$mem_class = x"$(curl -T $tmp -sSf http://$listen/tmp_class)" -} - -t_begin "class for a random blob file should be filesystem-backed" && { - resp="$(curl -T random_blob -sSf http://$listen/tmp_class)" - test x$fs_class = x"$resp" -} - -t_begin "one megabyte file should be filesystem-backed" && { - resp="$(curl -T $one_meg -sSf http://$listen/tmp_class)" - test x$fs_class = x"$resp" -} - -t_begin "reload with a big client_body_buffer_size" && { - echo "client_body_buffer_size(1024 * 1024)" >> $unicorn_config - kill -HUP $unicorn_pid - test x"$(cat $fifo)" = xSTART -} - -t_begin "one megabyte file should be memory-backed" && { - resp="$(curl -T $one_meg -sSf http://$listen/tmp_class)" - test x$mem_class = x"$resp" -} - -t_begin "one megabyte + 1 byte file should be filesystem-backed" && { - echo >> $one_meg - resp="$(curl -T $one_meg -sSf http://$listen/tmp_class)" - test x$fs_class = x"$resp" -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0116.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0116.ru deleted file mode 100644 index fab5fce..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0116.ru +++ /dev/null @@ -1,16 +0,0 @@ -#\ -E none -use Rack::ContentLength -use Rack::ContentType, 'text/plain' -app = lambda do |env| - input = env['rack.input'] - case env["PATH_INFO"] - when "/tmp_class" - body = input.instance_variable_get(:@tmp).class.name - when "/input_class" - body = input.class.name - else - return [ 500, {}, [] ] - end - [ 200, {}, [ body ] ] -end -run app diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0200-rack-hijack.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0200-rack-hijack.sh deleted file mode 100755 index f772071..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0200-rack-hijack.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 5 "rack.hijack tests (Rack 1.5+ (Rack::VERSION >= [ 1,2]))" - -t_begin "setup and start" && { - unicorn_setup - unicorn -D -c $unicorn_config hijack.ru - unicorn_wait_start -} - -t_begin "check request hijack" && { - test "xrequest.hijacked" = x"$(curl -sSfv http://$listen/hijack_req)" -} - -t_begin "check response hijack" && { - test "xresponse.hijacked" = x"$(curl -sSfv http://$listen/hijack_res)" -} - -t_begin "killing succeeds" && { - kill $unicorn_pid -} - -t_begin "check stderr" && { - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0300-no-default-middleware.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0300-no-default-middleware.sh deleted file mode 100644 index 779dc02..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t0300-no-default-middleware.sh +++ /dev/null @@ -1,20 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 3 "test the -N / --no-default-middleware option" - -t_begin "setup and start" && { - unicorn_setup - unicorn -N -D -c $unicorn_config fails-rack-lint.ru - unicorn_wait_start -} - -t_begin "check exit status with Rack::Lint not present" && { - test 42 -eq "$(curl -sf -o/dev/null -w'%{http_code}' http://$listen/)" -} - -t_begin "killing succeeds" && { - kill $unicorn_pid - check_stderr -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9000-preread-input.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9000-preread-input.sh deleted file mode 100755 index d6c73ab..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9000-preread-input.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 9 "PrereadInput middleware tests" - -t_begin "setup and start" && { - random_blob_sha1=$(rsha1 < random_blob) - unicorn_setup - unicorn -D -c $unicorn_config preread_input.ru - unicorn_wait_start -} - -t_begin "single identity request" && { - curl -sSf -T random_blob http://$listen/ > $tmp -} - -t_begin "sha1 matches" && { - test x"$(cat $tmp)" = x"$random_blob_sha1" -} - -t_begin "single chunked request" && { - curl -sSf -T- < random_blob http://$listen/ > $tmp -} - -t_begin "sha1 matches" && { - test x"$(cat $tmp)" = x"$random_blob_sha1" -} - -t_begin "app only dispatched twice" && { - test 2 -eq "$(grep 'app dispatch:' < $r_err | count_lines )" -} - -t_begin "aborted chunked request" && { - rm -f $tmp - curl -sSf -T- < $fifo http://$listen/ > $tmp & - curl_pid=$! - kill -9 $curl_pid - wait -} - -t_begin "app only dispatched twice" && { - test 2 -eq "$(grep 'app dispatch:' < $r_err | count_lines )" -} - -t_begin "killing succeeds" && { - kill -QUIT $unicorn_pid -} - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9001-oob_gc.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9001-oob_gc.sh deleted file mode 100755 index dcd8100..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9001-oob_gc.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 9 "OobGC test" - -t_begin "setup and start" && { - unicorn_setup - unicorn -D -c $unicorn_config oob_gc.ru - unicorn_wait_start -} - -t_begin "test default interval (4 requests)" && { - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "GC starting-request returns immediately" && { - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "GC is started after 5 requests" && { - test xtrue = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "reset GC" && { - test xfalse = x$(curl -vsSf -X POST http://$listen/gc_reset 2>> $tmp) -} - -t_begin "test default interval again (3 requests)" && { - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "GC is started after 5 requests" && { - test xtrue = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "killing succeeds" && { - kill -QUIT $unicorn_pid -} - -t_begin "check_stderr" && check_stderr -dbgcat r_err - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9002-oob_gc-path.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9002-oob_gc-path.sh deleted file mode 100755 index d4e795b..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/t9002-oob_gc-path.sh +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/sh -. ./test-lib.sh -t_plan 12 "OobGC test with limited path" - -t_begin "setup and start" && { - unicorn_setup - unicorn -D -c $unicorn_config oob_gc_path.ru - unicorn_wait_start -} - -t_begin "test default is noop" && { - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "4 bad requests to bump counter" && { - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) -} - -t_begin "GC-starting request returns immediately" && { - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) -} - -t_begin "GC was started after 5 requests" && { - test xtrue = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "reset GC" && { - test xfalse = x$(curl -vsSf -X POST http://$listen/gc_reset 2>> $tmp) -} - -t_begin "test default is noop" && { - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "4 bad requests to bump counter" && { - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) -} - -t_begin "GC-starting request returns immediately" && { - test xfalse = x$(curl -vsSf http://$listen/BAD 2>> $tmp) -} - -t_begin "GC was started after 5 requests" && { - test xtrue = x$(curl -vsSf http://$listen/ 2>> $tmp) -} - -t_begin "killing succeeds" && { - kill -QUIT $unicorn_pid -} - -t_begin "check_stderr" && check_stderr - -t_done diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/test-lib.sh b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/test-lib.sh deleted file mode 100644 index 28d6a88..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/t/test-lib.sh +++ /dev/null @@ -1,128 +0,0 @@ -#!/bin/sh -# Copyright (c) 2009 Rainbows! hackers -# Copyright (c) 2010 Unicorn hackers -. ./my-tap-lib.sh - -set +u - -# sometimes we rely on http_proxy to avoid wasting bandwidth with Isolate -# and multiple Ruby versions -NO_PROXY=${UNICORN_TEST_ADDR-127.0.0.1} -export NO_PROXY - -set -e -RUBY="${RUBY-ruby}" -RUBY_VERSION=${RUBY_VERSION-$($RUBY -e 'puts RUBY_VERSION')} -RUBY_ENGINE=${RUBY_ENGINE-$($RUBY -e 'puts((RUBY_ENGINE rescue "ruby"))')} -t_pfx=$PWD/trash/$T-$RUBY_ENGINE-$RUBY_VERSION -set -u - -PATH=$PWD/bin:$PATH -export PATH - -test -x $PWD/bin/unused_listen || die "must be run in 't' directory" - -wait_for_pid () { - path="$1" - nr=30 - while ! test -s "$path" && test $nr -gt 0 - do - nr=$(($nr - 1)) - sleep 1 - done -} - -# "unix_time" is not in POSIX, but in GNU, and FreeBSD 9.0 (possibly earlier) -unix_time () { - $RUBY -e 'puts Time.now.to_i' -} - -# "wc -l" outputs leading whitespace on *BSDs, filter it out for portability -count_lines () { - wc -l | tr -d '[:space:]' -} - -# "wc -c" outputs leading whitespace on *BSDs, filter it out for portability -count_bytes () { - wc -c | tr -d '[:space:]' -} - -# given a list of variable names, create temporary files and assign -# the pathnames to those variables -rtmpfiles () { - for id in "$@" - do - name=$id - - case $name in - *fifo) - _tmp=$t_pfx.$id - eval "$id=$_tmp" - rm -f $_tmp - mkfifo $_tmp - T_RM_LIST="$T_RM_LIST $_tmp" - ;; - *socket) - _tmp="$(mktemp -t $id.$$.XXXXXXXX)" - if test $(printf "$_tmp" |count_bytes) -gt 108 - then - echo >&2 "$_tmp too long, tests may fail" - echo >&2 "Try to set TMPDIR to a shorter path" - fi - eval "$id=$_tmp" - rm -f $_tmp - T_RM_LIST="$T_RM_LIST $_tmp" - ;; - *) - _tmp=$t_pfx.$id - eval "$id=$_tmp" - > $_tmp - T_OK_RM_LIST="$T_OK_RM_LIST $_tmp" - ;; - esac - done -} - -dbgcat () { - id=$1 - eval '_file=$'$id - echo "==> $id <==" - sed -e "s/^/$id:/" < $_file -} - -check_stderr () { - set +u - _r_err=${1-${r_err}} - set -u - if grep -v $T $_r_err | grep -i Error - then - die "Errors found in $_r_err" - elif grep SIGKILL $_r_err - then - die "SIGKILL found in $_r_err" - fi -} - -# unicorn_setup -unicorn_setup () { - eval $(unused_listen) - port=$(expr $listen : '[^:]*:\([0-9]\+\)') - host=$(expr $listen : '\([^:]*\):[0-9]\+') - - rtmpfiles unicorn_config pid r_err r_out fifo tmp ok - cat > $unicorn_config < unicorn@host1(tcp) - client@host2 -> unicorn@host1(tcp) - client@host3 -> nginx@host1 -> unicorn@host1(tcp) - client@host3 -> nginx@host1 -> unicorn@host1(unix) - client@host3 -> nginx@host2 -> unicorn@host1(tcp) - -The benchmark client is usually httperf. - -Another gentle reminder: performance with slow networks/clients -is NOT our problem. That is the job of nginx (or similar). - -== Contributors - -This directory is maintained independently in the "benchmark" branch -based against v0.1.0. Only changes to this directory (test/benchmarks) -are committed to this branch although the master branch may merge this -branch occassionaly. diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/benchmark/dd.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/benchmark/dd.ru deleted file mode 100644 index 111fa2e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/benchmark/dd.ru +++ /dev/null @@ -1,18 +0,0 @@ -# This benchmark is the simplest test of the I/O facilities in -# unicorn. It is meant to return a fixed-sized blob to test -# the performance of things in Unicorn, _NOT_ the app. -# -# Adjusting this benchmark is done via the "bs" (byte size) and "count" -# environment variables. "count" designates the count of elements of -# "bs" length in the Rack response body. The defaults are bs=4096, count=1 -# to return one 4096-byte chunk. -bs = ENV['bs'] ? ENV['bs'].to_i : 4096 -count = ENV['count'] ? ENV['count'].to_i : 1 -slice = (' ' * bs).freeze -body = (1..count).map { slice }.freeze -hdr = { - 'Content-Length' => (bs * count).to_s.freeze, - 'Content-Type' => 'text/plain'.freeze -}.freeze -response = [ 200, hdr, body ].freeze -run(lambda { |env| response }) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/benchmark/stack.ru b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/benchmark/stack.ru deleted file mode 100644 index fc9193f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/benchmark/stack.ru +++ /dev/null @@ -1,8 +0,0 @@ -run(lambda { |env| - body = "#{caller.size}\n" - h = { - "Content-Length" => body.size.to_s, - "Content-Type" => "text/plain", - } - [ 200, h, [ body ] ] -}) diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/exec/README b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/exec/README deleted file mode 100644 index a1341f5..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/exec/README +++ /dev/null @@ -1,5 +0,0 @@ -These tests require the "unicorn" executable script to be installed in -PATH and rack being directly "require"-able ("rubygems" will not be -loaded for you). The tester is responsible for setting up RUBYLIB and -PATH environment variables (or running tests via GNU Make instead of -Rake). diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/exec/test_exec.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/exec/test_exec.rb deleted file mode 100644 index 10a1bae..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/exec/test_exec.rb +++ /dev/null @@ -1,1047 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2009 Eric Wong -FLOCK_PATH = File.expand_path(__FILE__) -require 'test/test_helper' - -do_test = true -$unicorn_bin = ENV['UNICORN_TEST_BIN'] || "unicorn" -redirect_test_io do - do_test = system($unicorn_bin, '-v') -end - -unless do_test - warn "#{$unicorn_bin} not found in PATH=#{ENV['PATH']}, " \ - "skipping this test" -end - -unless try_require('rack') - warn "Unable to load Rack, skipping this test" - do_test = false -end - -class ExecTest < Test::Unit::TestCase - trap(:QUIT, 'IGNORE') - - HI = <<-EOS -use Rack::ContentLength -run proc { |env| [ 200, { 'Content-Type' => 'text/plain' }, [ "HI\\n" ] ] } - EOS - - SHOW_RACK_ENV = <<-EOS -use Rack::ContentLength -run proc { |env| - [ 200, { 'Content-Type' => 'text/plain' }, [ ENV['RACK_ENV'] ] ] -} - EOS - - HELLO = <<-EOS -class Hello - def call(env) - [ 200, { 'Content-Type' => 'text/plain' }, [ "HI\\n" ] ] - end -end - EOS - - COMMON_TMP = Tempfile.new('unicorn_tmp') unless defined?(COMMON_TMP) - - HEAVY_CFG = <<-EOS -worker_processes 4 -timeout 30 -logger Logger.new('#{COMMON_TMP.path}') -before_fork do |server, worker| - server.logger.info "before_fork: worker=\#{worker.nr}" -end - EOS - - WORKING_DIRECTORY_CHECK_RU = <<-EOS -use Rack::ContentLength -run lambda { |env| - pwd = ENV['PWD'] - a = ::File.stat(pwd) - b = ::File.stat(Dir.pwd) - if (a.ino == b.ino && a.dev == b.dev) - [ 200, { 'Content-Type' => 'text/plain' }, [ pwd ] ] - else - [ 404, { 'Content-Type' => 'text/plain' }, [] ] - end -} - EOS - - def setup - @pwd = Dir.pwd - @tmpfile = Tempfile.new('unicorn_exec_test') - @tmpdir = @tmpfile.path - @tmpfile.close! - Dir.mkdir(@tmpdir) - Dir.chdir(@tmpdir) - @addr = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - @port = unused_port(@addr) - @sockets = [] - @start_pid = $$ - end - - def teardown - return if @start_pid != $$ - Dir.chdir(@pwd) - FileUtils.rmtree(@tmpdir) - @sockets.each { |path| File.unlink(path) rescue nil } - loop do - Process.kill('-QUIT', 0) - begin - Process.waitpid(-1, Process::WNOHANG) or break - rescue Errno::ECHILD - break - end - end - end - - def test_working_directory_rel_path_config_file - other = Tempfile.new('unicorn.wd') - File.unlink(other.path) - Dir.mkdir(other.path) - File.open("config.ru", "wb") do |fp| - fp.syswrite WORKING_DIRECTORY_CHECK_RU - end - FileUtils.cp("config.ru", other.path + "/config.ru") - Dir.chdir(@tmpdir) - - tmp = File.open('unicorn.config', 'wb') - tmp.syswrite < 0 - end - rescue Errno::ENOENT - (sleep(DEFAULT_RES) and (tries -= 1) > 0) and retry - end - assert_equal current_pid, File.read(pid_file).to_i - - tries = DEFAULT_TRIES - while File.exist?(old_file) - (sleep(DEFAULT_RES) and (tries -= 1) > 0) or break - end - assert ! File.exist?(old_file), "oldbin=#{old_file} gone" - port2 = unused_port(@addr) - - # fix the bug - ucfg.sysseek(0) - ucfg.truncate(0) - ucfg.syswrite("listen %(#@addr:#@port)\n") - ucfg.syswrite("listen %(#@addr:#{port2})\n") - ucfg.syswrite("pid %(#{pid_file})\n") - Process.kill(:USR2, current_pid) - - wait_for_file(old_file) - wait_for_file(pid_file) - new_pid = File.read(pid_file).to_i - assert_not_equal current_pid, new_pid - assert_equal current_pid, File.read(old_file).to_i - results = retry_hit(["http://#{@addr}:#{@port}/", - "http://#{@addr}:#{port2}/"]) - assert_equal String, results[0].class - assert_equal String, results[1].class - - Process.kill(:QUIT, current_pid) - Process.kill(:QUIT, new_pid) - end - - def test_broken_reexec_ru - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - pid_file = "#{@tmpdir}/test.pid" - old_file = "#{pid_file}.oldbin" - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("pid %(#{pid_file})\n") - ucfg.syswrite("logger Logger.new(%(#{@tmpdir}/log))\n") - pid = xfork do - redirect_test_io do - exec($unicorn_bin, "-D", "-l#{@addr}:#{@port}", "-c#{ucfg.path}") - end - end - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - - wait_for_file(pid_file) - Process.waitpid(pid) - Process.kill(:USR2, File.read(pid_file).to_i) - wait_for_file(old_file) - wait_for_file(pid_file) - old_pid = File.read(old_file).to_i - Process.kill(:QUIT, old_pid) - wait_for_death(old_pid) - - File.unlink("config.ru") # break reloading - current_pid = File.read(pid_file).to_i - Process.kill(:USR2, current_pid) - - # wait for pid_file to restore itself - tries = DEFAULT_TRIES - begin - while current_pid != File.read(pid_file).to_i - sleep(DEFAULT_RES) and (tries -= 1) > 0 - end - rescue Errno::ENOENT - (sleep(DEFAULT_RES) and (tries -= 1) > 0) and retry - end - - tries = DEFAULT_TRIES - while File.exist?(old_file) - (sleep(DEFAULT_RES) and (tries -= 1) > 0) or break - end - assert ! File.exist?(old_file), "oldbin=#{old_file} gone" - assert_equal current_pid, File.read(pid_file).to_i - - # fix the bug - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - Process.kill(:USR2, current_pid) - wait_for_file(old_file) - wait_for_file(pid_file) - new_pid = File.read(pid_file).to_i - assert_not_equal current_pid, new_pid - assert_equal current_pid, File.read(old_file).to_i - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - - Process.kill(:QUIT, current_pid) - Process.kill(:QUIT, new_pid) - end - - def test_unicorn_config_listener_swap - port_cli = unused_port - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("listen '#@addr:#@port'\n") - pid = xfork do - redirect_test_io do - exec($unicorn_bin, "-c#{ucfg.path}", "-l#@addr:#{port_cli}") - end - end - results = retry_hit(["http://#@addr:#{port_cli}/"]) - assert_equal String, results[0].class - results = retry_hit(["http://#@addr:#@port/"]) - assert_equal String, results[0].class - - port2 = unused_port(@addr) - ucfg.sysseek(0) - ucfg.truncate(0) - ucfg.syswrite("listen '#@addr:#{port2}'\n") - Process.kill(:HUP, pid) - - results = retry_hit(["http://#@addr:#{port2}/"]) - assert_equal String, results[0].class - results = retry_hit(["http://#@addr:#{port_cli}/"]) - assert_equal String, results[0].class - reuse = TCPServer.new(@addr, @port) - reuse.close - assert_shutdown(pid) - end - - def test_unicorn_config_listen_with_options - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("listen '#{@addr}:#{@port}', :backlog => 512,\n") - ucfg.syswrite(" :rcvbuf => 4096,\n") - ucfg.syswrite(" :sndbuf => 4096\n") - pid = xfork do - redirect_test_io { exec($unicorn_bin, "-c#{ucfg.path}") } - end - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - assert_shutdown(pid) - end - - def test_unicorn_config_per_worker_listen - port2 = unused_port - pid_spit = 'use Rack::ContentLength;' \ - 'run proc { |e| [ 200, {"Content-Type"=>"text/plain"}, ["#$$\\n"] ] }' - File.open("config.ru", "wb") { |fp| fp.syswrite(pid_spit) } - tmp = Tempfile.new('test.socket') - File.unlink(tmp.path) - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("listen '#@addr:#@port'\n") - ucfg.syswrite("after_fork { |s,w|\n") - ucfg.syswrite(" s.listen('#{tmp.path}', :backlog => 5, :sndbuf => 8192)\n") - ucfg.syswrite(" s.listen('#@addr:#{port2}', :rcvbuf => 8192)\n") - ucfg.syswrite("\n}\n") - pid = xfork do - redirect_test_io { exec($unicorn_bin, "-c#{ucfg.path}") } - end - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - worker_pid = results[0].to_i - assert_not_equal pid, worker_pid - s = UNIXSocket.new(tmp.path) - s.syswrite("GET / HTTP/1.0\r\n\r\n") - results = '' - loop { results << s.sysread(4096) } rescue nil - s.close - assert_equal worker_pid, results.split(/\r\n/).last.to_i - results = hit(["http://#@addr:#{port2}/"]) - assert_equal String, results[0].class - assert_equal worker_pid, results[0].to_i - assert_shutdown(pid) - end - - def test_unicorn_config_listen_augments_cli - port2 = unused_port(@addr) - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("listen '#{@addr}:#{@port}'\n") - pid = xfork do - redirect_test_io do - exec($unicorn_bin, "-c#{ucfg.path}", "-l#{@addr}:#{port2}") - end - end - uris = [@port, port2].map { |i| "http://#{@addr}:#{i}/" } - results = retry_hit(uris) - assert_equal results.size, uris.size - assert_equal String, results[0].class - assert_equal String, results[1].class - assert_shutdown(pid) - end - - def test_weird_config_settings - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite(HEAVY_CFG) - pid = xfork do - redirect_test_io do - exec($unicorn_bin, "-c#{ucfg.path}", "-l#{@addr}:#{@port}") - end - end - - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - wait_master_ready(COMMON_TMP.path) - wait_workers_ready(COMMON_TMP.path, 4) - bf = File.readlines(COMMON_TMP.path).grep(/\bbefore_fork: worker=/) - assert_equal 4, bf.size - rotate = Tempfile.new('unicorn_rotate') - - File.rename(COMMON_TMP.path, rotate.path) - Process.kill(:USR1, pid) - - wait_for_file(COMMON_TMP.path) - assert File.exist?(COMMON_TMP.path), "#{COMMON_TMP.path} exists" - # USR1 should've been passed to all workers - tries = DEFAULT_TRIES - log = File.readlines(rotate.path) - while (tries -= 1) > 0 && - log.grep(/reopening logs\.\.\./).size < 5 - sleep DEFAULT_RES - log = File.readlines(rotate.path) - end - assert_equal 5, log.grep(/reopening logs\.\.\./).size - assert_equal 0, log.grep(/done reopening logs/).size - - tries = DEFAULT_TRIES - log = File.readlines(COMMON_TMP.path) - while (tries -= 1) > 0 && log.grep(/done reopening logs/).size < 5 - sleep DEFAULT_RES - log = File.readlines(COMMON_TMP.path) - end - assert_equal 5, log.grep(/done reopening logs/).size - assert_equal 0, log.grep(/reopening logs\.\.\./).size - - Process.kill(:QUIT, pid) - pid, status = Process.waitpid2(pid) - - assert status.success?, "exited successfully" - end - - def test_read_embedded_cli_switches - File.open("config.ru", "wb") do |fp| - fp.syswrite("#\\ -p #{@port} -o #{@addr}\n") - fp.syswrite(HI) - end - pid = fork { redirect_test_io { exec($unicorn_bin) } } - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - assert_shutdown(pid) - end - - def test_config_ru_alt_path - config_path = "#{@tmpdir}/foo.ru" - File.open(config_path, "wb") { |fp| fp.syswrite(HI) } - pid = fork do - redirect_test_io do - Dir.chdir("/") - exec($unicorn_bin, "-l#{@addr}:#{@port}", config_path) - end - end - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - assert_shutdown(pid) - end - - def test_load_module - libdir = "#{@tmpdir}/lib" - FileUtils.mkpath([ libdir ]) - config_path = "#{libdir}/hello.rb" - File.open(config_path, "wb") { |fp| fp.syswrite(HELLO) } - pid = fork do - redirect_test_io do - Dir.chdir("/") - exec($unicorn_bin, "-l#{@addr}:#{@port}", config_path) - end - end - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - assert_shutdown(pid) - end - - def test_reexec - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - pid_file = "#{@tmpdir}/test.pid" - pid = fork do - redirect_test_io do - exec($unicorn_bin, "-l#{@addr}:#{@port}", "-P#{pid_file}") - end - end - reexec_basic_test(pid, pid_file) - end - - def test_reexec_alt_config - config_file = "#{@tmpdir}/foo.ru" - File.open(config_file, "wb") { |fp| fp.syswrite(HI) } - pid_file = "#{@tmpdir}/test.pid" - pid = fork do - redirect_test_io do - exec($unicorn_bin, "-l#{@addr}:#{@port}", "-P#{pid_file}", config_file) - end - end - reexec_basic_test(pid, pid_file) - end - - def test_socket_unlinked_restore - results = nil - sock = Tempfile.new('unicorn_test_sock') - sock_path = sock.path - @sockets << sock_path - sock.close! - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("listen \"#{sock_path}\"\n") - - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - pid = xfork { redirect_test_io { exec($unicorn_bin, "-c#{ucfg.path}") } } - wait_for_file(sock_path) - assert File.socket?(sock_path) - - sock = UNIXSocket.new(sock_path) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - results = sock.sysread(4096) - - assert_equal String, results.class - File.unlink(sock_path) - Process.kill(:HUP, pid) - wait_for_file(sock_path) - assert File.socket?(sock_path) - - sock = UNIXSocket.new(sock_path) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - results = sock.sysread(4096) - - assert_equal String, results.class - end - - def test_unicorn_config_file - pid_file = "#{@tmpdir}/test.pid" - sock = Tempfile.new('unicorn_test_sock') - sock_path = sock.path - sock.close! - @sockets << sock_path - - log = Tempfile.new('unicorn_test_log') - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("listen \"#{sock_path}\"\n") - ucfg.syswrite("pid \"#{pid_file}\"\n") - ucfg.syswrite("logger Logger.new('#{log.path}')\n") - ucfg.close - - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - pid = xfork do - redirect_test_io do - exec($unicorn_bin, "-l#{@addr}:#{@port}", - "-P#{pid_file}", "-c#{ucfg.path}") - end - end - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - wait_master_ready(log.path) - assert File.exist?(pid_file), "pid_file created" - assert_equal pid, File.read(pid_file).to_i - assert File.socket?(sock_path), "socket created" - - sock = UNIXSocket.new(sock_path) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - results = sock.sysread(4096) - - assert_equal String, results.class - - # try reloading the config - sock = Tempfile.new('new_test_sock') - new_sock_path = sock.path - @sockets << new_sock_path - sock.close! - new_log = Tempfile.new('unicorn_test_log') - new_log.sync = true - assert_equal 0, new_log.size - - ucfg = File.open(ucfg.path, "wb") - ucfg.syswrite("listen \"#{sock_path}\"\n") - ucfg.syswrite("listen \"#{new_sock_path}\"\n") - ucfg.syswrite("pid \"#{pid_file}\"\n") - ucfg.syswrite("logger Logger.new('#{new_log.path}')\n") - ucfg.close - Process.kill(:HUP, pid) - - wait_for_file(new_sock_path) - assert File.socket?(new_sock_path), "socket exists" - @sockets.each do |path| - sock = UNIXSocket.new(path) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - results = sock.sysread(4096) - assert_equal String, results.class - end - - assert_not_equal 0, new_log.size - reexec_usr2_quit_test(pid, pid_file) - end - - def test_daemonize_reexec - pid_file = "#{@tmpdir}/test.pid" - log = Tempfile.new('unicorn_test_log') - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("pid \"#{pid_file}\"\n") - ucfg.syswrite("logger Logger.new('#{log.path}')\n") - ucfg.close - - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - pid = xfork do - redirect_test_io do - exec($unicorn_bin, "-D", "-l#{@addr}:#{@port}", "-c#{ucfg.path}") - end - end - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - wait_for_file(pid_file) - new_pid = File.read(pid_file).to_i - assert_not_equal pid, new_pid - pid, status = Process.waitpid2(pid) - assert status.success?, "original process exited successfully" - Process.kill(0, new_pid) - reexec_usr2_quit_test(new_pid, pid_file) - end - - def test_daemonize_redirect_fail - pid_file = "#{@tmpdir}/test.pid" - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("pid #{pid_file}\"\n") - err = Tempfile.new('stderr') - out = Tempfile.new('stdout ') - - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - pid = xfork do - $stderr.reopen(err.path, "a") - $stdout.reopen(out.path, "a") - exec($unicorn_bin, "-D", "-l#{@addr}:#{@port}", "-c#{ucfg.path}") - end - pid, status = Process.waitpid2(pid) - assert ! status.success?, "original process exited successfully" - sleep 1 # can't waitpid on a daemonized process :< - assert err.stat.size > 0 - end - - def test_reexec_fd_leak - unless RUBY_PLATFORM =~ /linux/ # Solaris may work, too, but I forget... - warn "FD leak test only works on Linux at the moment" - return - end - pid_file = "#{@tmpdir}/test.pid" - log = Tempfile.new('unicorn_test_log') - log.sync = true - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("pid \"#{pid_file}\"\n") - ucfg.syswrite("logger Logger.new('#{log.path}')\n") - ucfg.syswrite("stderr_path '#{log.path}'\n") - ucfg.syswrite("stdout_path '#{log.path}'\n") - ucfg.close - - File.open("config.ru", "wb") { |fp| fp.syswrite(HI) } - pid = xfork do - redirect_test_io do - exec($unicorn_bin, "-D", "-l#{@addr}:#{@port}", "-c#{ucfg.path}") - end - end - - wait_master_ready(log.path) - wait_workers_ready(log.path, 1) - File.truncate(log.path, 0) - wait_for_file(pid_file) - orig_pid = pid = File.read(pid_file).to_i - orig_fds = `ls -l /proc/#{pid}/fd`.split(/\n/) - assert $?.success? - expect_size = orig_fds.size - - Process.kill(:USR2, pid) - wait_for_file("#{pid_file}.oldbin") - Process.kill(:QUIT, pid) - - wait_for_death(pid) - - wait_master_ready(log.path) - wait_workers_ready(log.path, 1) - File.truncate(log.path, 0) - wait_for_file(pid_file) - pid = File.read(pid_file).to_i - assert_not_equal orig_pid, pid - curr_fds = `ls -l /proc/#{pid}/fd`.split(/\n/) - assert $?.success? - - # we could've inherited descriptors the first time around - assert expect_size >= curr_fds.size, curr_fds.inspect - expect_size = curr_fds.size - - Process.kill(:USR2, pid) - wait_for_file("#{pid_file}.oldbin") - Process.kill(:QUIT, pid) - - wait_for_death(pid) - - wait_master_ready(log.path) - wait_workers_ready(log.path, 1) - File.truncate(log.path, 0) - wait_for_file(pid_file) - pid = File.read(pid_file).to_i - curr_fds = `ls -l /proc/#{pid}/fd`.split(/\n/) - assert $?.success? - assert_equal expect_size, curr_fds.size, curr_fds.inspect - - Process.kill(:QUIT, pid) - wait_for_death(pid) - end - - def hup_test_common(preload, check_client=false) - File.open("config.ru", "wb") { |fp| fp.syswrite(HI.gsub("HI", '#$$')) } - pid_file = Tempfile.new('pid') - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("listen '#@addr:#@port'\n") - ucfg.syswrite("pid '#{pid_file.path}'\n") - ucfg.syswrite("preload_app true\n") if preload - ucfg.syswrite("check_client_connection true\n") if check_client - ucfg.syswrite("stderr_path 'test_stderr.#$$.log'\n") - ucfg.syswrite("stdout_path 'test_stdout.#$$.log'\n") - pid = xfork { - redirect_test_io { exec($unicorn_bin, "-D", "-c", ucfg.path) } - } - _, status = Process.waitpid2(pid) - assert status.success? - wait_master_ready("test_stderr.#$$.log") - wait_workers_ready("test_stderr.#$$.log", 1) - uri = URI.parse("http://#@addr:#@port/") - pids = Tempfile.new('worker_pids') - r, w = IO.pipe - hitter = fork { - r.close - bodies = Hash.new(0) - at_exit { pids.syswrite(bodies.inspect) } - trap(:TERM) { exit(0) } - nr = 0 - loop { - rv = Net::HTTP.get(uri) - pid = rv.to_i - exit!(1) if pid <= 0 - bodies[pid] += 1 - nr += 1 - if nr == 1 - w.syswrite('1') - elsif bodies.size > 1 - w.syswrite('2') - sleep - end - } - } - w.close - assert_equal '1', r.read(1) - daemon_pid = File.read(pid_file.path).to_i - assert daemon_pid > 0 - Process.kill(:HUP, daemon_pid) - assert_equal '2', r.read(1) - Process.kill(:TERM, hitter) - _, hitter_status = Process.waitpid2(hitter) - assert(hitter_status.success?, - "invalid: #{hitter_status.inspect} #{File.read(pids.path)}" \ - "#{File.read("test_stderr.#$$.log")}") - pids.sysseek(0) - pids = eval(pids.read) - assert_kind_of(Hash, pids) - assert_equal 2, pids.size - pids.keys.each { |x| - assert_kind_of(Integer, x) - assert x > 0 - assert pids[x] > 0 - } - Process.kill(:QUIT, daemon_pid) - wait_for_death(daemon_pid) - end - - def test_preload_app_hup - hup_test_common(true) - end - - def test_hup - hup_test_common(false) - end - - def test_check_client_hup - hup_test_common(false, true) - end - - def test_default_listen_hup_holds_listener - default_listen_lock do - res, pid_path = default_listen_setup - daemon_pid = File.read(pid_path).to_i - Process.kill(:HUP, daemon_pid) - wait_workers_ready("test_stderr.#$$.log", 1) - res2 = hit(["http://#{Unicorn::Const::DEFAULT_LISTEN}/"]) - assert_match %r{\d+}, res2.first - assert res2.first != res.first - Process.kill(:QUIT, daemon_pid) - wait_for_death(daemon_pid) - end - end - - def test_default_listen_upgrade_holds_listener - default_listen_lock do - res, pid_path = default_listen_setup - daemon_pid = File.read(pid_path).to_i - - Process.kill(:USR2, daemon_pid) - wait_for_file("#{pid_path}.oldbin") - wait_for_file(pid_path) - Process.kill(:QUIT, daemon_pid) - wait_for_death(daemon_pid) - - daemon_pid = File.read(pid_path).to_i - wait_workers_ready("test_stderr.#$$.log", 1) - File.truncate("test_stderr.#$$.log", 0) - - res2 = hit(["http://#{Unicorn::Const::DEFAULT_LISTEN}/"]) - assert_match %r{\d+}, res2.first - assert res2.first != res.first - - Process.kill(:HUP, daemon_pid) - wait_workers_ready("test_stderr.#$$.log", 1) - File.truncate("test_stderr.#$$.log", 0) - res3 = hit(["http://#{Unicorn::Const::DEFAULT_LISTEN}/"]) - assert res2.first != res3.first - - Process.kill(:QUIT, daemon_pid) - wait_for_death(daemon_pid) - end - end - - def default_listen_setup - File.open("config.ru", "wb") { |fp| fp.syswrite(HI.gsub("HI", '#$$')) } - pid_path = (tmp = Tempfile.new('pid')).path - tmp.close! - ucfg = Tempfile.new('unicorn_test_config') - ucfg.syswrite("pid '#{pid_path}'\n") - ucfg.syswrite("stderr_path 'test_stderr.#$$.log'\n") - ucfg.syswrite("stdout_path 'test_stdout.#$$.log'\n") - pid = xfork { - redirect_test_io { exec($unicorn_bin, "-D", "-c", ucfg.path) } - } - _, status = Process.waitpid2(pid) - assert status.success? - wait_master_ready("test_stderr.#$$.log") - wait_workers_ready("test_stderr.#$$.log", 1) - File.truncate("test_stderr.#$$.log", 0) - res = hit(["http://#{Unicorn::Const::DEFAULT_LISTEN}/"]) - assert_match %r{\d+}, res.first - [ res, pid_path ] - end - - # we need to flock() something to prevent these tests from running - def default_listen_lock(&block) - fp = File.open(FLOCK_PATH, "rb") - begin - fp.flock(File::LOCK_EX) - begin - TCPServer.new(Unicorn::Const::DEFAULT_HOST, - Unicorn::Const::DEFAULT_PORT).close - rescue Errno::EADDRINUSE, Errno::EACCES - warn "can't bind to #{Unicorn::Const::DEFAULT_LISTEN}" - return false - end - - # unused_port should never take this, but we may run an environment - # where tests are being run against older unicorns... - lock_path = "#{Dir::tmpdir}/unicorn_test." \ - "#{Unicorn::Const::DEFAULT_LISTEN}.lock" - begin - File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600) - yield - rescue Errno::EEXIST - lock_path = nil - return false - ensure - File.unlink(lock_path) if lock_path - end - ensure - fp.flock(File::LOCK_UN) - end - end - -end if do_test diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/test_helper.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/test_helper.rb deleted file mode 100644 index c65f2f3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/test_helper.rb +++ /dev/null @@ -1,297 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2005 Zed A. Shaw -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) -# -# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html -# for more information. - -STDIN.sync = STDOUT.sync = STDERR.sync = true # buffering makes debugging hard - -# FIXME: move curl-dependent tests into t/ -ENV['NO_PROXY'] ||= ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - -# Some tests watch a log file or a pid file to spring up to check state -# Can't rely on inotify on non-Linux and logging to a pipe makes things -# more complicated -DEFAULT_TRIES = 1000 -DEFAULT_RES = 0.2 - -require 'test/unit' -require 'net/http' -require 'digest/sha1' -require 'uri' -require 'stringio' -require 'pathname' -require 'tempfile' -require 'fileutils' -require 'logger' -require 'unicorn' - -if ENV['DEBUG'] - require 'ruby-debug' - Debugger.start -end - -def redirect_test_io - orig_err = STDERR.dup - orig_out = STDOUT.dup - STDERR.reopen("test_stderr.#{$$}.log", "a") - STDOUT.reopen("test_stdout.#{$$}.log", "a") - STDERR.sync = STDOUT.sync = true - - at_exit do - File.unlink("test_stderr.#{$$}.log") rescue nil - File.unlink("test_stdout.#{$$}.log") rescue nil - end - - begin - yield - ensure - STDERR.reopen(orig_err) - STDOUT.reopen(orig_out) - end -end - -# which(1) exit codes cannot be trusted on some systems -# We use UNIX shell utilities in some tests because we don't trust -# ourselves to write Ruby 100% correctly :) -def which(bin) - ex = ENV['PATH'].split(/:/).detect do |x| - x << "/#{bin}" - File.executable?(x) - end or warn "`#{bin}' not found in PATH=#{ENV['PATH']}" - ex -end - -# Either takes a string to do a get request against, or a tuple of [URI, HTTP] where -# HTTP is some kind of Net::HTTP request object (POST, HEAD, etc.) -def hit(uris) - results = [] - uris.each do |u| - res = nil - - if u.kind_of? String - u = 'http://127.0.0.1:8080/' if u == 'http://0.0.0.0:8080/' - res = Net::HTTP.get(URI.parse(u)) - else - url = URI.parse(u[0]) - res = Net::HTTP.new(url.host, url.port).start {|h| h.request(u[1]) } - end - - assert res != nil, "Didn't get a response: #{u}" - results << res - end - - return results -end - -# unused_port provides an unused port on +addr+ usable for TCP that is -# guaranteed to be unused across all unicorn builds on that system. It -# prevents race conditions by using a lock file other unicorn builds -# will see. This is required if you perform several builds in parallel -# with a continuous integration system or run tests in parallel via -# gmake. This is NOT guaranteed to be race-free if you run other -# processes that bind to random ports for testing (but the window -# for a race condition is very small). You may also set UNICORN_TEST_ADDR -# to override the default test address (127.0.0.1). -def unused_port(addr = '127.0.0.1') - retries = 100 - base = 5000 - port = sock = nil - begin - begin - port = base + rand(32768 - base) - while port == Unicorn::Const::DEFAULT_PORT - port = base + rand(32768 - base) - end - - sock = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0) - sock.bind(Socket.pack_sockaddr_in(port, addr)) - sock.listen(5) - rescue Errno::EADDRINUSE, Errno::EACCES - sock.close rescue nil - retry if (retries -= 1) >= 0 - end - - # since we'll end up closing the random port we just got, there's a race - # condition could allow the random port we just chose to reselect itself - # when running tests in parallel with gmake. Create a lock file while - # we have the port here to ensure that does not happen . - lock_path = "#{Dir::tmpdir}/unicorn_test.#{addr}:#{port}.lock" - File.open(lock_path, File::WRONLY|File::CREAT|File::EXCL, 0600).close - at_exit { File.unlink(lock_path) rescue nil } - rescue Errno::EEXIST - sock.close rescue nil - retry - end - sock.close rescue nil - port -end - -def try_require(lib) - begin - require lib - true - rescue LoadError - false - end -end - -# sometimes the server may not come up right away -def retry_hit(uris = []) - tries = DEFAULT_TRIES - begin - hit(uris) - rescue Errno::EINVAL, Errno::ECONNREFUSED => err - if (tries -= 1) > 0 - sleep DEFAULT_RES - retry - end - raise err - end -end - -def assert_shutdown(pid) - wait_master_ready("test_stderr.#{pid}.log") - Process.kill(:QUIT, pid) - pid, status = Process.waitpid2(pid) - assert status.success?, "exited successfully" -end - -def wait_workers_ready(path, nr_workers) - tries = DEFAULT_TRIES - lines = [] - while (tries -= 1) > 0 - begin - lines = File.readlines(path).grep(/worker=\d+ ready/) - lines.size == nr_workers and return - rescue Errno::ENOENT - end - sleep DEFAULT_RES - end - raise "#{nr_workers} workers never became ready:" \ - "\n\t#{lines.join("\n\t")}\n" -end - -def wait_master_ready(master_log) - tries = DEFAULT_TRIES - while (tries -= 1) > 0 - begin - File.readlines(master_log).grep(/master process ready/)[0] and return - rescue Errno::ENOENT - end - sleep DEFAULT_RES - end - raise "master process never became ready" -end - -def reexec_usr2_quit_test(pid, pid_file) - assert File.exist?(pid_file), "pid file OK" - assert ! File.exist?("#{pid_file}.oldbin"), "oldbin pid file" - Process.kill(:USR2, pid) - retry_hit(["http://#{@addr}:#{@port}/"]) - wait_for_file("#{pid_file}.oldbin") - wait_for_file(pid_file) - - old_pid = File.read("#{pid_file}.oldbin").to_i - new_pid = File.read(pid_file).to_i - - # kill old master process - assert_not_equal pid, new_pid - assert_equal pid, old_pid - Process.kill(:QUIT, old_pid) - retry_hit(["http://#{@addr}:#{@port}/"]) - wait_for_death(old_pid) - assert_equal new_pid, File.read(pid_file).to_i - retry_hit(["http://#{@addr}:#{@port}/"]) - Process.kill(:QUIT, new_pid) -end - -def reexec_basic_test(pid, pid_file) - results = retry_hit(["http://#{@addr}:#{@port}/"]) - assert_equal String, results[0].class - Process.kill(0, pid) - master_log = "#{@tmpdir}/test_stderr.#{pid}.log" - wait_master_ready(master_log) - File.truncate(master_log, 0) - nr = 50 - kill_point = 2 - nr.times do |i| - hit(["http://#{@addr}:#{@port}/#{i}"]) - i == kill_point and Process.kill(:HUP, pid) - end - wait_master_ready(master_log) - assert File.exist?(pid_file), "pid=#{pid_file} exists" - new_pid = File.read(pid_file).to_i - assert_not_equal pid, new_pid - Process.kill(0, new_pid) - Process.kill(:QUIT, new_pid) -end - -def wait_for_file(path) - tries = DEFAULT_TRIES - while (tries -= 1) > 0 && ! File.exist?(path) - sleep DEFAULT_RES - end - assert File.exist?(path), "path=#{path} exists #{caller.inspect}" -end - -def xfork(&block) - fork do - ObjectSpace.each_object(Tempfile) do |tmp| - ObjectSpace.undefine_finalizer(tmp) - end - yield - end -end - -# can't waitpid on detached processes -def wait_for_death(pid) - tries = DEFAULT_TRIES - while (tries -= 1) > 0 - begin - Process.kill(0, pid) - begin - Process.waitpid(pid, Process::WNOHANG) - rescue Errno::ECHILD - end - sleep(DEFAULT_RES) - rescue Errno::ESRCH - return - end - end - raise "PID:#{pid} never died!" -end - -# executes +cmd+ and chunks its STDOUT -def chunked_spawn(stdout, *cmd) - fork { - crd, cwr = IO.pipe - crd.binmode - cwr.binmode - crd.sync = cwr.sync = true - - pid = fork { - STDOUT.reopen(cwr) - crd.close - cwr.close - exec(*cmd) - } - cwr.close - begin - buf = crd.readpartial(16384) - stdout.write("#{'%x' % buf.size}\r\n#{buf}") - rescue EOFError - stdout.write("0\r\n") - pid, status = Process.waitpid(pid) - exit status.exitstatus - end while true - } -end - -def reset_sig_handlers - sigs = %w(CHLD).concat(Unicorn::HttpServer::QUEUE_SIGS) - sigs.each { |sig| trap(sig, "DEFAULT") } -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_configurator.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_configurator.rb deleted file mode 100644 index 1298f0e..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_configurator.rb +++ /dev/null @@ -1,175 +0,0 @@ -# -*- encoding: binary -*- - -require 'test/unit' -require 'tempfile' -require 'unicorn' - -TestStruct = Struct.new( - *(Unicorn::Configurator::DEFAULTS.keys + %w(listener_opts listeners))) -class TestConfigurator < Test::Unit::TestCase - - def test_config_init - Unicorn::Configurator.new {} - end - - def test_expand_addr - meth = Unicorn::Configurator.new.method(:expand_addr) - - assert_equal "/var/run/unicorn.sock", meth.call("/var/run/unicorn.sock") - assert_equal "#{Dir.pwd}/foo/bar.sock", meth.call("unix:foo/bar.sock") - - path = meth.call("~/foo/bar.sock") - assert_equal "/", path[0..0] - assert_match %r{/foo/bar\.sock\z}, path - - path = meth.call("~root/foo/bar.sock") - assert_equal "/", path[0..0] - assert_match %r{/foo/bar\.sock\z}, path - - assert_equal "1.2.3.4:2007", meth.call('1.2.3.4:2007') - assert_equal "0.0.0.0:2007", meth.call('0.0.0.0:2007') - assert_equal "0.0.0.0:2007", meth.call(':2007') - assert_equal "0.0.0.0:2007", meth.call('*:2007') - assert_equal "0.0.0.0:2007", meth.call('2007') - assert_equal "0.0.0.0:2007", meth.call(2007) - - %w([::1]:2007 [::]:2007).each do |addr| - assert_equal addr, meth.call(addr.dup) - end - - # for Rainbows! users only - assert_equal "[::]:80", meth.call("[::]") - assert_equal "127.6.6.6:80", meth.call("127.6.6.6") - - # the next two aren't portable, consider them unsupported for now - # assert_match %r{\A\d+\.\d+\.\d+\.\d+:2007\z}, meth.call('1:2007') - # assert_match %r{\A\d+\.\d+\.\d+\.\d+:2007\z}, meth.call('2:2007') - end - - def test_config_invalid - tmp = Tempfile.new('unicorn_config') - tmp.syswrite(%q(asdfasdf "hello-world")) - assert_raises(NoMethodError) do - Unicorn::Configurator.new(:config_file => tmp.path) - end - end - - def test_config_non_existent - tmp = Tempfile.new('unicorn_config') - path = tmp.path - tmp.close! - assert_raises(Errno::ENOENT) do - Unicorn::Configurator.new(:config_file => path) - end - end - - def test_config_defaults - cfg = Unicorn::Configurator.new(:use_defaults => true) - test_struct = TestStruct.new - cfg.commit!(test_struct) - Unicorn::Configurator::DEFAULTS.each do |key,value| - assert_equal value, test_struct.__send__(key) - end - end - - def test_config_defaults_skip - cfg = Unicorn::Configurator.new(:use_defaults => true) - skip = [ :logger ] - test_struct = TestStruct.new - cfg.commit!(test_struct, :skip => skip) - Unicorn::Configurator::DEFAULTS.each do |key,value| - next if skip.include?(key) - assert_equal value, test_struct.__send__(key) - end - assert_nil test_struct.logger - end - - def test_listen_options - tmp = Tempfile.new('unicorn_config') - expect = { :sndbuf => 1, :rcvbuf => 2, :backlog => 10 }.freeze - listener = "127.0.0.1:12345" - tmp.syswrite("listen '#{listener}', #{expect.inspect}\n") - cfg = Unicorn::Configurator.new(:config_file => tmp.path) - test_struct = TestStruct.new - cfg.commit!(test_struct) - assert(listener_opts = test_struct.listener_opts) - assert_equal expect, listener_opts[listener] - end - - def test_listen_option_bad - tmp = Tempfile.new('unicorn_config') - expect = { :sndbuf => "five" } - listener = "127.0.0.1:12345" - tmp.syswrite("listen '#{listener}', #{expect.inspect}\n") - assert_raises(ArgumentError) do - Unicorn::Configurator.new(:config_file => tmp.path) - end - end - - def test_listen_option_bad_delay - tmp = Tempfile.new('unicorn_config') - expect = { :delay => "five" } - listener = "127.0.0.1:12345" - tmp.syswrite("listen '#{listener}', #{expect.inspect}\n") - assert_raises(ArgumentError) do - Unicorn::Configurator.new(:config_file => tmp.path) - end - end - - def test_listen_option_float_delay - tmp = Tempfile.new('unicorn_config') - expect = { :delay => 0.5 } - listener = "127.0.0.1:12345" - tmp.syswrite("listen '#{listener}', #{expect.inspect}\n") - Unicorn::Configurator.new(:config_file => tmp.path) - end - - def test_listen_option_int_delay - tmp = Tempfile.new('unicorn_config') - expect = { :delay => 5 } - listener = "127.0.0.1:12345" - tmp.syswrite("listen '#{listener}', #{expect.inspect}\n") - Unicorn::Configurator.new(:config_file => tmp.path) - end - - def test_check_client_connection - tmp = Tempfile.new('unicorn_config') - test_struct = TestStruct.new - tmp.syswrite("check_client_connection true\n") - - assert_nothing_raised do - Unicorn::Configurator.new(:config_file => tmp.path).commit!(test_struct) - end - - assert test_struct.check_client_connection - end - - def test_check_client_connection_with_tcp_bad - tmp = Tempfile.new('unicorn_config') - test_struct = TestStruct.new - listener = "127.0.0.1:12345" - tmp.syswrite("check_client_connection true\n") - tmp.syswrite("listen '#{listener}', :tcp_nopush => true\n") - - assert_raises(ArgumentError) do - Unicorn::Configurator.new(:config_file => tmp.path).commit!(test_struct) - end - end - - def test_after_fork_proc - test_struct = TestStruct.new - [ proc { |a,b| }, Proc.new { |a,b| }, lambda { |a,b| } ].each do |my_proc| - Unicorn::Configurator.new(:after_fork => my_proc).commit!(test_struct) - assert_equal my_proc, test_struct.after_fork - end - end - - def test_after_fork_wrong_arity - [ proc { |a| }, Proc.new { }, lambda { |a,b,c| } ].each do |my_proc| - assert_raises(ArgumentError) do - Unicorn::Configurator.new(:after_fork => my_proc) - end - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_droplet.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_droplet.rb deleted file mode 100644 index 73cf38c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_droplet.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'test/unit' -require 'unicorn' - -class TestDroplet < Test::Unit::TestCase - def test_create_many_droplets - now = Time.now.to_i - tmp = (0..1024).map do |i| - droplet = Unicorn::Worker.new(i) - assert droplet.respond_to?(:tick) - assert_equal 0, droplet.tick - assert_equal(now, droplet.tick = now) - assert_equal now, droplet.tick - assert_equal(0, droplet.tick = 0) - assert_equal 0, droplet.tick - end - end - - def test_shared_process - droplet = Unicorn::Worker.new(0) - _, status = Process.waitpid2(fork { droplet.tick += 1; exit!(0) }) - assert status.success?, status.inspect - assert_equal 1, droplet.tick - - _, status = Process.waitpid2(fork { droplet.tick += 1; exit!(0) }) - assert status.success?, status.inspect - assert_equal 2, droplet.tick - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser.rb deleted file mode 100644 index 8d5b251..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser.rb +++ /dev/null @@ -1,854 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2005 Zed A. Shaw -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) -# -# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html -# for more information. - -require 'test/test_helper' - -include Unicorn - -class HttpParserTest < Test::Unit::TestCase - - def test_parse_simple - parser = HttpParser.new - req = parser.env - http = parser.buf - http << "GET / HTTP/1.1\r\n\r\n" - assert_equal req, parser.parse - assert_equal '', http - - assert_equal 'HTTP/1.1', req['SERVER_PROTOCOL'] - assert_equal '/', req['REQUEST_PATH'] - assert_equal 'HTTP/1.1', req['HTTP_VERSION'] - assert_equal '/', req['REQUEST_URI'] - assert_equal 'GET', req['REQUEST_METHOD'] - assert_nil req['FRAGMENT'] - assert_equal '', req['QUERY_STRING'] - - assert parser.keepalive? - parser.clear - req.clear - - http << "G" - assert_nil parser.parse - assert_equal "G", http - assert req.empty? - - # try parsing again to ensure we were reset correctly - http << "ET /hello-world HTTP/1.1\r\n\r\n" - assert parser.parse - - assert_equal 'HTTP/1.1', req['SERVER_PROTOCOL'] - assert_equal '/hello-world', req['REQUEST_PATH'] - assert_equal 'HTTP/1.1', req['HTTP_VERSION'] - assert_equal '/hello-world', req['REQUEST_URI'] - assert_equal 'GET', req['REQUEST_METHOD'] - assert_nil req['FRAGMENT'] - assert_equal '', req['QUERY_STRING'] - assert_equal '', http - assert parser.keepalive? - end - - def test_tab_lws - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nHost:\tfoo.bar\r\n\r\n" - assert_equal req.object_id, parser.parse.object_id - assert_equal "foo.bar", req['HTTP_HOST'] - end - - def test_connection_close_no_ka - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nConnection: close\r\n\r\n" - assert_equal req.object_id, parser.parse.object_id - assert_equal "GET", req['REQUEST_METHOD'] - assert ! parser.keepalive? - end - - def test_connection_keep_alive_ka - parser = HttpParser.new - req = parser.env - parser.buf << "HEAD / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n" - assert_equal req.object_id, parser.parse.object_id - assert parser.keepalive? - end - - def test_connection_keep_alive_no_body - parser = HttpParser.new - req = parser.env - parser.buf << "POST / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n" - assert_equal req.object_id, parser.parse.object_id - assert parser.keepalive? - end - - def test_connection_keep_alive_no_body_empty - parser = HttpParser.new - req = parser.env - parser.buf << "POST / HTTP/1.1\r\n" \ - "Content-Length: 0\r\n" \ - "Connection: keep-alive\r\n\r\n" - assert_equal req.object_id, parser.parse.object_id - assert parser.keepalive? - end - - def test_connection_keep_alive_ka_bad_version - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.0\r\nConnection: keep-alive\r\n\r\n" - assert_equal req.object_id, parser.parse.object_id - assert parser.keepalive? - end - - def test_parse_server_host_default_port - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nHost: foo\r\n\r\n" - assert_equal req, parser.parse - assert_equal 'foo', req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal '', parser.buf - assert parser.keepalive? - end - - def test_parse_server_host_alt_port - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nHost: foo:999\r\n\r\n" - assert_equal req, parser.parse - assert_equal 'foo', req['SERVER_NAME'] - assert_equal '999', req['SERVER_PORT'] - assert_equal '', parser.buf - assert parser.keepalive? - end - - def test_parse_server_host_empty_port - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nHost: foo:\r\n\r\n" - assert_equal req, parser.parse - assert_equal 'foo', req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal '', parser.buf - assert parser.keepalive? - end - - def test_parse_server_host_xfp_https - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nHost: foo:\r\n" \ - "X-Forwarded-Proto: https\r\n\r\n" - assert_equal req, parser.parse - assert_equal 'foo', req['SERVER_NAME'] - assert_equal '443', req['SERVER_PORT'] - assert_equal '', parser.buf - assert parser.keepalive? - end - - def test_parse_xfp_https_chained - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.0\r\n" \ - "X-Forwarded-Proto: https,http\r\n\r\n" - assert_equal req, parser.parse - assert_equal '443', req['SERVER_PORT'], req.inspect - assert_equal 'https', req['rack.url_scheme'], req.inspect - assert_equal '', parser.buf - end - - def test_parse_xfp_https_chained_backwards - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.0\r\n" \ - "X-Forwarded-Proto: http,https\r\n\r\n" - assert_equal req, parser.parse - assert_equal '80', req['SERVER_PORT'], req.inspect - assert_equal 'http', req['rack.url_scheme'], req.inspect - assert_equal '', parser.buf - end - - def test_parse_xfp_gopher_is_ignored - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.0\r\n" \ - "X-Forwarded-Proto: gopher\r\n\r\n" - assert_equal req, parser.parse - assert_equal '80', req['SERVER_PORT'], req.inspect - assert_equal 'http', req['rack.url_scheme'], req.inspect - assert_equal '', parser.buf - end - - def test_parse_x_forwarded_ssl_on - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.0\r\n" \ - "X-Forwarded-Ssl: on\r\n\r\n" - assert_equal req, parser.parse - assert_equal '443', req['SERVER_PORT'], req.inspect - assert_equal 'https', req['rack.url_scheme'], req.inspect - assert_equal '', parser.buf - end - - def test_parse_x_forwarded_ssl_off - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.0\r\nX-Forwarded-Ssl: off\r\n\r\n" - assert_equal req, parser.parse - assert_equal '80', req['SERVER_PORT'], req.inspect - assert_equal 'http', req['rack.url_scheme'], req.inspect - assert_equal '', parser.buf - end - - def test_parse_strange_headers - parser = HttpParser.new - req = parser.env - should_be_good = "GET / HTTP/1.1\r\naaaaaaaaaaaaa:++++++++++\r\n\r\n" - parser.buf << should_be_good - assert_equal req, parser.parse - assert_equal '', parser.buf - assert parser.keepalive? - end - - # legacy test case from Mongrel that we never supported before... - # I still consider Pound irrelevant, unfortunately stupid clients that - # send extremely big headers do exist and they've managed to find Unicorn... - def test_nasty_pound_header - parser = HttpParser.new - nasty_pound_header = "GET / HTTP/1.1\r\nX-SSL-Bullshit: -----BEGIN CERTIFICATE-----\r\n\tMIIFbTCCBFWgAwIBAgICH4cwDQYJKoZIhvcNAQEFBQAwcDELMAkGA1UEBhMCVUsx\r\n\tETAPBgNVBAoTCGVTY2llbmNlMRIwEAYDVQQLEwlBdXRob3JpdHkxCzAJBgNVBAMT\r\n\tAkNBMS0wKwYJKoZIhvcNAQkBFh5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMu\r\n\tdWswHhcNMDYwNzI3MTQxMzI4WhcNMDcwNzI3MTQxMzI4WjBbMQswCQYDVQQGEwJV\r\n\tSzERMA8GA1UEChMIZVNjaWVuY2UxEzARBgNVBAsTCk1hbmNoZXN0ZXIxCzAJBgNV\r\n\tBAcTmrsogriqMWLAk1DMRcwFQYDVQQDEw5taWNoYWVsIHBhcmQYJKoZIhvcNAQEB\r\n\tBQADggEPADCCAQoCggEBANPEQBgl1IaKdSS1TbhF3hEXSl72G9J+WC/1R64fAcEF\r\n\tW51rEyFYiIeZGx/BVzwXbeBoNUK41OK65sxGuflMo5gLflbwJtHBRIEKAfVVp3YR\r\n\tgW7cMA/s/XKgL1GEC7rQw8lIZT8RApukCGqOVHSi/F1SiFlPDxuDfmdiNzL31+sL\r\n\t0iwHDdNkGjy5pyBSB8Y79dsSJtCW/iaLB0/n8Sj7HgvvZJ7x0fr+RQjYOUUfrePP\r\n\tu2MSpFyf+9BbC/aXgaZuiCvSR+8Snv3xApQY+fULK/xY8h8Ua51iXoQ5jrgu2SqR\r\n\twgA7BUi3G8LFzMBl8FRCDYGUDy7M6QaHXx1ZWIPWNKsCAwEAAaOCAiQwggIgMAwG\r\n\tA1UdEwEB/wQCMAAwEQYJYIZIAYb4QgEBBAQDAgWgMA4GA1UdDwEB/wQEAwID6DAs\r\n\tBglghkgBhvhCAQ0EHxYdVUsgZS1TY2llbmNlIFVzZXIgQ2VydGlmaWNhdGUwHQYD\r\n\tVR0OBBYEFDTt/sf9PeMaZDHkUIldrDYMNTBZMIGaBgNVHSMEgZIwgY+AFAI4qxGj\r\n\tloCLDdMVKwiljjDastqooXSkcjBwMQswCQYDVQQGEwJVSzERMA8GA1UEChMIZVNj\r\n\taWVuY2UxEjAQBgNVBAsTCUF1dGhvcml0eTELMAkGA1UEAxMCQ0ExLTArBgkqhkiG\r\n\t9w0BCQEWHmNhLW9wZXJhdG9yQGdyaWQtc3VwcG9ydC5hYy51a4IBADApBgNVHRIE\r\n\tIjAggR5jYS1vcGVyYXRvckBncmlkLXN1cHBvcnQuYWMudWswGQYDVR0gBBIwEDAO\r\n\tBgwrBgEEAdkvAQEBAQYwPQYJYIZIAYb4QgEEBDAWLmh0dHA6Ly9jYS5ncmlkLXN1\r\n\tcHBvcnQuYWMudmT4sopwqlBWsvcHViL2NybC9jYWNybC5jcmwwPQYJYIZIAYb4QgEDBDAWLmh0\r\n\tdHA6Ly9jYS5ncmlkLXN1cHBvcnQuYWMudWsvcHViL2NybC9jYWNybC5jcmwwPwYD\r\n\tVR0fBDgwNjA0oDKgMIYuaHR0cDovL2NhLmdyaWQt5hYy51ay9wdWIv\r\n\tY3JsL2NhY3JsLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAS/U4iiooBENGW/Hwmmd3\r\n\tXCy6Zrt08YjKCzGNjorT98g8uGsqYjSxv/hmi0qlnlHs+k/3Iobc3LjS5AMYr5L8\r\n\tUO7OSkgFFlLHQyC9JzPfmLCAugvzEbyv4Olnsr8hbxF1MbKZoQxUZtMVu29wjfXk\r\n\thTeApBv7eaKCWpSp7MCbvgzm74izKhu3vlDk9w6qVrxePfGgpKPqfHiOoGhFnbTK\r\n\twTC6o2xq5y0qZ03JonF7OJspEd3I5zKY3E+ov7/ZhW6DqT8UFvsAdjvQbXyhV8Eu\r\n\tYhixw1aKEPzNjNowuIseVogKOLXxWI5vAi5HgXdS0/ES5gDGsABo4fqovUKlgop3\r\n\tRA==\r\n\t-----END CERTIFICATE-----\r\n\r\n" - req = parser.env - parser.buf << nasty_pound_header.dup - - assert nasty_pound_header =~ /(-----BEGIN .*--END CERTIFICATE-----)/m - expect = $1.dup - expect.gsub!(/\r\n\t/, ' ') - assert_equal req, parser.parse - assert_equal '', parser.buf - assert_equal expect, req['HTTP_X_SSL_BULLSHIT'] - end - - def test_continuation_eats_leading_spaces - parser = HttpParser.new - header = "GET / HTTP/1.1\r\n" \ - "X-ASDF: \r\n" \ - "\t\r\n" \ - " \r\n" \ - " ASDF\r\n\r\n" - parser.buf << header - req = parser.env - assert_equal req, parser.parse - assert_equal '', parser.buf - assert_equal 'ASDF', req['HTTP_X_ASDF'] - end - - def test_continuation_eats_scattered_leading_spaces - parser = HttpParser.new - header = "GET / HTTP/1.1\r\n" \ - "X-ASDF: hi\r\n" \ - " y\r\n" \ - "\t\r\n" \ - " x\r\n" \ - " ASDF\r\n\r\n" - req = parser.env - parser.buf << header - assert_equal req, parser.parse - assert_equal '', parser.buf - assert_equal 'hi y x ASDF', req['HTTP_X_ASDF'] - end - - def test_continuation_eats_trailing_spaces - parser = HttpParser.new - header = "GET / HTTP/1.1\r\n" \ - "X-ASDF: \r\n" \ - "\t\r\n" \ - " b \r\n" \ - " ASDF\r\n\r\n" - parser.buf << header - req = parser.env - assert_equal req, parser.parse - assert_equal '', parser.buf - assert_equal 'b ASDF', req['HTTP_X_ASDF'] - end - - def test_continuation_with_absolute_uri_and_ignored_host_header - parser = HttpParser.new - header = "GET http://example.com/ HTTP/1.1\r\n" \ - "Host: \r\n" \ - " YHBT.net\r\n" \ - "\r\n" - parser.buf << header - req = parser.env - assert_equal req, parser.parse - assert_equal 'example.com', req['HTTP_HOST'] - end - - # this may seem to be testing more of an implementation detail, but - # it also helps ensure we're safe in the presence of multiple parsers - # in case we ever go multithreaded/evented... - def test_resumable_continuations - nr = 1000 - header = "GET / HTTP/1.1\r\n" \ - "X-ASDF: \r\n" \ - " hello\r\n" - tmp = [] - nr.times { |i| - parser = HttpParser.new - req = parser.env - parser.buf << "#{header} #{i}\r\n" - assert parser.parse.nil? - asdf = req['HTTP_X_ASDF'] - assert_equal "hello #{i}", asdf - tmp << [ parser, asdf ] - } - tmp.each_with_index { |(parser, asdf), i| - parser.buf << " .\r\n\r\n" - assert parser.parse - assert_equal "hello #{i} .", asdf - } - end - - def test_invalid_continuation - parser = HttpParser.new - header = "GET / HTTP/1.1\r\n" \ - " y\r\n" \ - "Host: hello\r\n" \ - "\r\n" - parser.buf << header - assert_raises(HttpParserError) { parser.parse } - end - - def test_parse_ie6_urls - %w(/some/random/path" - /some/random/path> - /some/random/path< - /we/love/you/ie6?q=<""> - /url?<="&>=" - /mal"formed"? - ).each do |path| - parser = HttpParser.new - req = parser.env - sorta_safe = %(GET #{path} HTTP/1.1\r\n\r\n) - assert_equal req, parser.headers(req, sorta_safe) - assert_equal path, req['REQUEST_URI'] - assert_equal '', sorta_safe - assert parser.keepalive? - end - end - - def test_parse_error - parser = HttpParser.new - req = parser.env - bad_http = "GET / SsUTF/1.1" - - assert_raises(HttpParserError) { parser.headers(req, bad_http) } - - # make sure we can recover - parser.clear - req.clear - assert_equal req, parser.headers(req, "GET / HTTP/1.0\r\n\r\n") - assert ! parser.keepalive? - end - - def test_piecemeal - parser = HttpParser.new - req = parser.env - http = "GET" - assert_nil parser.headers(req, http) - assert_nil parser.headers(req, http) - assert_nil parser.headers(req, http << " / HTTP/1.0") - assert_equal '/', req['REQUEST_PATH'] - assert_equal '/', req['REQUEST_URI'] - assert_equal 'GET', req['REQUEST_METHOD'] - assert_nil parser.headers(req, http << "\r\n") - assert_equal 'HTTP/1.0', req['HTTP_VERSION'] - assert_nil parser.headers(req, http << "\r") - assert_equal req, parser.headers(req, http << "\n") - assert_equal 'HTTP/1.0', req['SERVER_PROTOCOL'] - assert_nil req['FRAGMENT'] - assert_equal '', req['QUERY_STRING'] - assert_equal "", http - assert ! parser.keepalive? - end - - # not common, but underscores do appear in practice - def test_absolute_uri_underscores - parser = HttpParser.new - req = parser.env - http = "GET http://under_score.example.com/foo?q=bar HTTP/1.0\r\n\r\n" - parser.buf << http - assert_equal req, parser.parse - assert_equal 'http', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - assert_equal 'under_score.example.com', req['HTTP_HOST'] - assert_equal 'under_score.example.com', req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal "", parser.buf - assert ! parser.keepalive? - end - - # some dumb clients add users because they're stupid - def test_absolute_uri_w_user - parser = HttpParser.new - req = parser.env - http = "GET http://user%20space@example.com/foo?q=bar HTTP/1.0\r\n\r\n" - parser.buf << http - assert_equal req, parser.parse - assert_equal 'http', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - assert_equal 'example.com', req['HTTP_HOST'] - assert_equal 'example.com', req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal "", parser.buf - assert ! parser.keepalive? - end - - # since Mongrel supported anything URI.parse supported, we're stuck - # supporting everything URI.parse supports - def test_absolute_uri_uri_parse - "#{URI::REGEXP::PATTERN::UNRESERVED};:&=+$,".split(//).each do |char| - parser = HttpParser.new - req = parser.env - http = "GET http://#{char}@example.com/ HTTP/1.0\r\n\r\n" - assert_equal req, parser.headers(req, http) - assert_equal 'http', req['rack.url_scheme'] - assert_equal '/', req['REQUEST_URI'] - assert_equal '/', req['REQUEST_PATH'] - assert_equal '', req['QUERY_STRING'] - - assert_equal 'example.com', req['HTTP_HOST'] - assert_equal 'example.com', req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal "", http - assert ! parser.keepalive? - end - end - - def test_absolute_uri - parser = HttpParser.new - req = parser.env - parser.buf << "GET http://example.com/foo?q=bar HTTP/1.0\r\n\r\n" - assert_equal req, parser.parse - assert_equal 'http', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - assert_equal 'example.com', req['HTTP_HOST'] - assert_equal 'example.com', req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal "", parser.buf - assert ! parser.keepalive? - end - - # X-Forwarded-Proto is not in rfc2616, absolute URIs are, however... - def test_absolute_uri_https - parser = HttpParser.new - req = parser.env - http = "GET https://example.com/foo?q=bar HTTP/1.1\r\n" \ - "X-Forwarded-Proto: http\r\n\r\n" - parser.buf << http - assert_equal req, parser.parse - assert_equal 'https', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - assert_equal 'example.com', req['HTTP_HOST'] - assert_equal 'example.com', req['SERVER_NAME'] - assert_equal '443', req['SERVER_PORT'] - assert_equal "", parser.buf - assert parser.keepalive? - end - - # Host: header should be ignored for absolute URIs - def test_absolute_uri_with_port - parser = HttpParser.new - req = parser.env - parser.buf << "GET http://example.com:8080/foo?q=bar HTTP/1.2\r\n" \ - "Host: bad.example.com\r\n\r\n" - assert_equal req, parser.parse - assert_equal 'http', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - assert_equal 'example.com:8080', req['HTTP_HOST'] - assert_equal 'example.com', req['SERVER_NAME'] - assert_equal '8080', req['SERVER_PORT'] - assert_equal "", parser.buf - assert ! parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_absolute_uri_with_empty_port - parser = HttpParser.new - req = parser.env - parser.buf << "GET https://example.com:/foo?q=bar HTTP/1.1\r\n" \ - "Host: bad.example.com\r\n\r\n" - assert_equal req, parser.parse - assert_equal 'https', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - assert_equal 'example.com:', req['HTTP_HOST'] - assert_equal 'example.com', req['SERVER_NAME'] - assert_equal '443', req['SERVER_PORT'] - assert_equal "", parser.buf - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_absolute_ipv6_uri - parser = HttpParser.new - req = parser.env - url = "http://[::1]/foo?q=bar" - http = "GET #{url} HTTP/1.1\r\n" \ - "Host: bad.example.com\r\n\r\n" - assert_equal req, parser.headers(req, http) - assert_equal 'http', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - uri = URI.parse(url) - assert_equal "[::1]", uri.host, - "URI.parse changed upstream for #{url}? host=#{uri.host}" - assert_equal "[::1]", req['HTTP_HOST'] - assert_equal "[::1]", req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal "", http - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_absolute_ipv6_uri_alpha - parser = HttpParser.new - req = parser.env - url = "http://[::a]/" - http = "GET #{url} HTTP/1.1\r\n" \ - "Host: bad.example.com\r\n\r\n" - assert_equal req, parser.headers(req, http) - assert_equal 'http', req['rack.url_scheme'] - - uri = URI.parse(url) - assert_equal "[::a]", uri.host, - "URI.parse changed upstream for #{url}? host=#{uri.host}" - assert_equal "[::a]", req['HTTP_HOST'] - assert_equal "[::a]", req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - end - - def test_absolute_ipv6_uri_alpha_2 - parser = HttpParser.new - req = parser.env - url = "http://[::B]/" - http = "GET #{url} HTTP/1.1\r\n" \ - "Host: bad.example.com\r\n\r\n" - assert_equal req, parser.headers(req, http) - assert_equal 'http', req['rack.url_scheme'] - - uri = URI.parse(url) - assert_equal "[::B]", uri.host, - "URI.parse changed upstream for #{url}? host=#{uri.host}" - assert_equal "[::B]", req['HTTP_HOST'] - assert_equal "[::B]", req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - end - - def test_absolute_ipv6_uri_with_empty_port - parser = HttpParser.new - req = parser.env - url = "https://[::1]:/foo?q=bar" - http = "GET #{url} HTTP/1.1\r\n" \ - "Host: bad.example.com\r\n\r\n" - assert_equal req, parser.headers(req, http) - assert_equal 'https', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - uri = URI.parse(url) - assert_equal "[::1]", uri.host, - "URI.parse changed upstream for #{url}? host=#{uri.host}" - assert_equal "[::1]:", req['HTTP_HOST'] - assert_equal "[::1]", req['SERVER_NAME'] - assert_equal '443', req['SERVER_PORT'] - assert_equal "", http - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_absolute_ipv6_uri_with_port - parser = HttpParser.new - req = parser.env - url = "https://[::1]:666/foo?q=bar" - http = "GET #{url} HTTP/1.1\r\n" \ - "Host: bad.example.com\r\n\r\n" - assert_equal req, parser.headers(req, http) - assert_equal 'https', req['rack.url_scheme'] - assert_equal '/foo?q=bar', req['REQUEST_URI'] - assert_equal '/foo', req['REQUEST_PATH'] - assert_equal 'q=bar', req['QUERY_STRING'] - - uri = URI.parse(url) - assert_equal "[::1]", uri.host, - "URI.parse changed upstream for #{url}? host=#{uri.host}" - assert_equal "[::1]:666", req['HTTP_HOST'] - assert_equal "[::1]", req['SERVER_NAME'] - assert_equal '666', req['SERVER_PORT'] - assert_equal "", http - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_ipv6_host_header - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\n" \ - "Host: [::1]\r\n\r\n" - assert_equal req, parser.parse - assert_equal "[::1]", req['HTTP_HOST'] - assert_equal "[::1]", req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal "", parser.buf - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_ipv6_host_header_with_port - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\n" \ - "Host: [::1]:666\r\n\r\n" - assert_equal req, parser.parse - assert_equal "[::1]", req['SERVER_NAME'] - assert_equal '666', req['SERVER_PORT'] - assert_equal "[::1]:666", req['HTTP_HOST'] - assert_equal "", parser.buf - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_ipv6_host_header_with_empty_port - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nHost: [::1]:\r\n\r\n" - assert_equal req, parser.parse - assert_equal "[::1]", req['SERVER_NAME'] - assert_equal '80', req['SERVER_PORT'] - assert_equal "[::1]:", req['HTTP_HOST'] - assert_equal "", parser.buf - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - # XXX Highly unlikely..., just make sure we don't segfault or assert on it - def test_broken_ipv6_host_header - parser = HttpParser.new - req = parser.env - parser.buf << "GET / HTTP/1.1\r\nHost: [::1:\r\n\r\n" - assert_equal req, parser.parse - assert_equal "[", req['SERVER_NAME'] - assert_equal ':1:', req['SERVER_PORT'] - assert_equal "[::1:", req['HTTP_HOST'] - assert_equal "", parser.buf - end - - def test_put_body_oneshot - parser = HttpParser.new - req = parser.env - parser.buf << "PUT / HTTP/1.0\r\nContent-Length: 5\r\n\r\nabcde" - assert_equal req, parser.parse - assert_equal '/', req['REQUEST_PATH'] - assert_equal '/', req['REQUEST_URI'] - assert_equal 'PUT', req['REQUEST_METHOD'] - assert_equal 'HTTP/1.0', req['HTTP_VERSION'] - assert_equal 'HTTP/1.0', req['SERVER_PROTOCOL'] - assert_equal "abcde", parser.buf - assert ! parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_put_body_later - parser = HttpParser.new - req = parser.env - parser.buf << "PUT /l HTTP/1.0\r\nContent-Length: 5\r\n\r\n" - assert_equal req, parser.parse - assert_equal '/l', req['REQUEST_PATH'] - assert_equal '/l', req['REQUEST_URI'] - assert_equal 'PUT', req['REQUEST_METHOD'] - assert_equal 'HTTP/1.0', req['HTTP_VERSION'] - assert_equal 'HTTP/1.0', req['SERVER_PROTOCOL'] - assert_equal "", parser.buf - assert ! parser.keepalive? # TODO: read HTTP/1.2 when it's final - end - - def test_unknown_methods - %w(GETT HEADR XGET XHEAD).each { |m| - parser = HttpParser.new - req = parser.env - s = "#{m} /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n\r\n" - ok = parser.headers(req, s) - assert ok - assert_equal '/forums/1/topics/2375?page=1', req['REQUEST_URI'] - assert_equal 'posts-17408', req['FRAGMENT'] - assert_equal 'page=1', req['QUERY_STRING'] - assert_equal "", s - assert_equal m, req['REQUEST_METHOD'] - assert parser.keepalive? # TODO: read HTTP/1.2 when it's final - } - end - - def test_fragment_in_uri - parser = HttpParser.new - req = parser.env - get = "GET /forums/1/topics/2375?page=1#posts-17408 HTTP/1.1\r\n\r\n" - parser.buf << get - ok = parser.parse - assert ok - assert_equal '/forums/1/topics/2375?page=1', req['REQUEST_URI'] - assert_equal 'posts-17408', req['FRAGMENT'] - assert_equal 'page=1', req['QUERY_STRING'] - assert_equal '', parser.buf - assert parser.keepalive? - end - - # lame random garbage maker - def rand_data(min, max, readable=true) - count = min + ((rand(max)+1) *10).to_i - res = count.to_s + "/" - - if readable - res << Digest::SHA1.hexdigest(rand(count * 100).to_s) * (count / 40) - else - res << Digest::SHA1.digest(rand(count * 100).to_s) * (count / 20) - end - - return res - end - - - def test_horrible_queries - parser = HttpParser.new - - # then that large header names are caught - 10.times do |c| - get = "GET /#{rand_data(10,120)} HTTP/1.1\r\nX-#{rand_data(1024, 1024+(c*1024))}: Test\r\n\r\n" - assert_raises(Unicorn::HttpParserError,Unicorn::RequestURITooLongError) do - parser.buf << get - parser.parse - parser.clear - end - end - - # then that large mangled field values are caught - 10.times do |c| - get = "GET /#{rand_data(10,120)} HTTP/1.1\r\nX-Test: #{rand_data(1024, 1024+(c*1024), false)}\r\n\r\n" - assert_raises(Unicorn::HttpParserError,Unicorn::RequestURITooLongError) do - parser.buf << get - parser.parse - parser.clear - end - end - - # then large headers are rejected too - get = "GET /#{rand_data(10,120)} HTTP/1.1\r\n" - get << "X-Test: test\r\n" * (80 * 1024) - parser.buf << get - assert_raises(Unicorn::HttpParserError,Unicorn::RequestURITooLongError) do - parser.parse - end - parser.clear - - # finally just that random garbage gets blocked all the time - 10.times do |c| - get = "GET #{rand_data(1024, 1024+(c*1024), false)} #{rand_data(1024, 1024+(c*1024), false)}\r\n\r\n" - assert_raises(Unicorn::HttpParserError,Unicorn::RequestURITooLongError) do - parser.buf << get - parser.parse - parser.clear - end - end - - end - - def test_leading_tab - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost:\texample.com\r\n\r\n" - assert parser.add_parse(get) - assert_equal 'example.com', parser.env['HTTP_HOST'] - end - - def test_trailing_whitespace - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost: example.com \r\n\r\n" - assert parser.add_parse(get) - assert_equal 'example.com', parser.env['HTTP_HOST'] - end - - def test_trailing_tab - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost: example.com\t\r\n\r\n" - assert parser.add_parse(get) - assert_equal 'example.com', parser.env['HTTP_HOST'] - end - - def test_trailing_multiple_linear_whitespace - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost: example.com\t \t \t\r\n\r\n" - assert parser.add_parse(get) - assert_equal 'example.com', parser.env['HTTP_HOST'] - end - - def test_embedded_linear_whitespace_ok - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nX-Space: hello\t world\t \r\n\r\n" - assert parser.add_parse(get) - assert_equal "hello\t world", parser.env["HTTP_X_SPACE"] - end - - def test_null_byte_header - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost: \0\r\n\r\n" - assert_raises(HttpParserError) { parser.add_parse(get) } - end - - def test_null_byte_in_middle - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost: hello\0world\r\n\r\n" - assert_raises(HttpParserError) { parser.add_parse(get) } - end - - def test_null_byte_at_end - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost: hello\0\r\n\r\n" - assert_raises(HttpParserError) { parser.add_parse(get) } - end - - def test_empty_header - parser = HttpParser.new - get = "GET / HTTP/1.1\r\nHost: \r\n\r\n" - assert parser.add_parse(get) - assert_equal '', parser.env['HTTP_HOST'] - end - - # so we don't care about the portability of this test - # if it doesn't leak on Linux, it won't leak anywhere else - # unless your C compiler or platform is otherwise broken - LINUX_PROC_PID_STATUS = "/proc/self/status" - def test_memory_leak - match_rss = /^VmRSS:\s+(\d+)/ - if File.read(LINUX_PROC_PID_STATUS) =~ match_rss - before = $1.to_i - 1000000.times { Unicorn::HttpParser.new } - File.read(LINUX_PROC_PID_STATUS) =~ match_rss - after = $1.to_i - diff = after - before - assert(diff < 10000, "memory grew more than 10M: #{diff}") - end - end if RUBY_PLATFORM =~ /linux/ && - File.readable?(LINUX_PROC_PID_STATUS) && - !defined?(RUBY_ENGINE) - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser_ng.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser_ng.rb deleted file mode 100644 index ab335ac..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser_ng.rb +++ /dev/null @@ -1,731 +0,0 @@ -# -*- encoding: binary -*- - -require 'test/test_helper' -require 'digest/md5' - -include Unicorn - -class HttpParserNgTest < Test::Unit::TestCase - - def setup - HttpParser.keepalive_requests = HttpParser::KEEPALIVE_REQUESTS_DEFAULT - @parser = HttpParser.new - end - - def test_next_clear - r = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" - @parser.buf << r - @parser.parse - @parser.response_start_sent = true - assert @parser.keepalive? - assert @parser.next? - assert @parser.response_start_sent - - # persistent client makes another request: - @parser.buf << r - @parser.parse - assert @parser.keepalive? - assert @parser.next? - assert_equal false, @parser.response_start_sent - end - - def test_keepalive_requests_default_constant - assert_kind_of Integer, HttpParser::KEEPALIVE_REQUESTS_DEFAULT - assert HttpParser::KEEPALIVE_REQUESTS_DEFAULT >= 0 - end - - def test_keepalive_requests_setting - HttpParser.keepalive_requests = 0 - assert_equal 0, HttpParser.keepalive_requests - HttpParser.keepalive_requests = nil - assert HttpParser.keepalive_requests >= 0xffffffff - HttpParser.keepalive_requests = 1 - assert_equal 1, HttpParser.keepalive_requests - HttpParser.keepalive_requests = 666 - assert_equal 666, HttpParser.keepalive_requests - - assert_raises(TypeError) { HttpParser.keepalive_requests = "666" } - assert_raises(TypeError) { HttpParser.keepalive_requests = [] } - end - - def test_connection_TE - @parser.buf << "GET / HTTP/1.1\r\nHost: example.com\r\nConnection: TE\r\n" - @parser.buf << "TE: trailers\r\n\r\n" - @parser.parse - assert @parser.keepalive? - assert @parser.next? - end - - def test_keepalive_requests_with_next? - req = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n".freeze - expect = { - "SERVER_NAME" => "example.com", - "HTTP_HOST" => "example.com", - "rack.url_scheme" => "http", - "REQUEST_PATH" => "/", - "SERVER_PROTOCOL" => "HTTP/1.1", - "PATH_INFO" => "/", - "HTTP_VERSION" => "HTTP/1.1", - "REQUEST_URI" => "/", - "SERVER_PORT" => "80", - "REQUEST_METHOD" => "GET", - "QUERY_STRING" => "" - }.freeze - HttpParser::KEEPALIVE_REQUESTS_DEFAULT.times do |nr| - @parser.buf << req - assert_equal expect, @parser.parse - assert @parser.next? - end - @parser.buf << req - assert_equal expect, @parser.parse - assert ! @parser.next? - end - - def test_fewer_keepalive_requests_with_next? - HttpParser.keepalive_requests = 5 - @parser = HttpParser.new - req = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n".freeze - expect = { - "SERVER_NAME" => "example.com", - "HTTP_HOST" => "example.com", - "rack.url_scheme" => "http", - "REQUEST_PATH" => "/", - "SERVER_PROTOCOL" => "HTTP/1.1", - "PATH_INFO" => "/", - "HTTP_VERSION" => "HTTP/1.1", - "REQUEST_URI" => "/", - "SERVER_PORT" => "80", - "REQUEST_METHOD" => "GET", - "QUERY_STRING" => "" - }.freeze - 5.times do |nr| - @parser.buf << req - assert_equal expect, @parser.parse - assert @parser.next? - end - @parser.buf << req - assert_equal expect, @parser.parse - assert ! @parser.next? - end - - def test_default_keepalive_is_off - assert ! @parser.keepalive? - assert ! @parser.next? - @parser.buf << "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" - @parser.parse - assert @parser.keepalive? - @parser.clear - assert ! @parser.keepalive? - assert ! @parser.next? - end - - def test_identity_byte_headers - req = @parser.env - str = "PUT / HTTP/1.1\r\n" - str << "Content-Length: 123\r\n" - str << "\r" - hdr = @parser.buf - str.each_byte { |byte| - hdr << byte.chr - assert_nil @parser.parse - } - hdr << "\n" - assert_equal req.object_id, @parser.parse.object_id - assert_equal '123', req['CONTENT_LENGTH'] - assert_equal 0, hdr.size - assert ! @parser.keepalive? - assert @parser.headers? - assert_equal 123, @parser.content_length - dst = "" - buf = '.' * 123 - @parser.filter_body(dst, buf) - assert_equal '.' * 123, dst - assert_equal "", buf - assert @parser.keepalive? - end - - def test_identity_step_headers - req = @parser.env - str = @parser.buf - str << "PUT / HTTP/1.1\r\n" - assert ! @parser.parse - str << "Content-Length: 123\r\n" - assert ! @parser.parse - str << "\r\n" - assert_equal req.object_id, @parser.parse.object_id - assert_equal '123', req['CONTENT_LENGTH'] - assert_equal 0, str.size - assert ! @parser.keepalive? - assert @parser.headers? - dst = "" - buf = '.' * 123 - @parser.filter_body(dst, buf) - assert_equal '.' * 123, dst - assert_equal "", buf - assert @parser.keepalive? - end - - def test_identity_oneshot_header - req = @parser.env - str = @parser.buf - str << "PUT / HTTP/1.1\r\nContent-Length: 123\r\n\r\n" - assert_equal req.object_id, @parser.parse.object_id - assert_equal '123', req['CONTENT_LENGTH'] - assert_equal 0, str.size - assert ! @parser.keepalive? - assert @parser.headers? - dst = "" - buf = '.' * 123 - @parser.filter_body(dst, buf) - assert_equal '.' * 123, dst - assert_equal "", buf - end - - def test_identity_oneshot_header_with_body - body = ('a' * 123).freeze - req = @parser.env - str = @parser.buf - str << "PUT / HTTP/1.1\r\n" \ - "Content-Length: #{body.length}\r\n" \ - "\r\n#{body}" - assert_equal req.object_id, @parser.parse.object_id - assert_equal '123', req['CONTENT_LENGTH'] - assert_equal 123, str.size - assert_equal body, str - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal 0, str.size - assert_equal tmp, body - assert_equal "", @parser.filter_body(tmp, str) - assert @parser.keepalive? - end - - def test_identity_oneshot_header_with_body_partial - str = @parser.buf - str << "PUT / HTTP/1.1\r\nContent-Length: 123\r\n\r\na" - assert_equal Hash, @parser.parse.class - assert_equal 1, str.size - assert_equal 'a', str - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal "", str - assert_equal "a", tmp - str << ' ' * 122 - rv = @parser.filter_body(tmp, str) - assert_equal 122, tmp.size - assert_nil rv - assert_equal "", str - assert_equal str.object_id, @parser.filter_body(tmp, str).object_id - assert @parser.keepalive? - end - - def test_identity_oneshot_header_with_body_slop - str = @parser.buf - str << "PUT / HTTP/1.1\r\nContent-Length: 1\r\n\r\naG" - assert_equal Hash, @parser.parse.class - assert_equal 2, str.size - assert_equal 'aG', str - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal "G", str - assert_equal "G", @parser.filter_body(tmp, str) - assert_equal 1, tmp.size - assert_equal "a", tmp - assert @parser.keepalive? - end - - def test_chunked - str = @parser.buf - req = @parser.env - str << "PUT / HTTP/1.1\r\ntransfer-Encoding: chunked\r\n\r\n" - assert_equal req, @parser.parse, "msg=#{str}" - assert_equal 0, str.size - tmp = "" - assert_nil @parser.filter_body(tmp, str << "6") - assert_equal 0, tmp.size - assert_nil @parser.filter_body(tmp, str << "\r\n") - assert_equal 0, str.size - assert_equal 0, tmp.size - tmp = "" - assert_nil @parser.filter_body(tmp, str << "..") - assert_equal "..", tmp - assert_nil @parser.filter_body(tmp, str << "abcd\r\n0\r\n") - assert_equal "abcd", tmp - assert_equal str.object_id, @parser.filter_body(tmp, str << "PUT").object_id - assert_equal "PUT", str - assert ! @parser.keepalive? - str << "TY: FOO\r\n\r\n" - assert_equal req, @parser.parse - assert_equal "FOO", req["HTTP_PUTTY"] - assert @parser.keepalive? - end - - def test_chunked_empty - str = @parser.buf - req = @parser.env - str << "PUT / HTTP/1.1\r\ntransfer-Encoding: chunked\r\n\r\n" - assert_equal req, @parser.parse, "msg=#{str}" - assert_equal 0, str.size - tmp = "" - assert_equal str, @parser.filter_body(tmp, str << "0\r\n\r\n") - assert_equal "", tmp - end - - def test_two_chunks - str = @parser.buf - str << "PUT / HTTP/1.1\r\ntransfer-Encoding: chunked\r\n\r\n" - req = @parser.env - assert_equal req, @parser.parse - assert_equal 0, str.size - tmp = "" - assert_nil @parser.filter_body(tmp, str << "6") - assert_equal 0, tmp.size - assert_nil @parser.filter_body(tmp, str << "\r\n") - assert_equal "", str - assert_equal 0, tmp.size - tmp = "" - assert_nil @parser.filter_body(tmp, str << "..") - assert_equal 2, tmp.size - assert_equal "..", tmp - assert_nil @parser.filter_body(tmp, str << "abcd\r\n1") - assert_equal "abcd", tmp - assert_nil @parser.filter_body(tmp, str << "\r") - assert_equal "", tmp - assert_nil @parser.filter_body(tmp, str << "\n") - assert_equal "", tmp - assert_nil @parser.filter_body(tmp, str << "z") - assert_equal "z", tmp - assert_nil @parser.filter_body(tmp, str << "\r\n") - assert_nil @parser.filter_body(tmp, str << "0") - assert_nil @parser.filter_body(tmp, str << "\r") - rv = @parser.filter_body(tmp, str << "\nGET") - assert_equal "GET", rv - assert_equal str.object_id, rv.object_id - assert ! @parser.keepalive? - end - - def test_big_chunk - str = @parser.buf - str << "PUT / HTTP/1.1\r\ntransfer-Encoding: chunked\r\n\r\n" \ - "4000\r\nabcd" - req = @parser.env - assert_equal req, @parser.parse - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal '', str - str << ' ' * 16300 - assert_nil @parser.filter_body(tmp, str) - assert_equal '', str - str << ' ' * 80 - assert_nil @parser.filter_body(tmp, str) - assert_equal '', str - assert ! @parser.body_eof? - assert_equal "", @parser.filter_body(tmp, str << "\r\n0\r\n") - assert_equal "", tmp - assert @parser.body_eof? - str << "\r\n" - assert_equal req, @parser.parse - assert_equal "", str - assert @parser.body_eof? - assert @parser.keepalive? - end - - def test_two_chunks_oneshot - str = @parser.buf - req = @parser.env - str << "PUT / HTTP/1.1\r\ntransfer-Encoding: chunked\r\n\r\n" \ - "1\r\na\r\n2\r\n..\r\n0\r\n" - assert_equal req, @parser.parse - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal 'a..', tmp - rv = @parser.filter_body(tmp, str) - assert_equal rv.object_id, str.object_id - assert ! @parser.keepalive? - end - - def test_chunks_bytewise - chunked = "10\r\nabcdefghijklmnop\r\n11\r\n0123456789abcdefg\r\n0\r\n" - str = "PUT / HTTP/1.1\r\ntransfer-Encoding: chunked\r\n\r\n" - buf = @parser.buf - buf << str - req = @parser.env - assert_equal req, @parser.parse - assert_equal "", buf - tmp = '' - body = '' - str = chunked[0..-2] - str.each_byte { |byte| - assert_nil @parser.filter_body(tmp, buf << byte.chr) - body << tmp - } - assert_equal 'abcdefghijklmnop0123456789abcdefg', body - rv = @parser.filter_body(tmp, buf<< "\n") - assert_equal rv.object_id, buf.object_id - assert ! @parser.keepalive? - end - - def test_trailers - req = @parser.env - str = @parser.buf - str << "PUT / HTTP/1.1\r\n" \ - "Trailer: Content-MD5\r\n" \ - "transfer-Encoding: chunked\r\n\r\n" \ - "1\r\na\r\n2\r\n..\r\n0\r\n" - assert_equal req, @parser.parse - assert_equal 'Content-MD5', req['HTTP_TRAILER'] - assert_nil req['HTTP_CONTENT_MD5'] - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal 'a..', tmp - md5_b64 = [ Digest::MD5.digest(tmp) ].pack('m').strip.freeze - rv = @parser.filter_body(tmp, str) - assert_equal rv.object_id, str.object_id - assert_equal '', str - md5_hdr = "Content-MD5: #{md5_b64}\r\n".freeze - str << md5_hdr - assert_nil @parser.trailers(req, str) - assert_equal md5_b64, req['HTTP_CONTENT_MD5'] - assert_equal "CONTENT_MD5: #{md5_b64}\r\n", str - str << "\r" - assert_nil @parser.parse - str << "\nGET / " - assert_equal req, @parser.parse - assert_equal "GET / ", str - assert @parser.keepalive? - end - - def test_trailers_slowly - str = @parser.buf - str << "PUT / HTTP/1.1\r\n" \ - "Trailer: Content-MD5\r\n" \ - "transfer-Encoding: chunked\r\n\r\n" \ - "1\r\na\r\n2\r\n..\r\n0\r\n" - req = @parser.env - assert_equal req, @parser.parse - assert_equal 'Content-MD5', req['HTTP_TRAILER'] - assert_nil req['HTTP_CONTENT_MD5'] - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal 'a..', tmp - md5_b64 = [ Digest::MD5.digest(tmp) ].pack('m').strip.freeze - rv = @parser.filter_body(tmp, str) - assert_equal rv.object_id, str.object_id - assert_equal '', str - assert_nil @parser.trailers(req, str) - md5_hdr = "Content-MD5: #{md5_b64}\r\n".freeze - md5_hdr.each_byte { |byte| - str << byte.chr - assert_nil @parser.trailers(req, str) - } - assert_equal md5_b64, req['HTTP_CONTENT_MD5'] - assert_equal "CONTENT_MD5: #{md5_b64}\r\n", str - str << "\r" - assert_nil @parser.parse - str << "\n" - assert_equal req, @parser.parse - end - - def test_max_chunk - str = @parser.buf - str << "PUT / HTTP/1.1\r\n" \ - "transfer-Encoding: chunked\r\n\r\n" \ - "#{HttpParser::CHUNK_MAX.to_s(16)}\r\na\r\n2\r\n..\r\n0\r\n" - req = @parser.env - assert_equal req, @parser.parse - assert_nil @parser.content_length - @parser.filter_body('', str) - assert ! @parser.keepalive? - end - - def test_max_body - n = HttpParser::LENGTH_MAX - @parser.buf << "PUT / HTTP/1.1\r\nContent-Length: #{n}\r\n\r\n" - req = @parser.env - @parser.headers(req, @parser.buf) - assert_equal n, req['CONTENT_LENGTH'].to_i - assert ! @parser.keepalive? - end - - def test_overflow_chunk - n = HttpParser::CHUNK_MAX + 1 - str = @parser.buf - req = @parser.env - str << "PUT / HTTP/1.1\r\n" \ - "transfer-Encoding: chunked\r\n\r\n" \ - "#{n.to_s(16)}\r\na\r\n2\r\n..\r\n0\r\n" - assert_equal req, @parser.parse - assert_nil @parser.content_length - assert_raise(HttpParserError) { @parser.filter_body('', str) } - end - - def test_overflow_content_length - n = HttpParser::LENGTH_MAX + 1 - @parser.buf << "PUT / HTTP/1.1\r\nContent-Length: #{n}\r\n\r\n" - assert_raise(HttpParserError) { @parser.parse } - end - - def test_bad_chunk - @parser.buf << "PUT / HTTP/1.1\r\n" \ - "transfer-Encoding: chunked\r\n\r\n" \ - "#zzz\r\na\r\n2\r\n..\r\n0\r\n" - req = @parser.env - assert_equal req, @parser.parse - assert_nil @parser.content_length - assert_raise(HttpParserError) { @parser.filter_body("", @parser.buf) } - end - - def test_bad_content_length - @parser.buf << "PUT / HTTP/1.1\r\nContent-Length: 7ff\r\n\r\n" - assert_raise(HttpParserError) { @parser.parse } - end - - def test_bad_trailers - str = @parser.buf - req = @parser.env - str << "PUT / HTTP/1.1\r\n" \ - "Trailer: Transfer-Encoding\r\n" \ - "transfer-Encoding: chunked\r\n\r\n" \ - "1\r\na\r\n2\r\n..\r\n0\r\n" - assert_equal req, @parser.parse - assert_equal 'Transfer-Encoding', req['HTTP_TRAILER'] - tmp = '' - assert_nil @parser.filter_body(tmp, str) - assert_equal 'a..', tmp - assert_equal '', str - str << "Transfer-Encoding: identity\r\n\r\n" - assert_raise(HttpParserError) { @parser.parse } - end - - def test_repeat_headers - str = "PUT / HTTP/1.1\r\n" \ - "Trailer: Content-MD5\r\n" \ - "Trailer: Content-SHA1\r\n" \ - "transfer-Encoding: chunked\r\n\r\n" \ - "1\r\na\r\n2\r\n..\r\n0\r\n" - req = @parser.env - @parser.buf << str - assert_equal req, @parser.parse - assert_equal 'Content-MD5,Content-SHA1', req['HTTP_TRAILER'] - assert ! @parser.keepalive? - end - - def test_parse_simple_request - parser = HttpParser.new - req = parser.env - parser.buf << "GET /read-rfc1945-if-you-dont-believe-me\r\n" - assert_equal req, parser.parse - assert_equal '', parser.buf - expect = { - "SERVER_NAME"=>"localhost", - "rack.url_scheme"=>"http", - "REQUEST_PATH"=>"/read-rfc1945-if-you-dont-believe-me", - "PATH_INFO"=>"/read-rfc1945-if-you-dont-believe-me", - "REQUEST_URI"=>"/read-rfc1945-if-you-dont-believe-me", - "SERVER_PORT"=>"80", - "SERVER_PROTOCOL"=>"HTTP/0.9", - "REQUEST_METHOD"=>"GET", - "QUERY_STRING"=>"" - } - assert_equal expect, req - assert ! parser.headers? - end - - def test_path_info_semicolon - qs = "QUERY_STRING" - pi = "PATH_INFO" - req = {} - str = "GET %s HTTP/1.1\r\nHost: example.com\r\n\r\n" - { - "/1;a=b?c=d&e=f" => { qs => "c=d&e=f", pi => "/1;a=b" }, - "/1?c=d&e=f" => { qs => "c=d&e=f", pi => "/1" }, - "/1;a=b" => { qs => "", pi => "/1;a=b" }, - "/1;a=b?" => { qs => "", pi => "/1;a=b" }, - "/1?a=b;c=d&e=f" => { qs => "a=b;c=d&e=f", pi => "/1" }, - "*" => { qs => "", pi => "" }, - }.each do |uri,expect| - assert_equal req, @parser.headers(req.clear, str % [ uri ]) - req = req.dup - @parser.clear - assert_equal uri, req["REQUEST_URI"], "REQUEST_URI mismatch" - assert_equal expect[qs], req[qs], "#{qs} mismatch" - assert_equal expect[pi], req[pi], "#{pi} mismatch" - next if uri == "*" - uri = URI.parse("http://example.com#{uri}") - assert_equal uri.query.to_s, req[qs], "#{qs} mismatch URI.parse disagrees" - assert_equal uri.path, req[pi], "#{pi} mismatch URI.parse disagrees" - end - end - - def test_path_info_semicolon_absolute - qs = "QUERY_STRING" - pi = "PATH_INFO" - req = {} - str = "GET http://example.com%s HTTP/1.1\r\nHost: www.example.com\r\n\r\n" - { - "/1;a=b?c=d&e=f" => { qs => "c=d&e=f", pi => "/1;a=b" }, - "/1?c=d&e=f" => { qs => "c=d&e=f", pi => "/1" }, - "/1;a=b" => { qs => "", pi => "/1;a=b" }, - "/1;a=b?" => { qs => "", pi => "/1;a=b" }, - "/1?a=b;c=d&e=f" => { qs => "a=b;c=d&e=f", pi => "/1" }, - }.each do |uri,expect| - assert_equal req, @parser.headers(req.clear, str % [ uri ]) - req = req.dup - @parser.clear - assert_equal uri, req["REQUEST_URI"], "REQUEST_URI mismatch" - assert_equal "example.com", req["HTTP_HOST"], "Host: mismatch" - assert_equal expect[qs], req[qs], "#{qs} mismatch" - assert_equal expect[pi], req[pi], "#{pi} mismatch" - end - end - - def test_negative_content_length - req = {} - str = "PUT / HTTP/1.1\r\n" \ - "Content-Length: -1\r\n" \ - "\r\n" - assert_raises(HttpParserError) do - @parser.headers(req, str) - end - end - - def test_invalid_content_length - req = {} - str = "PUT / HTTP/1.1\r\n" \ - "Content-Length: zzzzz\r\n" \ - "\r\n" - assert_raises(HttpParserError) do - @parser.headers(req, str) - end - end - - def test_backtrace_is_empty - begin - @parser.headers({}, "AAADFSFDSFD\r\n\r\n") - assert false, "should never get here line:#{__LINE__}" - rescue HttpParserError => e - assert_equal [], e.backtrace - return - end - assert false, "should never get here line:#{__LINE__}" - end - - def test_ignore_version_header - @parser.buf << "GET / HTTP/1.1\r\nVersion: hello\r\n\r\n" - req = @parser.env - assert_equal req, @parser.parse - assert_equal '', @parser.buf - expect = { - "SERVER_NAME" => "localhost", - "rack.url_scheme" => "http", - "REQUEST_PATH" => "/", - "SERVER_PROTOCOL" => "HTTP/1.1", - "PATH_INFO" => "/", - "HTTP_VERSION" => "HTTP/1.1", - "REQUEST_URI" => "/", - "SERVER_PORT" => "80", - "REQUEST_METHOD" => "GET", - "QUERY_STRING" => "" - } - assert_equal expect, req - end - - def test_pipelined_requests - host = "example.com" - expect = { - "HTTP_HOST" => host, - "SERVER_NAME" => host, - "REQUEST_PATH" => "/", - "rack.url_scheme" => "http", - "SERVER_PROTOCOL" => "HTTP/1.1", - "PATH_INFO" => "/", - "HTTP_VERSION" => "HTTP/1.1", - "REQUEST_URI" => "/", - "SERVER_PORT" => "80", - "REQUEST_METHOD" => "GET", - "QUERY_STRING" => "" - } - req1 = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" - req2 = "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n" - @parser.buf << (req1 + req2) - env1 = @parser.parse.dup - assert_equal expect, env1 - assert_equal req2, @parser.buf - assert ! @parser.env.empty? - assert @parser.next? - assert @parser.keepalive? - assert @parser.headers? - assert_equal expect, @parser.env - env2 = @parser.parse.dup - host.replace "www.example.com" - assert_equal "www.example.com", expect["HTTP_HOST"] - assert_equal "www.example.com", expect["SERVER_NAME"] - assert_equal expect, env2 - assert_equal "", @parser.buf - end - - def test_keepalive_requests_disabled - req = "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n".freeze - expect = { - "SERVER_NAME" => "example.com", - "HTTP_HOST" => "example.com", - "rack.url_scheme" => "http", - "REQUEST_PATH" => "/", - "SERVER_PROTOCOL" => "HTTP/1.1", - "PATH_INFO" => "/", - "HTTP_VERSION" => "HTTP/1.1", - "REQUEST_URI" => "/", - "SERVER_PORT" => "80", - "REQUEST_METHOD" => "GET", - "QUERY_STRING" => "" - }.freeze - HttpParser.keepalive_requests = 0 - @parser = HttpParser.new - @parser.buf << req - assert_equal expect, @parser.parse - assert ! @parser.next? - end - - def test_chunk_only - tmp = "" - assert_equal @parser, @parser.dechunk! - assert_nil @parser.filter_body(tmp, "6\r\n") - assert_equal "", tmp - assert_nil @parser.filter_body(tmp, "abcdef") - assert_equal "abcdef", tmp - assert_nil @parser.filter_body(tmp, "\r\n") - assert_equal "", tmp - src = "0\r\n\r\n" - assert_equal src.object_id, @parser.filter_body(tmp, src).object_id - assert_equal "", tmp - end - - def test_chunk_only_bad_align - tmp = "" - assert_equal @parser, @parser.dechunk! - assert_nil @parser.filter_body(tmp, "6\r\na") - assert_equal "a", tmp - assert_nil @parser.filter_body(tmp, "bcde") - assert_equal "bcde", tmp - assert_nil @parser.filter_body(tmp, "f\r") - assert_equal "f", tmp - src = "\n0\r\n\r\n" - assert_equal src.object_id, @parser.filter_body(tmp, src).object_id - assert_equal "", tmp - end - - def test_chunk_only_reset_ok - tmp = "" - assert_equal @parser, @parser.dechunk! - src = "1\r\na\r\n0\r\n\r\n" - assert_nil @parser.filter_body(tmp, src) - assert_equal "a", tmp - assert_equal src.object_id, @parser.filter_body(tmp, src).object_id - - assert_equal @parser, @parser.dechunk! - src = "0\r\n\r\n" - assert_equal src.object_id, @parser.filter_body(tmp, src).object_id - assert_equal "", tmp - assert_equal src, @parser.filter_body(tmp, src) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser_xftrust.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser_xftrust.rb deleted file mode 100644 index db8cfa9..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_http_parser_xftrust.rb +++ /dev/null @@ -1,38 +0,0 @@ -# -*- encoding: binary -*- -require 'test/test_helper' - -include Unicorn - -class HttpParserXFTrustTest < Test::Unit::TestCase - def setup - assert HttpParser.trust_x_forwarded? - end - - def test_xf_trust_false_xfp - HttpParser.trust_x_forwarded = false - parser = HttpParser.new - parser.buf << "GET / HTTP/1.1\r\nHost: foo:\r\n" \ - "X-Forwarded-Proto: https\r\n\r\n" - env = parser.parse - assert_kind_of Hash, env - assert_equal 'foo', env['SERVER_NAME'] - assert_equal '80', env['SERVER_PORT'] - assert_equal 'http', env['rack.url_scheme'] - end - - def test_xf_trust_false_xfs - HttpParser.trust_x_forwarded = false - parser = HttpParser.new - parser.buf << "GET / HTTP/1.1\r\nHost: foo:\r\n" \ - "X-Forwarded-SSL: on\r\n\r\n" - env = parser.parse - assert_kind_of Hash, env - assert_equal 'foo', env['SERVER_NAME'] - assert_equal '80', env['SERVER_PORT'] - assert_equal 'http', env['rack.url_scheme'] - end - - def teardown - HttpParser.trust_x_forwarded = true - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_request.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_request.rb deleted file mode 100644 index fbda1a2..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_request.rb +++ /dev/null @@ -1,182 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2009 Eric Wong -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) - -require 'test/test_helper' - -include Unicorn - -class RequestTest < Test::Unit::TestCase - - class MockRequest < StringIO - alias_method :readpartial, :sysread - alias_method :kgio_read!, :sysread - alias_method :read_nonblock, :sysread - def kgio_addr - '127.0.0.1' - end - end - - def setup - @request = HttpRequest.new - @app = lambda do |env| - [ 200, { 'Content-Length' => '0', 'Content-Type' => 'text/plain' }, [] ] - end - @lint = Rack::Lint.new(@app) - end - - def test_options - client = MockRequest.new("OPTIONS * HTTP/1.1\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal '', env['REQUEST_PATH'] - assert_equal '', env['PATH_INFO'] - assert_equal '*', env['REQUEST_URI'] - res = @lint.call(env) - end - - def test_absolute_uri_with_query - client = MockRequest.new("GET http://e:3/x?y=z HTTP/1.1\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal '/x', env['REQUEST_PATH'] - assert_equal '/x', env['PATH_INFO'] - assert_equal 'y=z', env['QUERY_STRING'] - res = @lint.call(env) - end - - def test_absolute_uri_with_fragment - client = MockRequest.new("GET http://e:3/x#frag HTTP/1.1\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal '/x', env['REQUEST_PATH'] - assert_equal '/x', env['PATH_INFO'] - assert_equal '', env['QUERY_STRING'] - assert_equal 'frag', env['FRAGMENT'] - res = @lint.call(env) - end - - def test_absolute_uri_with_query_and_fragment - client = MockRequest.new("GET http://e:3/x?a=b#frag HTTP/1.1\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal '/x', env['REQUEST_PATH'] - assert_equal '/x', env['PATH_INFO'] - assert_equal 'a=b', env['QUERY_STRING'] - assert_equal 'frag', env['FRAGMENT'] - res = @lint.call(env) - end - - def test_absolute_uri_unsupported_schemes - %w(ssh+http://e/ ftp://e/x http+ssh://e/x).each do |abs_uri| - client = MockRequest.new("GET #{abs_uri} HTTP/1.1\r\n" \ - "Host: foo\r\n\r\n") - assert_raises(HttpParserError) { @request.read(client) } - end - end - - def test_x_forwarded_proto_https - client = MockRequest.new("GET / HTTP/1.1\r\n" \ - "X-Forwarded-Proto: https\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal "https", env['rack.url_scheme'] - res = @lint.call(env) - end - - def test_x_forwarded_proto_http - client = MockRequest.new("GET / HTTP/1.1\r\n" \ - "X-Forwarded-Proto: http\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal "http", env['rack.url_scheme'] - res = @lint.call(env) - end - - def test_x_forwarded_proto_invalid - client = MockRequest.new("GET / HTTP/1.1\r\n" \ - "X-Forwarded-Proto: ftp\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal "http", env['rack.url_scheme'] - res = @lint.call(env) - end - - def test_rack_lint_get - client = MockRequest.new("GET / HTTP/1.1\r\nHost: foo\r\n\r\n") - env = @request.read(client) - assert_equal "http", env['rack.url_scheme'] - assert_equal '127.0.0.1', env['REMOTE_ADDR'] - res = @lint.call(env) - end - - def test_no_content_stringio - client = MockRequest.new("GET / HTTP/1.1\r\nHost: foo\r\n\r\n") - env = @request.read(client) - assert_equal StringIO, env['rack.input'].class - end - - def test_zero_content_stringio - client = MockRequest.new("PUT / HTTP/1.1\r\n" \ - "Content-Length: 0\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal StringIO, env['rack.input'].class - end - - def test_real_content_not_stringio - client = MockRequest.new("PUT / HTTP/1.1\r\n" \ - "Content-Length: 1\r\n" \ - "Host: foo\r\n\r\n") - env = @request.read(client) - assert_equal Unicorn::TeeInput, env['rack.input'].class - end - - def test_rack_lint_put - client = MockRequest.new( - "PUT / HTTP/1.1\r\n" \ - "Host: foo\r\n" \ - "Content-Length: 5\r\n" \ - "\r\n" \ - "abcde") - env = @request.read(client) - assert ! env.include?(:http_body) - res = @lint.call(env) - end - - def test_rack_lint_big_put - count = 100 - bs = 0x10000 - buf = (' ' * bs).freeze - length = bs * count - client = Tempfile.new('big_put') - def client.kgio_addr; '127.0.0.1'; end - def client.kgio_read(*args) - readpartial(*args) - rescue EOFError - end - def client.kgio_read!(*args) - readpartial(*args) - end - client.syswrite( - "PUT / HTTP/1.1\r\n" \ - "Host: foo\r\n" \ - "Content-Length: #{length}\r\n" \ - "\r\n") - count.times { assert_equal bs, client.syswrite(buf) } - assert_equal 0, client.sysseek(0) - env = @request.read(client) - assert ! env.include?(:http_body) - assert_equal length, env['rack.input'].size - count.times { - tmp = env['rack.input'].read(bs) - tmp << env['rack.input'].read(bs - tmp.size) if tmp.size != bs - assert_equal buf, tmp - } - assert_nil env['rack.input'].read(bs) - env['rack.input'].rewind - res = @lint.call(env) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_response.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_response.rb deleted file mode 100644 index 85ac085..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_response.rb +++ /dev/null @@ -1,99 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2005 Zed A. Shaw -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) -# -# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html -# for more information. - -require 'test/test_helper' -require 'time' - -include Unicorn - -class ResponseTest < Test::Unit::TestCase - include Unicorn::HttpResponse - - def test_httpdate - before = Time.now.to_i - 1 - str = httpdate - assert_kind_of(String, str) - middle = Time.parse(str).to_i - after = Time.now.to_i - assert before <= middle - assert middle <= after - end - - def test_response_headers - out = StringIO.new - http_response_write(out, 200, {"X-Whatever" => "stuff"}, ["cool"]) - assert ! out.closed? - - assert out.length > 0, "output didn't have data" - end - - def test_response_string_status - out = StringIO.new - http_response_write(out,'200', {}, []) - assert ! out.closed? - assert out.length > 0, "output didn't have data" - assert_equal 1, out.string.split(/\r\n/).grep(/^Status: 200 OK/).size - end - - def test_response_200 - io = StringIO.new - http_response_write(io, 200, {}, []) - assert ! io.closed? - assert io.length > 0, "output didn't have data" - end - - def test_response_with_default_reason - code = 400 - io = StringIO.new - http_response_write(io, code, {}, []) - assert ! io.closed? - lines = io.string.split(/\r\n/) - assert_match(/.* Bad Request$/, lines.first, - "wrong default reason phrase") - end - - def test_rack_multivalue_headers - out = StringIO.new - http_response_write(out,200, {"X-Whatever" => "stuff\nbleh"}, []) - assert ! out.closed? - assert_match(/^X-Whatever: stuff\r\nX-Whatever: bleh\r\n/, out.string) - end - - # Even though Rack explicitly forbids "Status" in the header hash, - # some broken clients still rely on it - def test_status_header_added - out = StringIO.new - http_response_write(out,200, {"X-Whatever" => "stuff"}, []) - assert ! out.closed? - assert_equal 1, out.string.split(/\r\n/).grep(/^Status: 200 OK/i).size - end - - def test_body_closed - expect_body = %w(1 2 3 4).join("\n") - body = StringIO.new(expect_body) - body.rewind - out = StringIO.new - http_response_write(out,200, {}, body) - assert ! out.closed? - assert body.closed? - assert_match(expect_body, out.string.split(/\r\n/).last) - end - - def test_unknown_status_pass_through - out = StringIO.new - http_response_write(out,"666 I AM THE BEAST", {}, [] ) - assert ! out.closed? - headers = out.string.split(/\r\n\r\n/).first.split(/\r\n/) - assert %r{\AHTTP/\d\.\d 666 I AM THE BEAST\z}.match(headers[0]) - status = headers.grep(/\AStatus:/i).first - assert status - assert_equal "Status: 666 I AM THE BEAST", status - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_server.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_server.rb deleted file mode 100644 index e5b335f..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_server.rb +++ /dev/null @@ -1,268 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2005 Zed A. Shaw -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) -# -# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html -# for more information. - -require 'test/test_helper' - -include Unicorn - -class TestHandler - - def call(env) - while env['rack.input'].read(4096) - end - [200, { 'Content-Type' => 'text/plain' }, ['hello!\n']] - rescue Unicorn::ClientShutdown, Unicorn::HttpParserError => e - $stderr.syswrite("#{e.class}: #{e.message} #{e.backtrace.empty?}\n") - raise e - end -end - - -class WebServerTest < Test::Unit::TestCase - - def setup - @valid_request = "GET / HTTP/1.1\r\nHost: www.zedshaw.com\r\nContent-Type: text/plain\r\n\r\n" - @port = unused_port - @tester = TestHandler.new - redirect_test_io do - @server = HttpServer.new(@tester, :listeners => [ "127.0.0.1:#{@port}" ] ) - @server.start - end - end - - def teardown - redirect_test_io do - wait_workers_ready("test_stderr.#$$.log", 1) - File.truncate("test_stderr.#$$.log", 0) - @server.stop(false) - end - reset_sig_handlers - end - - def test_preload_app_config - teardown - tmp = Tempfile.new('test_preload_app_config') - ObjectSpace.undefine_finalizer(tmp) - app = lambda { || - tmp.sysseek(0) - tmp.truncate(0) - tmp.syswrite($$) - lambda { |env| [ 200, { 'Content-Type' => 'text/plain' }, [ "#$$\n" ] ] } - } - redirect_test_io do - @server = HttpServer.new(app, :listeners => [ "127.0.0.1:#@port"] ) - @server.start - end - results = hit(["http://localhost:#@port/"]) - worker_pid = results[0].to_i - assert worker_pid != 0 - tmp.sysseek(0) - loader_pid = tmp.sysread(4096).to_i - assert loader_pid != 0 - assert_equal worker_pid, loader_pid - teardown - - redirect_test_io do - @server = HttpServer.new(app, :listeners => [ "127.0.0.1:#@port"], - :preload_app => true) - @server.start - end - results = hit(["http://localhost:#@port/"]) - worker_pid = results[0].to_i - assert worker_pid != 0 - tmp.sysseek(0) - loader_pid = tmp.sysread(4096).to_i - assert_equal $$, loader_pid - assert worker_pid != loader_pid - ensure - tmp.close! - end - - def test_broken_app - teardown - app = lambda { |env| raise RuntimeError, "hello" } - # [200, {}, []] } - redirect_test_io do - @server = HttpServer.new(app, :listeners => [ "127.0.0.1:#@port"] ) - @server.start - end - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - assert_match %r{\AHTTP/1.[01] 500\b}, sock.sysread(4096) - assert_nil sock.close - end - - def test_simple_server - results = hit(["http://localhost:#{@port}/test"]) - assert_equal 'hello!\n', results[0], "Handler didn't really run" - end - - def test_client_shutdown_writes - bs = 15609315 * rand - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("PUT /hello HTTP/1.1\r\n") - sock.syswrite("Host: example.com\r\n") - sock.syswrite("Transfer-Encoding: chunked\r\n") - sock.syswrite("Trailer: X-Foo\r\n") - sock.syswrite("\r\n") - sock.syswrite("%x\r\n" % [ bs ]) - sock.syswrite("F" * bs) - sock.syswrite("\r\n0\r\nX-") - "Foo: bar\r\n\r\n".each_byte do |x| - sock.syswrite x.chr - sleep 0.05 - end - # we wrote the entire request before shutting down, server should - # continue to process our request and never hit EOFError on our sock - sock.shutdown(Socket::SHUT_WR) - buf = sock.read - assert_equal 'hello!\n', buf.split(/\r\n\r\n/).last - next_client = Net::HTTP.get(URI.parse("http://127.0.0.1:#@port/")) - assert_equal 'hello!\n', next_client - lines = File.readlines("test_stderr.#$$.log") - assert lines.grep(/^Unicorn::ClientShutdown: /).empty? - assert_nil sock.close - end - - def test_client_shutdown_write_truncates - bs = 15609315 * rand - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("PUT /hello HTTP/1.1\r\n") - sock.syswrite("Host: example.com\r\n") - sock.syswrite("Transfer-Encoding: chunked\r\n") - sock.syswrite("Trailer: X-Foo\r\n") - sock.syswrite("\r\n") - sock.syswrite("%x\r\n" % [ bs ]) - sock.syswrite("F" * (bs / 2.0)) - - # shutdown prematurely, this will force the server to abort - # processing on us even during app dispatch - sock.shutdown(Socket::SHUT_WR) - IO.select([sock], nil, nil, 60) or raise "Timed out" - buf = sock.read - assert_equal "", buf - next_client = Net::HTTP.get(URI.parse("http://127.0.0.1:#@port/")) - assert_equal 'hello!\n', next_client - lines = File.readlines("test_stderr.#$$.log") - lines = lines.grep(/^Unicorn::ClientShutdown: bytes_read=\d+/) - assert_equal 1, lines.size - assert_match %r{\AUnicorn::ClientShutdown: bytes_read=\d+ true$}, lines[0] - assert_nil sock.close - end - - def test_client_malformed_body - bs = 15653984 - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("PUT /hello HTTP/1.1\r\n") - sock.syswrite("Host: example.com\r\n") - sock.syswrite("Transfer-Encoding: chunked\r\n") - sock.syswrite("Trailer: X-Foo\r\n") - sock.syswrite("\r\n") - sock.syswrite("%x\r\n" % [ bs ]) - sock.syswrite("F" * bs) - begin - File.open("/dev/urandom", "rb") { |fp| sock.syswrite(fp.sysread(16384)) } - rescue - end - assert_nil sock.close - next_client = Net::HTTP.get(URI.parse("http://127.0.0.1:#@port/")) - assert_equal 'hello!\n', next_client - lines = File.readlines("test_stderr.#$$.log") - lines = lines.grep(/^Unicorn::HttpParserError: .* true$/) - assert_equal 1, lines.size - end - - def do_test(string, chunk, close_after=nil, shutdown_delay=0) - # Do not use instance variables here, because it needs to be thread safe - socket = TCPSocket.new("127.0.0.1", @port); - request = StringIO.new(string) - chunks_out = 0 - - while data = request.read(chunk) - chunks_out += socket.write(data) - socket.flush - sleep 0.2 - if close_after and chunks_out > close_after - socket.close - sleep 1 - end - end - sleep(shutdown_delay) - socket.write(" ") # Some platforms only raise the exception on attempted write - socket.flush - end - - def test_trickle_attack - do_test(@valid_request, 3) - end - - def test_close_client - assert_raises IOError do - do_test(@valid_request, 10, 20) - end - end - - def test_bad_client - redirect_test_io do - do_test("GET /test HTTP/BAD", 3) - end - end - - def test_logger_set - assert_equal @server.logger, Unicorn::HttpRequest::DEFAULTS["rack.logger"] - end - - def test_logger_changed - tmp = Logger.new($stdout) - @server.logger = tmp - assert_equal tmp, Unicorn::HttpRequest::DEFAULTS["rack.logger"] - end - - def test_bad_client_400 - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET / HTTP/1.0\r\nHost: foo\rbar\r\n\r\n") - assert_match %r{\AHTTP/1.[01] 400\b}, sock.sysread(4096) - assert_nil sock.close - end - - def test_http_0_9 - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET /hello\r\n") - assert_match 'hello!\n', sock.sysread(4096) - assert_nil sock.close - end - - def test_header_is_too_long - redirect_test_io do - long = "GET /test HTTP/1.1\r\n" + ("X-Big: stuff\r\n" * 15000) + "\r\n" - assert_raises Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, Errno::EINVAL, IOError do - do_test(long, long.length/2, 10) - end - end - end - - def test_file_streamed_request - body = "a" * (Unicorn::Const::MAX_BODY * 2) - long = "PUT /test HTTP/1.1\r\nContent-length: #{body.length}\r\n\r\n" + body - do_test(long, Unicorn::Const::CHUNK_SIZE * 2 - 400) - end - - def test_file_streamed_request_bad_body - body = "a" * (Unicorn::Const::MAX_BODY * 2) - long = "GET /test HTTP/1.1\r\nContent-ength: #{body.length}\r\n\r\n" + body - assert_raises(EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL, - Errno::EBADF) { - do_test(long, Unicorn::Const::CHUNK_SIZE * 2 - 400) - } - end - - def test_listener_names - assert_equal [ "127.0.0.1:#@port" ], Unicorn.listener_names - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_signals.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_signals.rb deleted file mode 100644 index 443c736..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_signals.rb +++ /dev/null @@ -1,188 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2009 Eric Wong -# You can redistribute it and/or modify it under the same terms as Ruby 1.8 or -# the GPLv2+ (GPLv3+ preferred) -# -# Ensure we stay sane in the face of signals being sent to us - -require 'test/test_helper' - -include Unicorn - -class Dd - def initialize(bs, count) - @count = count - @buf = ' ' * bs - end - - def each(&block) - @count.times { yield @buf } - end -end - -class SignalsTest < Test::Unit::TestCase - - def setup - @bs = 1 * 1024 * 1024 - @count = 100 - @port = unused_port - @sock = Tempfile.new('unicorn.sock') - @tmp = Tempfile.new('unicorn.write') - @tmp.sync = true - File.unlink(@sock.path) - File.unlink(@tmp.path) - @server_opts = { - :listeners => [ "127.0.0.1:#@port", @sock.path ], - :after_fork => lambda { |server,worker| - trap(:HUP) { @tmp.syswrite('.') } - }, - } - @server = nil - end - - def teardown - reset_sig_handlers - end - - def test_worker_dies_on_dead_master - pid = fork { - app = lambda { |env| [ 200, {'X-Pid' => "#$$" }, [] ] } - opts = @server_opts.merge(:timeout => 3) - redirect_test_io { HttpServer.new(app, opts).start.join } - } - wait_workers_ready("test_stderr.#{pid}.log", 1) - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - buf = sock.readpartial(4096) - assert_nil sock.close - buf =~ /\bX-Pid: (\d+)\b/ or raise Exception - child = $1.to_i - wait_master_ready("test_stderr.#{pid}.log") - wait_workers_ready("test_stderr.#{pid}.log", 1) - Process.kill(:KILL, pid) - Process.waitpid(pid) - File.unlink("test_stderr.#{pid}.log", "test_stdout.#{pid}.log") - t0 = Time.now - assert child - assert t0 - assert_raises(Errno::ESRCH) { loop { Process.kill(0, child); sleep 0.2 } } - assert((Time.now - t0) < 60) - end - - def test_sleepy_kill - rd, wr = IO.pipe - pid = fork { - rd.close - app = lambda { |env| wr.syswrite('.'); sleep; [ 200, {}, [] ] } - redirect_test_io { HttpServer.new(app, @server_opts).start.join } - } - wr.close - wait_workers_ready("test_stderr.#{pid}.log", 1) - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - buf = rd.readpartial(1) - wait_master_ready("test_stderr.#{pid}.log") - Process.kill(:INT, pid) - Process.waitpid(pid) - assert_equal '.', buf - buf = nil - assert_raises(EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL, - Errno::EBADF) do - buf = sock.sysread(4096) - end - assert_nil buf - end - - def test_timeout_slow_response - pid = fork { - app = lambda { |env| sleep } - opts = @server_opts.merge(:timeout => 3) - redirect_test_io { HttpServer.new(app, opts).start.join } - } - t0 = Time.now - wait_workers_ready("test_stderr.#{pid}.log", 1) - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - - buf = nil - assert_raises(EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL, - Errno::EBADF) do - buf = sock.sysread(4096) - end - diff = Time.now - t0 - assert_nil buf - assert diff > 1.0, "diff was #{diff.inspect}" - assert diff < 60.0 - ensure - Process.kill(:TERM, pid) rescue nil - end - - def test_response_write - app = lambda { |env| - [ 200, { 'Content-Type' => 'text/plain', 'X-Pid' => Process.pid.to_s }, - Dd.new(@bs, @count) ] - } - redirect_test_io { @server = HttpServer.new(app, @server_opts).start } - wait_workers_ready("test_stderr.#{$$}.log", 1) - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - buf = '' - header_len = pid = nil - buf = sock.sysread(16384, buf) - pid = buf[/\r\nX-Pid: (\d+)\r\n/, 1].to_i - header_len = buf[/\A(.+?\r\n\r\n)/m, 1].size - assert pid > 0, "pid not positive: #{pid.inspect}" - read = buf.size - size_before = @tmp.stat.size - assert_raises(EOFError,Errno::ECONNRESET,Errno::EPIPE,Errno::EINVAL, - Errno::EBADF) do - loop do - 3.times { Process.kill(:HUP, pid) } - sock.sysread(16384, buf) - read += buf.size - 3.times { Process.kill(:HUP, pid) } - end - end - - redirect_test_io { @server.stop(true) } - # can't check for == since pending signals get merged - assert size_before < @tmp.stat.size - got = read - header_len - expect = @bs * @count - assert_equal(expect, got, "expect=#{expect} got=#{got}") - assert_nil sock.close - end - - def test_request_read - app = lambda { |env| - while env['rack.input'].read(4096) - end - [ 200, {'Content-Type'=>'text/plain', 'X-Pid'=>Process.pid.to_s}, [] ] - } - redirect_test_io { @server = HttpServer.new(app, @server_opts).start } - - wait_workers_ready("test_stderr.#{$$}.log", 1) - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("GET / HTTP/1.0\r\n\r\n") - pid = sock.sysread(4096)[/\r\nX-Pid: (\d+)\r\n/, 1].to_i - assert_nil sock.close - - assert pid > 0, "pid not positive: #{pid.inspect}" - sock = TCPSocket.new('127.0.0.1', @port) - sock.syswrite("PUT / HTTP/1.0\r\n") - sock.syswrite("Content-Length: #{@bs * @count}\r\n\r\n") - 1000.times { Process.kill(:HUP, pid) } - size_before = @tmp.stat.size - killer = fork { loop { Process.kill(:HUP, pid); sleep(0.01) } } - buf = ' ' * @bs - @count.times { sock.syswrite(buf) } - Process.kill(:KILL, killer) - Process.waitpid2(killer) - redirect_test_io { @server.stop(true) } - # can't check for == since pending signals get merged - assert size_before < @tmp.stat.size - assert_equal pid, sock.sysread(4096)[/\r\nX-Pid: (\d+)\r\n/, 1].to_i - assert_nil sock.close - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_sni_hostnames.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_sni_hostnames.rb deleted file mode 100644 index 457afee..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_sni_hostnames.rb +++ /dev/null @@ -1,47 +0,0 @@ -# -*- encoding: binary -*- -require "test/unit" -require "unicorn" - -# this tests an implementation detail, it may change so this test -# can be removed later. -class TestSniHostnames < Test::Unit::TestCase - include Unicorn::SSLServer - - def setup - GC.start - end - - def teardown - GC.start - end - - def test_host_name_detect_one - app = Rack::Builder.new do - map "http://sni1.example.com/" do - use Rack::ContentLength - use Rack::ContentType, "text/plain" - run lambda { |env| [ 200, {}, [] ] } - end - end.to_app - hostnames = rack_sni_hostnames(app) - assert hostnames.include?("sni1.example.com") - end - - def test_host_name_detect_multiple - app = Rack::Builder.new do - map "http://sni2.example.com/" do - use Rack::ContentLength - use Rack::ContentType, "text/plain" - run lambda { |env| [ 200, {}, [] ] } - end - map "http://sni3.example.com/" do - use Rack::ContentLength - use Rack::ContentType, "text/plain" - run lambda { |env| [ 200, {}, [] ] } - end - end.to_app - hostnames = rack_sni_hostnames(app) - assert hostnames.include?("sni2.example.com") - assert hostnames.include?("sni3.example.com") - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_socket_helper.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_socket_helper.rb deleted file mode 100644 index 8992757..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_socket_helper.rb +++ /dev/null @@ -1,197 +0,0 @@ -# -*- encoding: binary -*- - -require 'test/test_helper' -require 'tempfile' - -class TestSocketHelper < Test::Unit::TestCase - include Unicorn::SocketHelper - attr_reader :logger - GET_SLASH = "GET / HTTP/1.0\r\n\r\n".freeze - - def setup - @log_tmp = Tempfile.new 'logger' - @logger = Logger.new(@log_tmp.path) - @test_addr = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - @test6_addr = ENV['UNICORN_TEST6_ADDR'] || '::1' - GC.disable - end - - def teardown - GC.enable - end - - def test_bind_listen_tcp - port = unused_port @test_addr - @tcp_listener_name = "#@test_addr:#{port}" - @tcp_listener = bind_listen(@tcp_listener_name) - assert TCPServer === @tcp_listener - assert_equal @tcp_listener_name, sock_name(@tcp_listener) - end - - def test_bind_listen_options - port = unused_port @test_addr - tcp_listener_name = "#@test_addr:#{port}" - tmp = Tempfile.new 'unix.sock' - unix_listener_name = tmp.path - File.unlink(tmp.path) - [ { :backlog => 5 }, { :sndbuf => 4096 }, { :rcvbuf => 4096 }, - { :backlog => 16, :rcvbuf => 4096, :sndbuf => 4096 } - ].each do |opts| - tcp_listener = bind_listen(tcp_listener_name, opts) - assert TCPServer === tcp_listener - tcp_listener.close - unix_listener = bind_listen(unix_listener_name, opts) - assert UNIXServer === unix_listener - unix_listener.close - end - end - - def test_bind_listen_unix - old_umask = File.umask(0777) - tmp = Tempfile.new 'unix.sock' - @unix_listener_path = tmp.path - File.unlink(@unix_listener_path) - @unix_listener = bind_listen(@unix_listener_path) - assert UNIXServer === @unix_listener - assert_equal @unix_listener_path, sock_name(@unix_listener) - assert File.readable?(@unix_listener_path), "not readable" - assert File.writable?(@unix_listener_path), "not writable" - assert_equal 0777, File.umask - ensure - File.umask(old_umask) - end - - def test_bind_listen_unix_umask - old_umask = File.umask(0777) - tmp = Tempfile.new 'unix.sock' - @unix_listener_path = tmp.path - File.unlink(@unix_listener_path) - @unix_listener = bind_listen(@unix_listener_path, :umask => 077) - assert UNIXServer === @unix_listener - assert_equal @unix_listener_path, sock_name(@unix_listener) - assert_equal 0140700, File.stat(@unix_listener_path).mode - assert_equal 0777, File.umask - ensure - File.umask(old_umask) - end - - def test_bind_listen_unix_idempotent - test_bind_listen_unix - a = bind_listen(@unix_listener) - assert_equal a.fileno, @unix_listener.fileno - unix_server = server_cast(@unix_listener) - assert UNIXServer === unix_server - a = bind_listen(unix_server) - assert_equal a.fileno, unix_server.fileno - assert_equal a.fileno, @unix_listener.fileno - end - - def test_bind_listen_tcp_idempotent - test_bind_listen_tcp - a = bind_listen(@tcp_listener) - assert_equal a.fileno, @tcp_listener.fileno - tcp_server = server_cast(@tcp_listener) - assert TCPServer === tcp_server - a = bind_listen(tcp_server) - assert_equal a.fileno, tcp_server.fileno - assert_equal a.fileno, @tcp_listener.fileno - end - - def test_bind_listen_unix_rebind - test_bind_listen_unix - new_listener = nil - assert_raises(Errno::EADDRINUSE) do - new_listener = bind_listen(@unix_listener_path) - end - - File.unlink(@unix_listener_path) - new_listener = bind_listen(@unix_listener_path) - - assert UNIXServer === new_listener - assert new_listener.fileno != @unix_listener.fileno - assert_equal sock_name(new_listener), sock_name(@unix_listener) - assert_equal @unix_listener_path, sock_name(new_listener) - pid = fork do - client = server_cast(new_listener).accept - client.syswrite('abcde') - exit 0 - end - s = UNIXSocket.new(@unix_listener_path) - IO.select([s]) - assert_equal 'abcde', s.sysread(5) - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_server_cast - test_bind_listen_unix - test_bind_listen_tcp - unix_listener_socket = Socket.for_fd(@unix_listener.fileno) - assert Socket === unix_listener_socket - @unix_server = server_cast(unix_listener_socket) - assert_equal @unix_listener.fileno, @unix_server.fileno - assert UNIXServer === @unix_server - assert_equal(@unix_server.path, @unix_listener.path, - "##{@unix_server.path} != #{@unix_listener.path}") - assert File.socket?(@unix_server.path) - assert_equal @unix_listener_path, sock_name(@unix_server) - - tcp_listener_socket = Socket.for_fd(@tcp_listener.fileno) - assert Socket === tcp_listener_socket - @tcp_server = server_cast(tcp_listener_socket) - assert_equal @tcp_listener.fileno, @tcp_server.fileno - assert TCPServer === @tcp_server - assert_equal @tcp_listener_name, sock_name(@tcp_server) - end - - def test_sock_name - test_server_cast - sock_name(@unix_server) - end - - def test_tcp_defer_accept_default - port = unused_port @test_addr - name = "#@test_addr:#{port}" - sock = bind_listen(name) - cur = sock.getsockopt(Socket::SOL_TCP, TCP_DEFER_ACCEPT).unpack('i')[0] - assert cur >= 1 - end if defined?(TCP_DEFER_ACCEPT) - - def test_tcp_defer_accept_disable - port = unused_port @test_addr - name = "#@test_addr:#{port}" - sock = bind_listen(name, :tcp_defer_accept => false) - cur = sock.getsockopt(Socket::SOL_TCP, TCP_DEFER_ACCEPT).unpack('i')[0] - assert_equal 0, cur - end if defined?(TCP_DEFER_ACCEPT) - - def test_tcp_defer_accept_nr - port = unused_port @test_addr - name = "#@test_addr:#{port}" - sock = bind_listen(name, :tcp_defer_accept => 60) - cur = sock.getsockopt(Socket::SOL_TCP, TCP_DEFER_ACCEPT).unpack('i')[0] - assert cur > 1 - end if defined?(TCP_DEFER_ACCEPT) - - def test_ipv6only - port = begin - unused_port "#@test6_addr" - rescue Errno::EINVAL - return - end - sock = bind_listen "[#@test6_addr]:#{port}", :ipv6only => true - cur = sock.getsockopt(:IPPROTO_IPV6, :IPV6_V6ONLY).unpack('i')[0] - assert_equal 1, cur - rescue Errno::EAFNOSUPPORT - end if RUBY_VERSION >= "1.9.2" - - def test_reuseport - port = unused_port @test_addr - name = "#@test_addr:#{port}" - sock = bind_listen(name, :reuseport => true) - cur = sock.getsockopt(Socket::SOL_SOCKET, SO_REUSEPORT).unpack('i')[0] - assert_operator cur, :>, 0 - rescue Errno::ENOPROTOOPT - # kernel does not support SO_REUSEPORT (older Linux) - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_stream_input.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_stream_input.rb deleted file mode 100644 index 1a07ec3..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_stream_input.rb +++ /dev/null @@ -1,203 +0,0 @@ -# -*- encoding: binary -*- - -require 'test/unit' -require 'digest/sha1' -require 'unicorn' - -class TestStreamInput < Test::Unit::TestCase - def setup - @rs = $/ - @env = {} - @rd, @wr = Kgio::UNIXSocket.pair - @rd.sync = @wr.sync = true - @start_pid = $$ - end - - def teardown - return if $$ != @start_pid - $/ = @rs - @rd.close rescue nil - @wr.close rescue nil - Process.waitall - end - - def test_read_negative - r = init_request('hello') - si = Unicorn::StreamInput.new(@rd, r) - assert_raises(ArgumentError) { si.read(-1) } - assert_equal 'hello', si.read - end - - def test_read_small - r = init_request('hello') - si = Unicorn::StreamInput.new(@rd, r) - assert_equal 'hello', si.read - assert_equal '', si.read - assert_nil si.read(5) - assert_nil si.gets - end - - def test_gets_oneliner - r = init_request('hello') - si = Unicorn::StreamInput.new(@rd, r) - assert_equal 'hello', si.gets - assert_nil si.gets - end - - def test_gets_multiline - r = init_request("a\nb\n\n") - si = Unicorn::StreamInput.new(@rd, r) - assert_equal "a\n", si.gets - assert_equal "b\n", si.gets - assert_equal "\n", si.gets - assert_nil si.gets - end - - def test_gets_empty_rs - $/ = nil - r = init_request("a\nb\n\n") - si = Unicorn::StreamInput.new(@rd, r) - assert_equal "a\nb\n\n", si.gets - assert_nil si.gets - end - - def test_read_with_equal_len - r = init_request("abcde") - si = Unicorn::StreamInput.new(@rd, r) - assert_equal "abcde", si.read(5) - assert_nil si.read(5) - end - - def test_big_body_multi - r = init_request('.', Unicorn::Const::MAX_BODY + 1) - si = Unicorn::StreamInput.new(@rd, r) - assert_equal Unicorn::Const::MAX_BODY, @parser.content_length - assert ! @parser.body_eof? - nr = Unicorn::Const::MAX_BODY / 4 - pid = fork { - @rd.close - nr.times { @wr.write('....') } - @wr.close - } - @wr.close - assert_equal '.', si.read(1) - nr.times { |x| - assert_equal '....', si.read(4), "nr=#{x}" - } - assert_nil si.read(1) - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_gets_long - r = init_request("hello", 5 + (4096 * 4 * 3) + "#$/foo#$/".size) - si = Unicorn::StreamInput.new(@rd, r) - status = line = nil - pid = fork { - @rd.close - 3.times { @wr.write("ffff" * 4096) } - @wr.write "#$/foo#$/" - @wr.close - } - @wr.close - line = si.gets - assert_equal(4096 * 4 * 3 + 5 + $/.size, line.size) - assert_equal("hello" << ("ffff" * 4096 * 3) << "#$/", line) - line = si.gets - assert_equal "foo#$/", line - assert_nil si.gets - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_read_with_buffer - r = init_request('hello') - si = Unicorn::StreamInput.new(@rd, r) - buf = '' - rv = si.read(4, buf) - assert_equal 'hell', rv - assert_equal 'hell', buf - assert_equal rv.object_id, buf.object_id - assert_equal 'o', si.read - assert_equal nil, si.read(5, buf) - end - - def test_read_with_buffer_clobbers - r = init_request('hello') - si = Unicorn::StreamInput.new(@rd, r) - buf = 'foo' - assert_equal 'hello', si.read(nil, buf) - assert_equal 'hello', buf - assert_equal '', si.read(nil, buf) - assert_equal '', buf - buf = 'asdf' - assert_nil si.read(5, buf) - assert_equal '', buf - end - - def test_read_zero - r = init_request('hello') - si = Unicorn::StreamInput.new(@rd, r) - assert_equal '', si.read(0) - buf = 'asdf' - rv = si.read(0, buf) - assert_equal rv.object_id, buf.object_id - assert_equal '', buf - assert_equal 'hello', si.read - assert_nil si.read(5) - assert_equal '', si.read(0) - buf = 'hello' - rv = si.read(0, buf) - assert_equal rv.object_id, buf.object_id - assert_equal '', rv - end - - def test_gets_read_mix - r = init_request("hello\nasdfasdf") - si = Unicorn::StreamInput.new(@rd, r) - assert_equal "hello\n", si.gets - assert_equal "asdfasdf", si.read(9) - assert_nil si.read(9) - end - - def test_gets_read_mix_chunked - r = @parser = Unicorn::HttpParser.new - body = "6\r\nhello" - @buf = "POST / HTTP/1.1\r\n" \ - "Host: localhost\r\n" \ - "Transfer-Encoding: chunked\r\n" \ - "\r\n#{body}" - assert_equal @env, @parser.headers(@env, @buf) - assert_equal body, @buf - si = Unicorn::StreamInput.new(@rd, r) - @wr.syswrite "\n\r\n" - assert_equal "hello\n", si.gets - @wr.syswrite "8\r\nasdfasdf\r\n" - assert_equal"asdfasdf", si.read(9) + si.read(9) - @wr.syswrite "0\r\n\r\n" - assert_nil si.read(9) - end - - def test_gets_read_mix_big - r = init_request("hello\n#{'.' * 65536}") - si = Unicorn::StreamInput.new(@rd, r) - assert_equal "hello\n", si.gets - assert_equal '.' * 16384, si.read(16384) - assert_equal '.' * 16383, si.read(16383) - assert_equal '.' * 16384, si.read(16384) - assert_equal '.' * 16385, si.read(16385) - assert_nil si.gets - end - - def init_request(body, size = nil) - @parser = Unicorn::HttpParser.new - body = body.to_s.freeze - @buf = "POST / HTTP/1.1\r\n" \ - "Host: localhost\r\n" \ - "Content-Length: #{size || body.size}\r\n" \ - "\r\n#{body}" - assert_equal @env, @parser.headers(@env, @buf) - assert_equal body, @buf - @parser - end -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_tee_input.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_tee_input.rb deleted file mode 100644 index 0c2c941..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_tee_input.rb +++ /dev/null @@ -1,294 +0,0 @@ -# -*- encoding: binary -*- - -require 'test/unit' -require 'digest/sha1' -require 'unicorn' - -class TeeInput < Unicorn::TeeInput - attr_accessor :tmp, :len -end - -class TestTeeInput < Test::Unit::TestCase - - def setup - @rs = $/ - @rd, @wr = Kgio::UNIXSocket.pair - @rd.sync = @wr.sync = true - @start_pid = $$ - end - - def teardown - return if $$ != @start_pid - $/ = @rs - @rd.close rescue nil - @wr.close rescue nil - begin - Process.wait - rescue Errno::ECHILD - break - end while true - end - - def test_gets_long - r = init_request("hello", 5 + (4096 * 4 * 3) + "#$/foo#$/".size) - ti = TeeInput.new(@rd, r) - status = line = nil - pid = fork { - @rd.close - 3.times { @wr.write("ffff" * 4096) } - @wr.write "#$/foo#$/" - @wr.close - } - @wr.close - line = ti.gets - assert_equal(4096 * 4 * 3 + 5 + $/.size, line.size) - assert_equal("hello" << ("ffff" * 4096 * 3) << "#$/", line) - line = ti.gets - assert_equal "foo#$/", line - assert_nil ti.gets - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_gets_short - r = init_request("hello", 5 + "#$/foo".size) - ti = TeeInput.new(@rd, r) - status = line = nil - pid = fork { - @rd.close - @wr.write "#$/foo" - @wr.close - } - @wr.close - line = ti.gets - assert_equal("hello#$/", line) - line = ti.gets - assert_equal "foo", line - assert_nil ti.gets - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_small_body - r = init_request('hello') - ti = TeeInput.new(@rd, r) - assert_equal 0, @parser.content_length - assert @parser.body_eof? - assert_equal StringIO, ti.tmp.class - assert_equal 0, ti.tmp.pos - assert_equal 5, ti.size - assert_equal 'hello', ti.read - assert_equal '', ti.read - assert_nil ti.read(4096) - assert_equal 5, ti.size - end - - def test_read_with_buffer - r = init_request('hello') - ti = TeeInput.new(@rd, r) - buf = '' - rv = ti.read(4, buf) - assert_equal 'hell', rv - assert_equal 'hell', buf - assert_equal rv.object_id, buf.object_id - assert_equal 'o', ti.read - assert_equal nil, ti.read(5, buf) - assert_equal 0, ti.rewind - assert_equal 'hello', ti.read(5, buf) - assert_equal 'hello', buf - end - - def test_big_body - r = init_request('.' * Unicorn::Const::MAX_BODY << 'a') - ti = TeeInput.new(@rd, r) - assert_equal 0, @parser.content_length - assert @parser.body_eof? - assert_kind_of File, ti.tmp - assert_equal 0, ti.tmp.pos - assert_equal Unicorn::Const::MAX_BODY + 1, ti.size - end - - def test_read_in_full_if_content_length - a, b = 300, 3 - r = init_request('.' * b, 300) - assert_equal 300, @parser.content_length - ti = TeeInput.new(@rd, r) - pid = fork { - @wr.write('.' * 197) - sleep 1 # still a *potential* race here that would make the test moot... - @wr.write('.' * 100) - } - assert_equal a, ti.read(a).size - _, status = Process.waitpid2(pid) - assert status.success? - @wr.close - end - - def test_big_body_multi - r = init_request('.', Unicorn::Const::MAX_BODY + 1) - ti = TeeInput.new(@rd, r) - assert_equal Unicorn::Const::MAX_BODY, @parser.content_length - assert ! @parser.body_eof? - assert_kind_of File, ti.tmp - assert_equal 0, ti.tmp.pos - assert_equal Unicorn::Const::MAX_BODY + 1, ti.size - nr = Unicorn::Const::MAX_BODY / 4 - pid = fork { - @rd.close - nr.times { @wr.write('....') } - @wr.close - } - @wr.close - assert_equal '.', ti.read(1) - assert_equal Unicorn::Const::MAX_BODY + 1, ti.size - nr.times { |x| - assert_equal '....', ti.read(4), "nr=#{x}" - assert_equal Unicorn::Const::MAX_BODY + 1, ti.size - } - assert_nil ti.read(1) - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_chunked - @parser = Unicorn::HttpParser.new - @parser.buf << "POST / HTTP/1.1\r\n" \ - "Host: localhost\r\n" \ - "Transfer-Encoding: chunked\r\n" \ - "\r\n" - assert @parser.parse - assert_equal "", @parser.buf - - pid = fork { - @rd.close - 5.times { @wr.write("5\r\nabcde\r\n") } - @wr.write("0\r\n\r\n") - } - @wr.close - ti = TeeInput.new(@rd, @parser) - assert_nil @parser.content_length - assert_nil ti.len - assert ! @parser.body_eof? - assert_equal 25, ti.size - assert @parser.body_eof? - assert_equal 25, ti.len - assert_equal 0, ti.tmp.pos - ti.rewind - assert_equal 0, ti.tmp.pos - assert_equal 'abcdeabcdeabcdeabcde', ti.read(20) - assert_equal 20, ti.tmp.pos - ti.rewind - assert_equal 0, ti.tmp.pos - assert_kind_of File, ti.tmp - status = nil - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_chunked_ping_pong - @parser = Unicorn::HttpParser.new - buf = @parser.buf - buf << "POST / HTTP/1.1\r\n" \ - "Host: localhost\r\n" \ - "Transfer-Encoding: chunked\r\n" \ - "\r\n" - assert @parser.parse - assert_equal "", buf - chunks = %w(aa bbb cccc dddd eeee) - rd, wr = IO.pipe - - pid = fork { - chunks.each do |chunk| - rd.read(1) == "." and - @wr.write("#{'%x' % [ chunk.size]}\r\n#{chunk}\r\n") - end - @wr.write("0\r\n\r\n") - } - ti = TeeInput.new(@rd, @parser) - assert_nil @parser.content_length - assert_nil ti.len - assert ! @parser.body_eof? - chunks.each do |chunk| - wr.write('.') - assert_equal chunk, ti.read(16384) - end - _, status = Process.waitpid2(pid) - assert status.success? - end - - def test_chunked_with_trailer - @parser = Unicorn::HttpParser.new - buf = @parser.buf - buf << "POST / HTTP/1.1\r\n" \ - "Host: localhost\r\n" \ - "Trailer: Hello\r\n" \ - "Transfer-Encoding: chunked\r\n" \ - "\r\n" - assert @parser.parse - assert_equal "", buf - - pid = fork { - @rd.close - 5.times { @wr.write("5\r\nabcde\r\n") } - @wr.write("0\r\n") - @wr.write("Hello: World\r\n\r\n") - } - @wr.close - ti = TeeInput.new(@rd, @parser) - assert_nil @parser.content_length - assert_nil ti.len - assert ! @parser.body_eof? - assert_equal 25, ti.size - assert_equal "World", @parser.env['HTTP_HELLO'] - pid, status = Process.waitpid2(pid) - assert status.success? - end - - def test_chunked_and_size_slow - @parser = Unicorn::HttpParser.new - buf = @parser.buf - buf << "POST / HTTP/1.1\r\n" \ - "Host: localhost\r\n" \ - "Trailer: Hello\r\n" \ - "Transfer-Encoding: chunked\r\n" \ - "\r\n" - assert @parser.parse - assert_equal "", buf - - @wr.write("9\r\nabcde") - ti = TeeInput.new(@rd, @parser) - assert_nil @parser.content_length - assert_equal "abcde", ti.read(9) - assert ! @parser.body_eof? - @wr.write("fghi\r\n0\r\nHello: World\r\n\r\n") - assert_equal 9, ti.size - assert_equal "fghi", ti.read(9) - assert_equal nil, ti.read(9) - assert_equal "World", @parser.env['HTTP_HELLO'] - end - - def test_gets_read_mix - r = init_request("hello\nasdfasdf") - ti = Unicorn::TeeInput.new(@rd, r) - assert_equal "hello\n", ti.gets - assert_equal "asdfasdf", ti.read(9) - assert_nil ti.read(9) - end - -private - - def init_request(body, size = nil) - @parser = Unicorn::HttpParser.new - body = body.to_s.freeze - buf = @parser.buf - buf << "POST / HTTP/1.1\r\n" \ - "Host: localhost\r\n" \ - "Content-Length: #{size || body.size}\r\n" \ - "\r\n#{body}" - assert @parser.parse - assert_equal body, buf - @buf = buf - @parser - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_upload.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_upload.rb deleted file mode 100644 index bcce4bc..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_upload.rb +++ /dev/null @@ -1,306 +0,0 @@ -# -*- encoding: binary -*- - -# Copyright (c) 2009 Eric Wong -require 'test/test_helper' -require 'digest/md5' - -include Unicorn - -class UploadTest < Test::Unit::TestCase - - def setup - @addr = ENV['UNICORN_TEST_ADDR'] || '127.0.0.1' - @port = unused_port - @hdr = {'Content-Type' => 'text/plain', 'Content-Length' => '0'} - @bs = 4096 - @count = 256 - @server = nil - - # we want random binary data to test 1.9 encoding-aware IO craziness - @random = File.open('/dev/urandom','rb') - @sha1 = Digest::SHA1.new - @sha1_app = lambda do |env| - input = env['rack.input'] - resp = {} - - @sha1.reset - while buf = input.read(@bs) - @sha1.update(buf) - end - resp[:sha1] = @sha1.hexdigest - - # rewind and read again - input.rewind - @sha1.reset - while buf = input.read(@bs) - @sha1.update(buf) - end - - if resp[:sha1] == @sha1.hexdigest - resp[:sysread_read_byte_match] = true - end - - if expect_size = env['HTTP_X_EXPECT_SIZE'] - if expect_size.to_i == input.size - resp[:expect_size_match] = true - end - end - resp[:size] = input.size - resp[:content_md5] = env['HTTP_CONTENT_MD5'] - - [ 200, @hdr.merge({'X-Resp' => resp.inspect}), [] ] - end - end - - def teardown - redirect_test_io { @server.stop(false) } if @server - @random.close - reset_sig_handlers - end - - def test_put - start_server(@sha1_app) - sock = TCPSocket.new(@addr, @port) - sock.syswrite("PUT / HTTP/1.0\r\nContent-Length: #{length}\r\n\r\n") - @count.times do |i| - buf = @random.sysread(@bs) - @sha1.update(buf) - sock.syswrite(buf) - end - read = sock.read.split(/\r\n/) - assert_equal "HTTP/1.1 200 OK", read[0] - resp = eval(read.grep(/^X-Resp: /).first.sub!(/X-Resp: /, '')) - assert_equal length, resp[:size] - assert_equal @sha1.hexdigest, resp[:sha1] - end - - def test_put_content_md5 - md5 = Digest::MD5.new - start_server(@sha1_app) - sock = TCPSocket.new(@addr, @port) - sock.syswrite("PUT / HTTP/1.0\r\nTransfer-Encoding: chunked\r\n" \ - "Trailer: Content-MD5\r\n\r\n") - @count.times do |i| - buf = @random.sysread(@bs) - @sha1.update(buf) - md5.update(buf) - sock.syswrite("#{'%x' % buf.size}\r\n") - sock.syswrite(buf << "\r\n") - end - sock.syswrite("0\r\n") - - content_md5 = [ md5.digest! ].pack('m').strip.freeze - sock.syswrite("Content-MD5: #{content_md5}\r\n\r\n") - read = sock.read.split(/\r\n/) - assert_equal "HTTP/1.1 200 OK", read[0] - resp = eval(read.grep(/^X-Resp: /).first.sub!(/X-Resp: /, '')) - assert_equal length, resp[:size] - assert_equal @sha1.hexdigest, resp[:sha1] - assert_equal content_md5, resp[:content_md5] - end - - def test_put_trickle_small - @count, @bs = 2, 128 - start_server(@sha1_app) - assert_equal 256, length - sock = TCPSocket.new(@addr, @port) - hdr = "PUT / HTTP/1.0\r\nContent-Length: #{length}\r\n\r\n" - @count.times do - buf = @random.sysread(@bs) - @sha1.update(buf) - hdr << buf - sock.syswrite(hdr) - hdr = '' - sleep 0.6 - end - read = sock.read.split(/\r\n/) - assert_equal "HTTP/1.1 200 OK", read[0] - resp = eval(read.grep(/^X-Resp: /).first.sub!(/X-Resp: /, '')) - assert_equal length, resp[:size] - assert_equal @sha1.hexdigest, resp[:sha1] - end - - def test_put_keepalive_truncates_small_overwrite - start_server(@sha1_app) - sock = TCPSocket.new(@addr, @port) - to_upload = length + 1 - sock.syswrite("PUT / HTTP/1.0\r\nContent-Length: #{to_upload}\r\n\r\n") - @count.times do - buf = @random.sysread(@bs) - @sha1.update(buf) - sock.syswrite(buf) - end - sock.syswrite('12345') # write 4 bytes more than we expected - @sha1.update('1') - - buf = sock.readpartial(4096) - while buf !~ /\r\n\r\n/ - buf << sock.readpartial(4096) - end - read = buf.split(/\r\n/) - assert_equal "HTTP/1.1 200 OK", read[0] - resp = eval(read.grep(/^X-Resp: /).first.sub!(/X-Resp: /, '')) - assert_equal to_upload, resp[:size] - assert_equal @sha1.hexdigest, resp[:sha1] - end - - def test_put_excessive_overwrite_closed - tmp = Tempfile.new('overwrite_check') - tmp.sync = true - start_server(lambda { |env| - nr = 0 - while buf = env['rack.input'].read(65536) - nr += buf.size - end - tmp.write(nr.to_s) - [ 200, @hdr, [] ] - }) - sock = TCPSocket.new(@addr, @port) - buf = ' ' * @bs - sock.syswrite("PUT / HTTP/1.0\r\nContent-Length: #{length}\r\n\r\n") - - @count.times { sock.syswrite(buf) } - assert_raise(Errno::ECONNRESET, Errno::EPIPE) do - ::Unicorn::Const::CHUNK_SIZE.times { sock.syswrite(buf) } - end - sock.gets - tmp.rewind - assert_equal length, tmp.read.to_i - end - - # Despite reading numerous articles and inspecting the 1.9.1-p0 C - # source, Eric Wong will never trust that we're always handling - # encoding-aware IO objects correctly. Thus this test uses shell - # utilities that should always operate on files/sockets on a - # byte-level. - def test_uncomfortable_with_onenine_encodings - # POSIX doesn't require all of these to be present on a system - which('curl') or return - which('sha1sum') or return - which('dd') or return - - start_server(@sha1_app) - - tmp = Tempfile.new('dd_dest') - assert(system("dd", "if=#{@random.path}", "of=#{tmp.path}", - "bs=#{@bs}", "count=#{@count}"), - "dd #@random to #{tmp}") - sha1_re = %r!\b([a-f0-9]{40})\b! - sha1_out = `sha1sum #{tmp.path}` - assert $?.success?, 'sha1sum ran OK' - - assert_match(sha1_re, sha1_out) - sha1 = sha1_re.match(sha1_out)[1] - resp = `curl -isSfN -T#{tmp.path} http://#@addr:#@port/` - assert $?.success?, 'curl ran OK' - assert_match(%r!\b#{sha1}\b!, resp) - assert_match(/sysread_read_byte_match/, resp) - - # small StringIO path - assert(system("dd", "if=#{@random.path}", "of=#{tmp.path}", - "bs=1024", "count=1"), - "dd #@random to #{tmp}") - sha1_re = %r!\b([a-f0-9]{40})\b! - sha1_out = `sha1sum #{tmp.path}` - assert $?.success?, 'sha1sum ran OK' - - assert_match(sha1_re, sha1_out) - sha1 = sha1_re.match(sha1_out)[1] - resp = `curl -isSfN -T#{tmp.path} http://#@addr:#@port/` - assert $?.success?, 'curl ran OK' - assert_match(%r!\b#{sha1}\b!, resp) - assert_match(/sysread_read_byte_match/, resp) - end - - def test_chunked_upload_via_curl - # POSIX doesn't require all of these to be present on a system - which('curl') or return - which('sha1sum') or return - which('dd') or return - - start_server(@sha1_app) - - tmp = Tempfile.new('dd_dest') - assert(system("dd", "if=#{@random.path}", "of=#{tmp.path}", - "bs=#{@bs}", "count=#{@count}"), - "dd #@random to #{tmp}") - sha1_re = %r!\b([a-f0-9]{40})\b! - sha1_out = `sha1sum #{tmp.path}` - assert $?.success?, 'sha1sum ran OK' - - assert_match(sha1_re, sha1_out) - sha1 = sha1_re.match(sha1_out)[1] - cmd = "curl -H 'X-Expect-Size: #{tmp.size}' --tcp-nodelay \ - -isSf --no-buffer -T- " \ - "http://#@addr:#@port/" - resp = Tempfile.new('resp') - resp.sync = true - - rd, wr = IO.pipe - wr.sync = rd.sync = true - pid = fork { - STDIN.reopen(rd) - rd.close - wr.close - STDOUT.reopen(resp) - exec cmd - } - rd.close - - tmp.rewind - @count.times { |i| - wr.write(tmp.read(@bs)) - sleep(rand / 10) if 0 == i % 8 - } - wr.close - pid, status = Process.waitpid2(pid) - - resp.rewind - resp = resp.read - assert status.success?, 'curl ran OK' - assert_match(%r!\b#{sha1}\b!, resp) - assert_match(/sysread_read_byte_match/, resp) - assert_match(/expect_size_match/, resp) - end - - def test_curl_chunked_small - # POSIX doesn't require all of these to be present on a system - which('curl') or return - which('sha1sum') or return - which('dd') or return - - start_server(@sha1_app) - - tmp = Tempfile.new('dd_dest') - # small StringIO path - assert(system("dd", "if=#{@random.path}", "of=#{tmp.path}", - "bs=1024", "count=1"), - "dd #@random to #{tmp}") - sha1_re = %r!\b([a-f0-9]{40})\b! - sha1_out = `sha1sum #{tmp.path}` - assert $?.success?, 'sha1sum ran OK' - - assert_match(sha1_re, sha1_out) - sha1 = sha1_re.match(sha1_out)[1] - resp = `curl -H 'X-Expect-Size: #{tmp.size}' --tcp-nodelay \ - -isSf --no-buffer -T- http://#@addr:#@port/ < #{tmp.path}` - assert $?.success?, 'curl ran OK' - assert_match(%r!\b#{sha1}\b!, resp) - assert_match(/sysread_read_byte_match/, resp) - assert_match(/expect_size_match/, resp) - end - - private - - def length - @bs * @count - end - - def start_server(app) - redirect_test_io do - @server = HttpServer.new(app, :listeners => [ "#{@addr}:#{@port}" ] ) - @server.start - end - end - -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_util.rb b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_util.rb deleted file mode 100644 index 904d51c..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/test/unit/test_util.rb +++ /dev/null @@ -1,105 +0,0 @@ -# -*- encoding: binary -*- - -require 'test/test_helper' -require 'tempfile' - -class TestUtil < Test::Unit::TestCase - - EXPECT_FLAGS = File::WRONLY | File::APPEND - def test_reopen_logs_noop - tmp = Tempfile.new('') - fp = File.open(tmp.path, 'ab') - fp.sync = true - ext = fp.external_encoding rescue nil - int = fp.internal_encoding rescue nil - before = fp.stat.inspect - Unicorn::Util.reopen_logs - assert_equal before, File.stat(fp.path).inspect - assert_equal ext, (fp.external_encoding rescue nil) - assert_equal int, (fp.internal_encoding rescue nil) - assert_equal(EXPECT_FLAGS, EXPECT_FLAGS & fp.fcntl(Fcntl::F_GETFL)) - tmp.close! - fp.close - end - - def test_reopen_logs_renamed - tmp = Tempfile.new('') - tmp_path = tmp.path.freeze - fp = File.open(tmp_path, 'ab') - fp.sync = true - - ext = fp.external_encoding rescue nil - int = fp.internal_encoding rescue nil - before = fp.stat.inspect - to = Tempfile.new('') - File.rename(tmp_path, to.path) - assert ! File.exist?(tmp_path) - Unicorn::Util.reopen_logs - assert_equal tmp_path, tmp.path - assert File.exist?(tmp_path) - assert before != File.stat(tmp_path).inspect - assert_equal fp.stat.inspect, File.stat(tmp_path).inspect - assert_equal ext, (fp.external_encoding rescue nil) - assert_equal int, (fp.internal_encoding rescue nil) - assert_equal(EXPECT_FLAGS, EXPECT_FLAGS & fp.fcntl(Fcntl::F_GETFL)) - assert fp.sync - tmp.close! - to.close! - fp.close - end - - def test_reopen_logs_renamed_with_encoding - tmp = Tempfile.new('') - tmp_path = tmp.path.dup.freeze - Encoding.list.each { |encoding| - File.open(tmp_path, "a:#{encoding.to_s}") { |fp| - fp.sync = true - assert_equal encoding, fp.external_encoding - assert_nil fp.internal_encoding - File.unlink(tmp_path) - assert ! File.exist?(tmp_path) - Unicorn::Util.reopen_logs - assert_equal tmp_path, fp.path - assert File.exist?(tmp_path) - assert_equal fp.stat.inspect, File.stat(tmp_path).inspect - assert_equal encoding, fp.external_encoding - assert_nil fp.internal_encoding - assert_equal(EXPECT_FLAGS, EXPECT_FLAGS & fp.fcntl(Fcntl::F_GETFL)) - assert fp.sync - } - } - tmp.close! - end if STDIN.respond_to?(:external_encoding) - - def test_reopen_logs_renamed_with_internal_encoding - tmp = Tempfile.new('') - tmp_path = tmp.path.dup.freeze - Encoding.list.each { |ext| - Encoding.list.each { |int| - next if ext == int - File.open(tmp_path, "a:#{ext.to_s}:#{int.to_s}") { |fp| - fp.sync = true - assert_equal ext, fp.external_encoding - - if ext != Encoding::BINARY - assert_equal int, fp.internal_encoding - end - - File.unlink(tmp_path) - assert ! File.exist?(tmp_path) - Unicorn::Util.reopen_logs - assert_equal tmp_path, fp.path - assert File.exist?(tmp_path) - assert_equal fp.stat.inspect, File.stat(tmp_path).inspect - assert_equal ext, fp.external_encoding - if ext != Encoding::BINARY - assert_equal int, fp.internal_encoding - end - assert_equal(EXPECT_FLAGS, EXPECT_FLAGS & fp.fcntl(Fcntl::F_GETFL)) - assert fp.sync - } - } - } - tmp.close! - end if STDIN.respond_to?(:external_encoding) -end diff --git a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/unicorn.gemspec b/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/unicorn.gemspec deleted file mode 100644 index c0c8092..0000000 --- a/vendor/bundle/ruby/2.0.0/gems/unicorn-4.8.3/unicorn.gemspec +++ /dev/null @@ -1,44 +0,0 @@ -# -*- encoding: binary -*- -ENV["VERSION"] or abort "VERSION= must be specified" -manifest = File.readlines('.manifest').map! { |x| x.chomp! } -require 'wrongdoc' -extend Wrongdoc::Gemspec -name, summary, title = readme_metadata - -# don't bother with tests that fork, not worth our time to get working -# with `gem check -t` ... (of course we care for them when testing with -# GNU make when they can run in parallel) -test_files = manifest.grep(%r{\Atest/unit/test_.*\.rb\z}).map do |f| - File.readlines(f).grep(/\bfork\b/).empty? ? f : nil -end.compact - -Gem::Specification.new do |s| - s.name = %q{unicorn} - s.version = ENV["VERSION"].dup - s.authors = ["#{name} hackers"] - s.summary = summary - s.date = Time.now.utc.strftime('%Y-%m-%d') - s.description = readme_description - s.email = %q{unicorn-public@bogomips.org} - s.executables = %w(unicorn unicorn_rails) - s.extensions = %w(ext/unicorn_http/extconf.rb) - s.extra_rdoc_files = extra_rdoc_files(manifest) - s.files = manifest - s.homepage = Wrongdoc.config[:rdoc_url] - s.rdoc_options = rdoc_options - s.rubyforge_project = %q{mongrel} - s.test_files = test_files - - # for people that are absolutely stuck on Rails 2.3.2 and can't - # up/downgrade to any other version, the Rack dependency may be - # commented out. Nevertheless, upgrading to Rails 2.3.4 or later is - # *strongly* recommended for security reasons. - s.add_dependency(%q) - s.add_dependency(%q, '~> 2.6') - s.add_dependency(%q, '~> 0.7') - - s.add_development_dependency('isolate', '~> 3.2') - s.add_development_dependency('wrongdoc', '~> 1.8') - - s.licenses = ["GPLv2+", "Ruby 1.8"] -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/diff-lcs-1.2.5.gemspec b/vendor/bundle/ruby/2.0.0/specifications/diff-lcs-1.2.5.gemspec deleted file mode 100644 index cc088b4..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/diff-lcs-1.2.5.gemspec +++ /dev/null @@ -1,68 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: diff-lcs 1.2.5 ruby lib - -Gem::Specification.new do |s| - s.name = "diff-lcs" - s.version = "1.2.5" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Austin Ziegler"] - s.cert_chain = ["-----BEGIN CERTIFICATE-----\nMIIDNjCCAh6gAwIBAgIBADANBgkqhkiG9w0BAQUFADBBMQ8wDQYDVQQDDAZhdXN0\naW4xGTAXBgoJkiaJk/IsZAEZFglydWJ5Zm9yZ2UxEzARBgoJkiaJk/IsZAEZFgNv\ncmcwHhcNMTMwMjA0MDMzMzI3WhcNMTQwMjA0MDMzMzI3WjBBMQ8wDQYDVQQDDAZh\ndXN0aW4xGTAXBgoJkiaJk/IsZAEZFglydWJ5Zm9yZ2UxEzARBgoJkiaJk/IsZAEZ\nFgNvcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC2mPNf4L37GhKI\nSPCYsvYWXA2/R9u5+pyUnbJ2R1o2CiRq2ZA/AIzY6N3hGnsgoWnh5RzvgTN1Lt08\nDNIrsIG2VDYk/JVt6f9J6zZ8EQHbznWa3cWYoCFaaICdk7jV1n/42hg70jEDYXl9\ngDOl0k6JmyF/rtfFu/OIkFGWeFYIuFHvRuLyUbw66+QDTOzKb3t8o55Ihgy1GVwT\ni6pkDs8LhZWXdOD+921l2Z1NZGZa9KNbJIg6vtgYKU98jQ5qr9iY3ikBAspHrFas\nK6USvGgAg8fCD5YiotBEvCBMYtfqmfrhpdU2p+gvTgeLW1Kaevwqd7ngQmFUrFG1\neUJSURv5AgMBAAGjOTA3MAkGA1UdEwQCMAAwHQYDVR0OBBYEFAtJKMp6YYNqlgR3\n9TiZLWqvLagSMAsGA1UdDwQEAwIEsDANBgkqhkiG9w0BAQUFAAOCAQEApTPkvDm8\n7gJlUT4FfumXPvtuqP67LxUtGE8syvR0A4As+0P/wylLJFUOsGTTdZYtThhxCSJG\n+7KG2FfIcH4Zz2d97arZGAzBoi8iPht2/UtSl1fCcUI5vmJa1MiXZT2oqdW7Wydq\nrAZcBPlrYYuiwtGI0yqIOgBfXSZCWWsJsuyTKELep6mCLgz0YZUfmvKr8W/Ab3ax\nDuLzH92LSRjZJyjyAUpw/Vc2rM4giiP5jtByrb1Y1dGnQhHTMHf1GfucWm7Nw/V9\ntwEPVw8+0f88JQucxOTmTF1NbLFpiRwQUZ1zoZbNg2e7mShc/eexnVLWKFKxRoP6\nKPj3WoD+spB8fA==\n-----END CERTIFICATE-----\n"] - s.date = "2013-11-08" - s.description = "Diff::LCS computes the difference between two Enumerable sequences using the\nMcIlroy-Hunt longest common subsequence (LCS) algorithm. It includes utilities\nto create a simple HTML diff output format and a standard diff-like tool.\n\nThis is release 1.2.4, fixing a bug introduced after diff-lcs 1.1.3 that did\nnot properly prune common sequences at the beginning of a comparison set.\nThanks to Paul Kunysch for fixing this issue.\n\nCoincident with the release of diff-lcs 1.2.3, we reported an issue with\nRubinius in 1.9 mode\n({rubinius/rubinius#2268}[https://github.com/rubinius/rubinius/issues/2268]).\nWe are happy to report that this issue has been resolved." - s.email = ["austin@rubyforge.org"] - s.executables = ["htmldiff", "ldiff"] - s.extra_rdoc_files = ["Contributing.rdoc", "History.rdoc", "License.rdoc", "Manifest.txt", "README.rdoc", "docs/COPYING.txt", "docs/artistic.txt"] - s.files = ["Contributing.rdoc", "History.rdoc", "License.rdoc", "Manifest.txt", "README.rdoc", "bin/htmldiff", "bin/ldiff", "docs/COPYING.txt", "docs/artistic.txt"] - s.homepage = "http://diff-lcs.rubyforge.org/" - s.licenses = ["MIT", "Perl Artistic v2", "GNU GPL v2"] - s.rdoc_options = ["--main", "README.rdoc"] - s.rubyforge_project = "diff-lcs" - s.rubygems_version = "2.4.1" - s.summary = "Diff::LCS computes the difference between two Enumerable sequences using the McIlroy-Hunt longest common subsequence (LCS) algorithm" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q, [">= 2.0.4"]) - s.add_development_dependency(%q, ["~> 4.0"]) - s.add_development_dependency(%q, ["~> 1.2"]) - s.add_development_dependency(%q, ["~> 1.0"]) - s.add_development_dependency(%q, ["~> 1.1"]) - s.add_development_dependency(%q, ["~> 1.5"]) - s.add_development_dependency(%q, ["~> 1.0"]) - s.add_development_dependency(%q, ["~> 1.2"]) - s.add_development_dependency(%q, ["~> 10.0"]) - s.add_development_dependency(%q, ["~> 2.0"]) - s.add_development_dependency(%q, ["~> 3.7"]) - else - s.add_dependency(%q, [">= 2.0.4"]) - s.add_dependency(%q, ["~> 4.0"]) - s.add_dependency(%q, ["~> 1.2"]) - s.add_dependency(%q, ["~> 1.0"]) - s.add_dependency(%q, ["~> 1.1"]) - s.add_dependency(%q, ["~> 1.5"]) - s.add_dependency(%q, ["~> 1.0"]) - s.add_dependency(%q, ["~> 1.2"]) - s.add_dependency(%q, ["~> 10.0"]) - s.add_dependency(%q, ["~> 2.0"]) - s.add_dependency(%q, ["~> 3.7"]) - end - else - s.add_dependency(%q, [">= 2.0.4"]) - s.add_dependency(%q, ["~> 4.0"]) - s.add_dependency(%q, ["~> 1.2"]) - s.add_dependency(%q, ["~> 1.0"]) - s.add_dependency(%q, ["~> 1.1"]) - s.add_dependency(%q, ["~> 1.5"]) - s.add_dependency(%q, ["~> 1.0"]) - s.add_dependency(%q, ["~> 1.2"]) - s.add_dependency(%q, ["~> 10.0"]) - s.add_dependency(%q, ["~> 2.0"]) - s.add_dependency(%q, ["~> 3.7"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/dotenv-0.11.1.gemspec b/vendor/bundle/ruby/2.0.0/specifications/dotenv-0.11.1.gemspec deleted file mode 100644 index 32ae5a6..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/dotenv-0.11.1.gemspec +++ /dev/null @@ -1,40 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: dotenv 0.11.1 ruby lib - -Gem::Specification.new do |s| - s.name = "dotenv" - s.version = "0.11.1" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Brandon Keepers"] - s.date = "2014-04-22" - s.description = "Loads environment variables from `.env`." - s.email = ["brandon@opensoul.org"] - s.executables = ["dotenv"] - s.files = ["bin/dotenv"] - s.homepage = "https://github.com/bkeepers/dotenv" - s.licenses = ["MIT"] - s.rubygems_version = "2.4.1" - s.summary = "Loads environment variables from `.env`." - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, ["~> 0.0.2"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - else - s.add_dependency(%q, ["~> 0.0.2"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - end - else - s.add_dependency(%q, ["~> 0.0.2"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/dotenv-deployment-0.0.2.gemspec b/vendor/bundle/ruby/2.0.0/specifications/dotenv-deployment-0.0.2.gemspec deleted file mode 100644 index bda0008..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/dotenv-deployment-0.0.2.gemspec +++ /dev/null @@ -1,34 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: dotenv-deployment 0.0.2 ruby lib - -Gem::Specification.new do |s| - s.name = "dotenv-deployment" - s.version = "0.0.2" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Brandon Keepers"] - s.date = "2014-04-22" - s.email = ["brandon@opensoul.org"] - s.homepage = "https://github.com/bkeepers/dotenv-deployment" - s.licenses = ["MIT"] - s.rubygems_version = "2.4.1" - s.summary = "Deployment concerns for dotenv" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q, ["~> 1.5"]) - s.add_development_dependency(%q, [">= 0"]) - else - s.add_dependency(%q, ["~> 1.5"]) - s.add_dependency(%q, [">= 0"]) - end - else - s.add_dependency(%q, ["~> 1.5"]) - s.add_dependency(%q, [">= 0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/foreman-0.74.0.gemspec b/vendor/bundle/ruby/2.0.0/specifications/foreman-0.74.0.gemspec deleted file mode 100644 index 39edfbb..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/foreman-0.74.0.gemspec +++ /dev/null @@ -1,37 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: foreman 0.74.0 ruby lib - -Gem::Specification.new do |s| - s.name = "foreman" - s.version = "0.74.0" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["David Dollar"] - s.date = "2014-06-19" - s.description = "Process manager for applications with multiple components" - s.email = "ddollar@gmail.com" - s.executables = ["foreman"] - s.files = ["bin/foreman"] - s.homepage = "http://github.com/ddollar/foreman" - s.licenses = ["MIT"] - s.rubygems_version = "2.4.1" - s.summary = "Process manager for applications with multiple components" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, ["~> 0.19.1"]) - s.add_runtime_dependency(%q, ["~> 0.11.1"]) - else - s.add_dependency(%q, ["~> 0.19.1"]) - s.add_dependency(%q, ["~> 0.11.1"]) - end - else - s.add_dependency(%q, ["~> 0.19.1"]) - s.add_dependency(%q, ["~> 0.11.1"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/kgio-2.9.2.gemspec b/vendor/bundle/ruby/2.0.0/specifications/kgio-2.9.2.gemspec deleted file mode 100644 index ac70d2f..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/kgio-2.9.2.gemspec +++ /dev/null @@ -1,25 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: kgio 2.9.2 ruby lib -# stub: ext/kgio/extconf.rb - -Gem::Specification.new do |s| - s.name = "kgio" - s.version = "2.9.2" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["kgio hackers"] - s.date = "2014-02-15" - s.description = "kgio provides non-blocking I/O methods for Ruby without raising\nexceptions on EAGAIN and EINPROGRESS. It is intended for use with the\nUnicorn and Rainbows! Rack servers, but may be used by other\napplications (that run on Unix-like platforms)." - s.email = "kgio@librelist.org" - s.extensions = ["ext/kgio/extconf.rb"] - s.extra_rdoc_files = ["LICENSE", "README", "TODO", "NEWS", "LATEST", "ChangeLog", "ISSUES", "HACKING", "lib/kgio.rb", "ext/kgio/accept.c", "ext/kgio/autopush.c", "ext/kgio/connect.c", "ext/kgio/kgio_ext.c", "ext/kgio/poll.c", "ext/kgio/wait.c", "ext/kgio/tryopen.c"] - s.files = ["ChangeLog", "HACKING", "ISSUES", "LATEST", "LICENSE", "NEWS", "README", "TODO", "ext/kgio/accept.c", "ext/kgio/autopush.c", "ext/kgio/connect.c", "ext/kgio/extconf.rb", "ext/kgio/kgio_ext.c", "ext/kgio/poll.c", "ext/kgio/tryopen.c", "ext/kgio/wait.c", "lib/kgio.rb"] - s.homepage = "http://bogomips.org/kgio/" - s.rdoc_options = ["-t", "kgio - kinder, gentler I/O for Ruby", "-W", "http://bogomips.org/kgio.git/tree/%s"] - s.rubyforge_project = "rainbows" - s.rubygems_version = "2.4.1" - s.summary = "kinder, gentler I/O for Ruby" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/rack-1.5.2.gemspec b/vendor/bundle/ruby/2.0.0/specifications/rack-1.5.2.gemspec deleted file mode 100644 index 424a81f..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/rack-1.5.2.gemspec +++ /dev/null @@ -1,39 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: rack 1.5.2 ruby lib - -Gem::Specification.new do |s| - s.name = "rack" - s.version = "1.5.2" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Christian Neukirchen"] - s.date = "2013-02-08" - s.description = "Rack provides a minimal, modular and adaptable interface for developing\nweb applications in Ruby. By wrapping HTTP requests and responses in\nthe simplest way possible, it unifies and distills the API for web\nservers, web frameworks, and software in between (the so-called\nmiddleware) into a single method call.\n\nAlso see http://rack.github.com/.\n" - s.email = "chneukirchen@gmail.com" - s.executables = ["rackup"] - s.extra_rdoc_files = ["README.rdoc", "KNOWN-ISSUES"] - s.files = ["KNOWN-ISSUES", "README.rdoc", "bin/rackup"] - s.homepage = "http://rack.github.com/" - s.licenses = ["MIT"] - s.rubyforge_project = "rack" - s.rubygems_version = "2.4.1" - s.summary = "a modular Ruby webserver interface" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 3 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - end - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/rack-protection-1.5.3.gemspec b/vendor/bundle/ruby/2.0.0/specifications/rack-protection-1.5.3.gemspec deleted file mode 100644 index c619659..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/rack-protection-1.5.3.gemspec +++ /dev/null @@ -1,38 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: rack-protection 1.5.3 ruby lib - -Gem::Specification.new do |s| - s.name = "rack-protection" - s.version = "1.5.3" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Konstantin Haase", "Alex Rodionov", "Patrick Ellis", "Jason Staten", "ITO Nobuaki", "Jeff Welling", "Matteo Centenaro", "Egor Homakov", "Florian Gilcher", "Fojas", "Igor Bochkariov", "Mael Clerambault", "Martin Mauch", "Renne Nissinen", "SAKAI, Kazuaki", "Stanislav Savulchik", "Steve Agalloco", "TOBY", "Thais Camilo and Konstantin Haase", "Vipul A M", "Akzhan Abdulin", "brookemckim", "Bj\u{f8}rge N\u{e6}ss", "Chris Heald", "Chris Mytton", "Corey Ward", "Dario Cravero", "David Kellum"] - s.date = "2014-04-08" - s.description = "You should use protection!" - s.email = ["konstantin.mailinglists@googlemail.com", "p0deje@gmail.com", "jstaten07@gmail.com", "patrick@soundcloud.com", "jeff.welling@gmail.com", "bugant@gmail.com", "daydream.trippers@gmail.com", "florian.gilcher@asquera.de", "developer@fojasaur.us", "ujifgc@gmail.com", "mael@clerambault.fr", "martin.mauch@gmail.com", "rennex@iki.fi", "kaz.july.7@gmail.com", "s.savulchik@gmail.com", "steve.agalloco@gmail.com", "toby.net.info.mail+git@gmail.com", "dev+narwen+rkh@rkh.im", "vipulnsward@gmail.com", "akzhan.abdulin@gmail.com", "brooke@digitalocean.com", "bjoerge@bengler.no", "cheald@gmail.com", "self@hecticjeff.net", "coreyward@me.com", "dario@uxtemple.com", "dek-oss@gravitext.com", "homakov@gmail.com"] - s.homepage = "http://github.com/rkh/rack-protection" - s.licenses = ["MIT"] - s.rubygems_version = "2.4.1" - s.summary = "You should use protection!" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, ["~> 2.0"]) - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["~> 2.0"]) - end - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["~> 2.0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/raindrops-0.13.0.gemspec b/vendor/bundle/ruby/2.0.0/specifications/raindrops-0.13.0.gemspec deleted file mode 100644 index bb34bdf..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/raindrops-0.13.0.gemspec +++ /dev/null @@ -1,53 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: raindrops 0.13.0 ruby lib -# stub: ext/raindrops/extconf.rb - -Gem::Specification.new do |s| - s.name = "raindrops" - s.version = "0.13.0" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["raindrops hackers"] - s.date = "2014-02-18" - s.description = "Raindrops is a real-time stats toolkit to show statistics for Rack HTTP\nservers. It is designed for preforking servers such as Rainbows! and\nUnicorn, but should support any Rack HTTP server under Ruby 2.0, 1.9,\n1.8 and Rubinius on platforms supporting POSIX shared memory. It may\nalso be used as a generic scoreboard for sharing atomic counters across\nmultiple processes." - s.email = "raindrops@librelist.org" - s.extensions = ["ext/raindrops/extconf.rb"] - s.extra_rdoc_files = ["README", "LICENSE", "NEWS", "ChangeLog", "lib/raindrops.rb", "lib/raindrops/aggregate.rb", "lib/raindrops/aggregate/last_data_recv.rb", "lib/raindrops/aggregate/pmq.rb", "lib/raindrops/last_data_recv.rb", "lib/raindrops/linux.rb", "lib/raindrops/middleware.rb", "lib/raindrops/middleware/proxy.rb", "lib/raindrops/struct.rb", "lib/raindrops/watcher.rb", "ext/raindrops/raindrops.c", "ext/raindrops/linux_inet_diag.c", "ext/raindrops/linux_tcp_info.c"] - s.files = ["ChangeLog", "LICENSE", "NEWS", "README", "ext/raindrops/extconf.rb", "ext/raindrops/linux_inet_diag.c", "ext/raindrops/linux_tcp_info.c", "ext/raindrops/raindrops.c", "lib/raindrops.rb", "lib/raindrops/aggregate.rb", "lib/raindrops/aggregate/last_data_recv.rb", "lib/raindrops/aggregate/pmq.rb", "lib/raindrops/last_data_recv.rb", "lib/raindrops/linux.rb", "lib/raindrops/middleware.rb", "lib/raindrops/middleware/proxy.rb", "lib/raindrops/struct.rb", "lib/raindrops/watcher.rb"] - s.homepage = "http://raindrops.bogomips.org/" - s.licenses = ["LGPLv2.1+"] - s.rdoc_options = ["-t", "raindrops - real-time stats for preforking Rack servers", "-W", "http://bogomips.org/raindrops.git/tree/%s"] - s.rubyforge_project = "rainbows" - s.rubygems_version = "2.4.1" - s.summary = "real-time stats for preforking Rack servers" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 3 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q, ["~> 0.2"]) - s.add_development_dependency(%q, [">= 1.2.3", "~> 1.2"]) - s.add_development_dependency(%q, ["~> 2.0"]) - s.add_development_dependency(%q, ["~> 1.2"]) - s.add_development_dependency(%q, [">= 0.98"]) - s.add_development_dependency(%q, [">= 1.6.2", "~> 1.6.2"]) - else - s.add_dependency(%q, ["~> 0.2"]) - s.add_dependency(%q, [">= 1.2.3", "~> 1.2"]) - s.add_dependency(%q, ["~> 2.0"]) - s.add_dependency(%q, ["~> 1.2"]) - s.add_dependency(%q, [">= 0.98"]) - s.add_dependency(%q, [">= 1.6.2", "~> 1.6.2"]) - end - else - s.add_dependency(%q, ["~> 0.2"]) - s.add_dependency(%q, [">= 1.2.3", "~> 1.2"]) - s.add_dependency(%q, ["~> 2.0"]) - s.add_dependency(%q, ["~> 1.2"]) - s.add_dependency(%q, [">= 0.98"]) - s.add_dependency(%q, [">= 1.6.2", "~> 1.6.2"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/rspec-3.0.0.gemspec b/vendor/bundle/ruby/2.0.0/specifications/rspec-3.0.0.gemspec deleted file mode 100644 index 5e4aec3..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/rspec-3.0.0.gemspec +++ /dev/null @@ -1,43 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: rspec 3.0.0 ruby lib - -Gem::Specification.new do |s| - s.name = "rspec" - s.version = "3.0.0" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Steven Baker", "David Chelimsky", "Myron Marston"] - s.cert_chain = ["-----BEGIN CERTIFICATE-----\nMIIDjjCCAnagAwIBAgIBATANBgkqhkiG9w0BAQUFADBGMRIwEAYDVQQDDAlyc3Bl\nYy1kZXYxGzAZBgoJkiaJk/IsZAEZFgtnb29nbGVnb3VwczETMBEGCgmSJomT8ixk\nARkWA2NvbTAeFw0xMzExMDcxOTQyNTlaFw0xNDExMDcxOTQyNTlaMEYxEjAQBgNV\nBAMMCXJzcGVjLWRldjEbMBkGCgmSJomT8ixkARkWC2dvb2dsZWdvdXBzMRMwEQYK\nCZImiZPyLGQBGRYDY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\nnhCeZouDLXWO55no+EdZNCtjXjfJQ1X9TbPcvBDD29OypIUce2h/VdKXB2gI7ZHs\nF5NkPggslTErGFmWAtIiur7u943RVqHOsyoIsy065F9fCtrykkA+22elvTDha4Iz\nRUCvuhQ3klatYk4jF+cGt1jNONNVdLOiy0bMynvcM7hoVQ2AomwGs+cEOWQ/4dkD\nJcNV3qfzF5QBcTD2372XNM53b25nYVQSX2KH5FF7BhlKyov33bOm2gA9M+mWIujW\nqgkyxVlfrlE+ZBgV3wXn1Cojg1LpTq35yOArgwioyrwwlZZJR9joN9s/nDklfr5A\n+dyETjFc6cmEPWZrt2cJBQIDAQABo4GGMIGDMAkGA1UdEwQCMAAwCwYDVR0PBAQD\nAgSwMB0GA1UdDgQWBBSW+WD7hn1swJ1A7i8tbuFeuNCJCjAkBgNVHREEHTAbgRly\nc3BlYy1kZXZAZ29vZ2xlZ291cHMuY29tMCQGA1UdEgQdMBuBGXJzcGVjLWRldkBn\nb29nbGVnb3Vwcy5jb20wDQYJKoZIhvcNAQEFBQADggEBAH27jAZ8sD7vnXupj6Y+\nBaBdfHtCkFaslLJ0aKuMDIVXwYuKfqoW15cZPDLmSIEBuQFM3lw6d/hEEL4Uo2jZ\nFvtmH5OxifPDzFyUtCL4yp6qgNe/Xf6sDsRg6FmKcpgqCwNOmsViaf0LPSUH/GYQ\n3Teoz8QCaDbD7AKsffT7eDrnbHnKweO1XdemRJC98u/yYxnGzMSWKEsn09etBlZ9\n7H67k5Z3uf6cfLZgToWL6zShzZY3Nun5r73YsNf2/QZOe4UZe4vfGvn6baw53ys9\n1yHC1AcSYpvi2dAbOiHT5iQF+krm4wse8KctXgTNnjMsHEoGKulJS2/sZl90jcCz\nmuA=\n-----END CERTIFICATE-----\n"] - s.date = "2014-06-02" - s.description = "BDD for Ruby" - s.email = "rspec@googlegroups.com" - s.extra_rdoc_files = ["README.md"] - s.files = ["README.md"] - s.homepage = "http://github.com/rspec" - s.licenses = ["MIT"] - s.rdoc_options = ["--charset=UTF-8"] - s.rubyforge_project = "rspec" - s.rubygems_version = "2.4.1" - s.summary = "rspec-3.0.0" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, ["~> 3.0.0"]) - s.add_runtime_dependency(%q, ["~> 3.0.0"]) - s.add_runtime_dependency(%q, ["~> 3.0.0"]) - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 3.0.0"]) - end - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 3.0.0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/rspec-core-3.0.3.gemspec b/vendor/bundle/ruby/2.0.0/specifications/rspec-core-3.0.3.gemspec deleted file mode 100644 index e7c619b..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/rspec-core-3.0.3.gemspec +++ /dev/null @@ -1,66 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: rspec-core 3.0.3 ruby lib - -Gem::Specification.new do |s| - s.name = "rspec-core" - s.version = "3.0.3" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Steven Baker", "David Chelimsky", "Chad Humphries", "Myron Marston"] - s.bindir = "exe" - s.cert_chain = ["-----BEGIN CERTIFICATE-----\nMIIDjjCCAnagAwIBAgIBATANBgkqhkiG9w0BAQUFADBGMRIwEAYDVQQDDAlyc3Bl\nYy1kZXYxGzAZBgoJkiaJk/IsZAEZFgtnb29nbGVnb3VwczETMBEGCgmSJomT8ixk\nARkWA2NvbTAeFw0xMzExMDcxOTQyNTlaFw0xNDExMDcxOTQyNTlaMEYxEjAQBgNV\nBAMMCXJzcGVjLWRldjEbMBkGCgmSJomT8ixkARkWC2dvb2dsZWdvdXBzMRMwEQYK\nCZImiZPyLGQBGRYDY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\nnhCeZouDLXWO55no+EdZNCtjXjfJQ1X9TbPcvBDD29OypIUce2h/VdKXB2gI7ZHs\nF5NkPggslTErGFmWAtIiur7u943RVqHOsyoIsy065F9fCtrykkA+22elvTDha4Iz\nRUCvuhQ3klatYk4jF+cGt1jNONNVdLOiy0bMynvcM7hoVQ2AomwGs+cEOWQ/4dkD\nJcNV3qfzF5QBcTD2372XNM53b25nYVQSX2KH5FF7BhlKyov33bOm2gA9M+mWIujW\nqgkyxVlfrlE+ZBgV3wXn1Cojg1LpTq35yOArgwioyrwwlZZJR9joN9s/nDklfr5A\n+dyETjFc6cmEPWZrt2cJBQIDAQABo4GGMIGDMAkGA1UdEwQCMAAwCwYDVR0PBAQD\nAgSwMB0GA1UdDgQWBBSW+WD7hn1swJ1A7i8tbuFeuNCJCjAkBgNVHREEHTAbgRly\nc3BlYy1kZXZAZ29vZ2xlZ291cHMuY29tMCQGA1UdEgQdMBuBGXJzcGVjLWRldkBn\nb29nbGVnb3Vwcy5jb20wDQYJKoZIhvcNAQEFBQADggEBAH27jAZ8sD7vnXupj6Y+\nBaBdfHtCkFaslLJ0aKuMDIVXwYuKfqoW15cZPDLmSIEBuQFM3lw6d/hEEL4Uo2jZ\nFvtmH5OxifPDzFyUtCL4yp6qgNe/Xf6sDsRg6FmKcpgqCwNOmsViaf0LPSUH/GYQ\n3Teoz8QCaDbD7AKsffT7eDrnbHnKweO1XdemRJC98u/yYxnGzMSWKEsn09etBlZ9\n7H67k5Z3uf6cfLZgToWL6zShzZY3Nun5r73YsNf2/QZOe4UZe4vfGvn6baw53ys9\n1yHC1AcSYpvi2dAbOiHT5iQF+krm4wse8KctXgTNnjMsHEoGKulJS2/sZl90jcCz\nmuA=\n-----END CERTIFICATE-----\n"] - s.date = "2014-07-21" - s.description = "BDD for Ruby. RSpec runner and example groups." - s.email = "rspec@googlegroups.com" - s.executables = ["rspec"] - s.files = ["exe/rspec"] - s.homepage = "http://github.com/rspec/rspec-core" - s.licenses = ["MIT"] - s.rdoc_options = ["--charset=UTF-8"] - s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") - s.rubyforge_project = "rspec" - s.rubygems_version = "2.4.1" - s.summary = "rspec-core-3.0.3" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, ["~> 3.0.0"]) - s.add_development_dependency(%q, ["~> 10.0.0"]) - s.add_development_dependency(%q, ["~> 1.3"]) - s.add_development_dependency(%q, ["~> 5.3"]) - s.add_development_dependency(%q, ["~> 0.5"]) - s.add_development_dependency(%q, ["= 1.5.2"]) - s.add_development_dependency(%q, ["~> 1.0.9"]) - s.add_development_dependency(%q, ["~> 0.13.0"]) - s.add_development_dependency(%q, ["~> 1.0.4"]) - s.add_development_dependency(%q, ["~> 0.9.0"]) - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, ["~> 1.3"]) - s.add_dependency(%q, ["~> 5.3"]) - s.add_dependency(%q, ["~> 0.5"]) - s.add_dependency(%q, ["= 1.5.2"]) - s.add_dependency(%q, ["~> 1.0.9"]) - s.add_dependency(%q, ["~> 0.13.0"]) - s.add_dependency(%q, ["~> 1.0.4"]) - s.add_dependency(%q, ["~> 0.9.0"]) - end - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, ["~> 1.3"]) - s.add_dependency(%q, ["~> 5.3"]) - s.add_dependency(%q, ["~> 0.5"]) - s.add_dependency(%q, ["= 1.5.2"]) - s.add_dependency(%q, ["~> 1.0.9"]) - s.add_dependency(%q, ["~> 0.13.0"]) - s.add_dependency(%q, ["~> 1.0.4"]) - s.add_dependency(%q, ["~> 0.9.0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/rspec-expectations-3.0.3.gemspec b/vendor/bundle/ruby/2.0.0/specifications/rspec-expectations-3.0.3.gemspec deleted file mode 100644 index e40d713..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/rspec-expectations-3.0.3.gemspec +++ /dev/null @@ -1,51 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: rspec-expectations 3.0.3 ruby lib - -Gem::Specification.new do |s| - s.name = "rspec-expectations" - s.version = "3.0.3" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Steven Baker", "David Chelimsky", "Myron Marston"] - s.cert_chain = ["-----BEGIN CERTIFICATE-----\nMIIDjjCCAnagAwIBAgIBATANBgkqhkiG9w0BAQUFADBGMRIwEAYDVQQDDAlyc3Bl\nYy1kZXYxGzAZBgoJkiaJk/IsZAEZFgtnb29nbGVnb3VwczETMBEGCgmSJomT8ixk\nARkWA2NvbTAeFw0xMzExMDcxOTQyNTlaFw0xNDExMDcxOTQyNTlaMEYxEjAQBgNV\nBAMMCXJzcGVjLWRldjEbMBkGCgmSJomT8ixkARkWC2dvb2dsZWdvdXBzMRMwEQYK\nCZImiZPyLGQBGRYDY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\nnhCeZouDLXWO55no+EdZNCtjXjfJQ1X9TbPcvBDD29OypIUce2h/VdKXB2gI7ZHs\nF5NkPggslTErGFmWAtIiur7u943RVqHOsyoIsy065F9fCtrykkA+22elvTDha4Iz\nRUCvuhQ3klatYk4jF+cGt1jNONNVdLOiy0bMynvcM7hoVQ2AomwGs+cEOWQ/4dkD\nJcNV3qfzF5QBcTD2372XNM53b25nYVQSX2KH5FF7BhlKyov33bOm2gA9M+mWIujW\nqgkyxVlfrlE+ZBgV3wXn1Cojg1LpTq35yOArgwioyrwwlZZJR9joN9s/nDklfr5A\n+dyETjFc6cmEPWZrt2cJBQIDAQABo4GGMIGDMAkGA1UdEwQCMAAwCwYDVR0PBAQD\nAgSwMB0GA1UdDgQWBBSW+WD7hn1swJ1A7i8tbuFeuNCJCjAkBgNVHREEHTAbgRly\nc3BlYy1kZXZAZ29vZ2xlZ291cHMuY29tMCQGA1UdEgQdMBuBGXJzcGVjLWRldkBn\nb29nbGVnb3Vwcy5jb20wDQYJKoZIhvcNAQEFBQADggEBAH27jAZ8sD7vnXupj6Y+\nBaBdfHtCkFaslLJ0aKuMDIVXwYuKfqoW15cZPDLmSIEBuQFM3lw6d/hEEL4Uo2jZ\nFvtmH5OxifPDzFyUtCL4yp6qgNe/Xf6sDsRg6FmKcpgqCwNOmsViaf0LPSUH/GYQ\n3Teoz8QCaDbD7AKsffT7eDrnbHnKweO1XdemRJC98u/yYxnGzMSWKEsn09etBlZ9\n7H67k5Z3uf6cfLZgToWL6zShzZY3Nun5r73YsNf2/QZOe4UZe4vfGvn6baw53ys9\n1yHC1AcSYpvi2dAbOiHT5iQF+krm4wse8KctXgTNnjMsHEoGKulJS2/sZl90jcCz\nmuA=\n-----END CERTIFICATE-----\n"] - s.date = "2014-07-21" - s.description = "rspec-expectations provides a simple, readable API to express expected outcomes of a code example." - s.email = "rspec@googlegroups.com" - s.homepage = "http://github.com/rspec/rspec-expectations" - s.licenses = ["MIT"] - s.rdoc_options = ["--charset=UTF-8"] - s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") - s.rubyforge_project = "rspec" - s.rubygems_version = "2.4.1" - s.summary = "rspec-expectations-3.0.3" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, ["~> 3.0.0"]) - s.add_runtime_dependency(%q, ["< 2.0", ">= 1.2.0"]) - s.add_development_dependency(%q, ["~> 10.0.0"]) - s.add_development_dependency(%q, ["~> 1.3"]) - s.add_development_dependency(%q, ["~> 0.5"]) - s.add_development_dependency(%q, ["~> 5.2"]) - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["< 2.0", ">= 1.2.0"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, ["~> 1.3"]) - s.add_dependency(%q, ["~> 0.5"]) - s.add_dependency(%q, ["~> 5.2"]) - end - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["< 2.0", ">= 1.2.0"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, ["~> 1.3"]) - s.add_dependency(%q, ["~> 0.5"]) - s.add_dependency(%q, ["~> 5.2"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/rspec-mocks-3.0.3.gemspec b/vendor/bundle/ruby/2.0.0/specifications/rspec-mocks-3.0.3.gemspec deleted file mode 100644 index c280bfe..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/rspec-mocks-3.0.3.gemspec +++ /dev/null @@ -1,48 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: rspec-mocks 3.0.3 ruby lib - -Gem::Specification.new do |s| - s.name = "rspec-mocks" - s.version = "3.0.3" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Steven Baker", "David Chelimsky", "Myron Marston"] - s.cert_chain = ["-----BEGIN CERTIFICATE-----\nMIIDjjCCAnagAwIBAgIBATANBgkqhkiG9w0BAQUFADBGMRIwEAYDVQQDDAlyc3Bl\nYy1kZXYxGzAZBgoJkiaJk/IsZAEZFgtnb29nbGVnb3VwczETMBEGCgmSJomT8ixk\nARkWA2NvbTAeFw0xMzExMDcxOTQyNTlaFw0xNDExMDcxOTQyNTlaMEYxEjAQBgNV\nBAMMCXJzcGVjLWRldjEbMBkGCgmSJomT8ixkARkWC2dvb2dsZWdvdXBzMRMwEQYK\nCZImiZPyLGQBGRYDY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\nnhCeZouDLXWO55no+EdZNCtjXjfJQ1X9TbPcvBDD29OypIUce2h/VdKXB2gI7ZHs\nF5NkPggslTErGFmWAtIiur7u943RVqHOsyoIsy065F9fCtrykkA+22elvTDha4Iz\nRUCvuhQ3klatYk4jF+cGt1jNONNVdLOiy0bMynvcM7hoVQ2AomwGs+cEOWQ/4dkD\nJcNV3qfzF5QBcTD2372XNM53b25nYVQSX2KH5FF7BhlKyov33bOm2gA9M+mWIujW\nqgkyxVlfrlE+ZBgV3wXn1Cojg1LpTq35yOArgwioyrwwlZZJR9joN9s/nDklfr5A\n+dyETjFc6cmEPWZrt2cJBQIDAQABo4GGMIGDMAkGA1UdEwQCMAAwCwYDVR0PBAQD\nAgSwMB0GA1UdDgQWBBSW+WD7hn1swJ1A7i8tbuFeuNCJCjAkBgNVHREEHTAbgRly\nc3BlYy1kZXZAZ29vZ2xlZ291cHMuY29tMCQGA1UdEgQdMBuBGXJzcGVjLWRldkBn\nb29nbGVnb3Vwcy5jb20wDQYJKoZIhvcNAQEFBQADggEBAH27jAZ8sD7vnXupj6Y+\nBaBdfHtCkFaslLJ0aKuMDIVXwYuKfqoW15cZPDLmSIEBuQFM3lw6d/hEEL4Uo2jZ\nFvtmH5OxifPDzFyUtCL4yp6qgNe/Xf6sDsRg6FmKcpgqCwNOmsViaf0LPSUH/GYQ\n3Teoz8QCaDbD7AKsffT7eDrnbHnKweO1XdemRJC98u/yYxnGzMSWKEsn09etBlZ9\n7H67k5Z3uf6cfLZgToWL6zShzZY3Nun5r73YsNf2/QZOe4UZe4vfGvn6baw53ys9\n1yHC1AcSYpvi2dAbOiHT5iQF+krm4wse8KctXgTNnjMsHEoGKulJS2/sZl90jcCz\nmuA=\n-----END CERTIFICATE-----\n"] - s.date = "2014-07-21" - s.description = "RSpec's 'test double' framework, with support for stubbing and mocking" - s.email = "rspec@googlegroups.com" - s.homepage = "http://github.com/rspec/rspec-mocks" - s.licenses = ["MIT"] - s.rdoc_options = ["--charset=UTF-8"] - s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") - s.rubyforge_project = "rspec" - s.rubygems_version = "2.4.1" - s.summary = "rspec-mocks-3.0.3" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, ["~> 3.0.0"]) - s.add_development_dependency(%q, ["~> 10.0.0"]) - s.add_development_dependency(%q, ["~> 1.3.15"]) - s.add_development_dependency(%q, ["~> 0.5"]) - s.add_development_dependency(%q, ["~> 5.2"]) - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, ["~> 1.3.15"]) - s.add_dependency(%q, ["~> 0.5"]) - s.add_dependency(%q, ["~> 5.2"]) - end - else - s.add_dependency(%q, ["~> 3.0.0"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, ["~> 1.3.15"]) - s.add_dependency(%q, ["~> 0.5"]) - s.add_dependency(%q, ["~> 5.2"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/rspec-support-3.0.3.gemspec b/vendor/bundle/ruby/2.0.0/specifications/rspec-support-3.0.3.gemspec deleted file mode 100644 index 8b38db0..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/rspec-support-3.0.3.gemspec +++ /dev/null @@ -1,42 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: rspec-support 3.0.3 ruby lib - -Gem::Specification.new do |s| - s.name = "rspec-support" - s.version = "3.0.3" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["David Chelimsky", "Myron Marson", "Jon Rowe", "Sam Phippen", "Xaviery Shay", "Bradley Schaefer"] - s.cert_chain = ["-----BEGIN CERTIFICATE-----\nMIIDjjCCAnagAwIBAgIBATANBgkqhkiG9w0BAQUFADBGMRIwEAYDVQQDDAlyc3Bl\nYy1kZXYxGzAZBgoJkiaJk/IsZAEZFgtnb29nbGVnb3VwczETMBEGCgmSJomT8ixk\nARkWA2NvbTAeFw0xMzExMDcxOTQyNTlaFw0xNDExMDcxOTQyNTlaMEYxEjAQBgNV\nBAMMCXJzcGVjLWRldjEbMBkGCgmSJomT8ixkARkWC2dvb2dsZWdvdXBzMRMwEQYK\nCZImiZPyLGQBGRYDY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\nnhCeZouDLXWO55no+EdZNCtjXjfJQ1X9TbPcvBDD29OypIUce2h/VdKXB2gI7ZHs\nF5NkPggslTErGFmWAtIiur7u943RVqHOsyoIsy065F9fCtrykkA+22elvTDha4Iz\nRUCvuhQ3klatYk4jF+cGt1jNONNVdLOiy0bMynvcM7hoVQ2AomwGs+cEOWQ/4dkD\nJcNV3qfzF5QBcTD2372XNM53b25nYVQSX2KH5FF7BhlKyov33bOm2gA9M+mWIujW\nqgkyxVlfrlE+ZBgV3wXn1Cojg1LpTq35yOArgwioyrwwlZZJR9joN9s/nDklfr5A\n+dyETjFc6cmEPWZrt2cJBQIDAQABo4GGMIGDMAkGA1UdEwQCMAAwCwYDVR0PBAQD\nAgSwMB0GA1UdDgQWBBSW+WD7hn1swJ1A7i8tbuFeuNCJCjAkBgNVHREEHTAbgRly\nc3BlYy1kZXZAZ29vZ2xlZ291cHMuY29tMCQGA1UdEgQdMBuBGXJzcGVjLWRldkBn\nb29nbGVnb3Vwcy5jb20wDQYJKoZIhvcNAQEFBQADggEBAH27jAZ8sD7vnXupj6Y+\nBaBdfHtCkFaslLJ0aKuMDIVXwYuKfqoW15cZPDLmSIEBuQFM3lw6d/hEEL4Uo2jZ\nFvtmH5OxifPDzFyUtCL4yp6qgNe/Xf6sDsRg6FmKcpgqCwNOmsViaf0LPSUH/GYQ\n3Teoz8QCaDbD7AKsffT7eDrnbHnKweO1XdemRJC98u/yYxnGzMSWKEsn09etBlZ9\n7H67k5Z3uf6cfLZgToWL6zShzZY3Nun5r73YsNf2/QZOe4UZe4vfGvn6baw53ys9\n1yHC1AcSYpvi2dAbOiHT5iQF+krm4wse8KctXgTNnjMsHEoGKulJS2/sZl90jcCz\nmuA=\n-----END CERTIFICATE-----\n"] - s.date = "2014-07-21" - s.description = "Support utilities for RSpec gems" - s.email = "rspec-users@rubyforge.org" - s.homepage = "https://github.com/rspec/rspec-support" - s.licenses = ["MIT"] - s.rdoc_options = ["--charset=UTF-8"] - s.required_ruby_version = Gem::Requirement.new(">= 1.8.7") - s.rubyforge_project = "rspec" - s.rubygems_version = "2.4.1" - s.summary = "rspec-support-3.0.3" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q, ["~> 1.3"]) - s.add_development_dependency(%q, ["~> 10.0.0"]) - s.add_development_dependency(%q, [">= 3.0.0.pre"]) - else - s.add_dependency(%q, ["~> 1.3"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, [">= 3.0.0.pre"]) - end - else - s.add_dependency(%q, ["~> 1.3"]) - s.add_dependency(%q, ["~> 10.0.0"]) - s.add_dependency(%q, [">= 3.0.0.pre"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/sinatra-1.4.5.gemspec b/vendor/bundle/ruby/2.0.0/specifications/sinatra-1.4.5.gemspec deleted file mode 100644 index b261165..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/sinatra-1.4.5.gemspec +++ /dev/null @@ -1,41 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: sinatra 1.4.5 ruby lib - -Gem::Specification.new do |s| - s.name = "sinatra" - s.version = "1.4.5" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Blake Mizerany", "Ryan Tomayko", "Simon Rozet", "Konstantin Haase"] - s.date = "2014-04-08" - s.description = "Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort." - s.email = "sinatrarb@googlegroups.com" - s.extra_rdoc_files = ["README.de.md", "README.es.md", "README.fr.md", "README.hu.md", "README.ja.md", "README.ko.md", "README.md", "README.pt-br.md", "README.pt-pt.md", "README.ru.md", "README.zh.md", "LICENSE"] - s.files = ["LICENSE", "README.de.md", "README.es.md", "README.fr.md", "README.hu.md", "README.ja.md", "README.ko.md", "README.md", "README.pt-br.md", "README.pt-pt.md", "README.ru.md", "README.zh.md"] - s.homepage = "http://www.sinatrarb.com/" - s.licenses = ["MIT"] - s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Sinatra", "--main", "README.rdoc", "--encoding=UTF-8"] - s.rubygems_version = "2.4.1" - s.summary = "Classy web-development dressed in a DSL" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, ["~> 1.4"]) - s.add_runtime_dependency(%q, [">= 1.3.4", "~> 1.3"]) - s.add_runtime_dependency(%q, ["~> 1.4"]) - else - s.add_dependency(%q, ["~> 1.4"]) - s.add_dependency(%q, [">= 1.3.4", "~> 1.3"]) - s.add_dependency(%q, ["~> 1.4"]) - end - else - s.add_dependency(%q, ["~> 1.4"]) - s.add_dependency(%q, [">= 1.3.4", "~> 1.3"]) - s.add_dependency(%q, ["~> 1.4"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/thor-0.19.1.gemspec b/vendor/bundle/ruby/2.0.0/specifications/thor-0.19.1.gemspec deleted file mode 100644 index c277dbf..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/thor-0.19.1.gemspec +++ /dev/null @@ -1,34 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: thor 0.19.1 ruby lib - -Gem::Specification.new do |s| - s.name = "thor" - s.version = "0.19.1" - - s.required_rubygems_version = Gem::Requirement.new(">= 1.3.5") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Yehuda Katz", "Jos\u{e9} Valim"] - s.date = "2014-03-24" - s.description = "Thor is a toolkit for building powerful command-line interfaces." - s.email = "ruby-thor@googlegroups.com" - s.executables = ["thor"] - s.files = ["bin/thor"] - s.homepage = "http://whatisthor.com/" - s.licenses = ["MIT"] - s.rubygems_version = "2.4.1" - s.summary = "Thor is a toolkit for building powerful command-line interfaces." - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q, ["~> 1.0"]) - else - s.add_dependency(%q, ["~> 1.0"]) - end - else - s.add_dependency(%q, ["~> 1.0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/tilt-1.4.1.gemspec b/vendor/bundle/ruby/2.0.0/specifications/tilt-1.4.1.gemspec deleted file mode 100644 index 3269c11..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/tilt-1.4.1.gemspec +++ /dev/null @@ -1,101 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: tilt 1.4.1 ruby lib - -Gem::Specification.new do |s| - s.name = "tilt" - s.version = "1.4.1" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Ryan Tomayko"] - s.date = "2013-05-08" - s.description = "Generic interface to multiple Ruby template engines" - s.email = "r@tomayko.com" - s.executables = ["tilt"] - s.files = ["bin/tilt"] - s.homepage = "http://github.com/rtomayko/tilt/" - s.licenses = ["MIT"] - s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Tilt", "--main", "Tilt"] - s.rubygems_version = "2.4.1" - s.summary = "Generic interface to multiple Ruby template engines" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 2 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q, [">= 0.1.0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 2.2.11"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - s.add_development_dependency(%q, [">= 0"]) - else - s.add_dependency(%q, [">= 0.1.0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 2.2.11"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - end - else - s.add_dependency(%q, [">= 0.1.0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 2.2.11"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, [">= 0"]) - end -end diff --git a/vendor/bundle/ruby/2.0.0/specifications/unicorn-4.8.3.gemspec b/vendor/bundle/ruby/2.0.0/specifications/unicorn-4.8.3.gemspec deleted file mode 100644 index 42dca04..0000000 --- a/vendor/bundle/ruby/2.0.0/specifications/unicorn-4.8.3.gemspec +++ /dev/null @@ -1,51 +0,0 @@ -# -*- encoding: utf-8 -*- -# stub: unicorn 4.8.3 ruby lib -# stub: ext/unicorn_http/extconf.rb - -Gem::Specification.new do |s| - s.name = "unicorn" - s.version = "4.8.3" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib"] - s.authors = ["Unicorn hackers"] - s.date = "2014-05-07" - s.description = "\\Unicorn is an HTTP server for Rack applications designed to only serve\nfast clients on low-latency, high-bandwidth connections and take\nadvantage of features in Unix/Unix-like kernels. Slow clients should\nonly be served by placing a reverse proxy capable of fully buffering\nboth the the request and response in between \\Unicorn and slow clients." - s.email = "unicorn-public@bogomips.org" - s.executables = ["unicorn", "unicorn_rails"] - s.extensions = ["ext/unicorn_http/extconf.rb"] - s.extra_rdoc_files = ["FAQ", "README", "TUNING", "PHILOSOPHY", "HACKING", "DESIGN", "CONTRIBUTORS", "LICENSE", "SIGNALS", "KNOWN_ISSUES", "TODO", "NEWS", "ChangeLog", "LATEST", "lib/unicorn.rb", "lib/unicorn/configurator.rb", "lib/unicorn/http_server.rb", "lib/unicorn/preread_input.rb", "lib/unicorn/stream_input.rb", "lib/unicorn/tee_input.rb", "lib/unicorn/util.rb", "lib/unicorn/oob_gc.rb", "lib/unicorn/worker.rb", "ISSUES", "Sandbox", "Links", "Application_Timeouts"] - s.files = ["Application_Timeouts", "CONTRIBUTORS", "ChangeLog", "DESIGN", "FAQ", "HACKING", "ISSUES", "KNOWN_ISSUES", "LATEST", "LICENSE", "Links", "NEWS", "PHILOSOPHY", "README", "SIGNALS", "Sandbox", "TODO", "TUNING", "bin/unicorn", "bin/unicorn_rails", "ext/unicorn_http/extconf.rb", "lib/unicorn.rb", "lib/unicorn/configurator.rb", "lib/unicorn/http_server.rb", "lib/unicorn/oob_gc.rb", "lib/unicorn/preread_input.rb", "lib/unicorn/stream_input.rb", "lib/unicorn/tee_input.rb", "lib/unicorn/util.rb", "lib/unicorn/worker.rb"] - s.homepage = "http://unicorn.bogomips.org/" - s.licenses = ["GPLv2+", "Ruby 1.8"] - s.rdoc_options = ["-t", "Unicorn: Rack HTTP server for fast clients and Unix", "-W", "http://bogomips.org/unicorn.git/tree/%s"] - s.rubyforge_project = "mongrel" - s.rubygems_version = "2.4.1" - s.summary = "Rack HTTP server for fast clients and Unix" - - s.installed_by_version = "2.4.1" if s.respond_to? :installed_by_version - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q, [">= 0"]) - s.add_runtime_dependency(%q, ["~> 2.6"]) - s.add_runtime_dependency(%q, ["~> 0.7"]) - s.add_development_dependency(%q, ["~> 3.2"]) - s.add_development_dependency(%q, ["~> 1.8"]) - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["~> 2.6"]) - s.add_dependency(%q, ["~> 0.7"]) - s.add_dependency(%q, ["~> 3.2"]) - s.add_dependency(%q, ["~> 1.8"]) - end - else - s.add_dependency(%q, [">= 0"]) - s.add_dependency(%q, ["~> 2.6"]) - s.add_dependency(%q, ["~> 0.7"]) - s.add_dependency(%q, ["~> 3.2"]) - s.add_dependency(%q, ["~> 1.8"]) - end -end