CombinedText stringlengths 4 3.42M |
|---|
#
# Author:: Steven Danna (<steve@opscode.com>)
# Copyright:: Copyright (c) 2011 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper"))
describe Chef::Knife::CookbookSiteInstall do
before(:each) do
require 'chef/knife/core/cookbook_scm_repo'
@knife = Chef::Knife::CookbookSiteInstall.new
@knife.config = {}
@install_path = "/var/tmp/chef"
@knife.config[:cookbook_path] = [ @install_path ]
@stdout = StringIO.new
@stderr = StringIO.new
@knife.stub!(:stderr).and_return(@stdout)
@knife.stub!(:stdout).and_return(@stdout)
#Assume all external commands would have succeed. :(
@knife.stub!(:shell_out!).and_return(true)
#CookbookSiteDownload Stup
@downloader = {}
@knife.stub!(:download_cookbook_to).and_return(@downloader)
@downloader.stub!(:version).and_return do
if @knife.name_args.size == 2
@knife.name_args[1]
else
"0.3.0"
end
end
#Stubs for CookbookSCMRepo
@repo = {}
Chef::Knife::CookbookSCMRepo.stub!(:new).and_return(@repo)
@repo.stub!(:sanity_check).and_return(true)
@repo.stub!(:reset_to_default_state).and_return(true)
@repo.stub!(:prepare_to_import).and_return(true)
@repo.stub!(:finalize_updates_to).and_return(true)
@repo.stub!(:merge_updates_from).and_return(true)
end
describe "run" do
it "should return an error if a cookbook name is not provided" do
@knife.name_args = []
@knife.ui.should_receive(:error).with("Please specify a cookbook to download and install.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should return an error if more than two arguments are given" do
@knife.name_args = ["foo", "bar", "baz"]
@knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should return an error if the second argument is not a version" do
@knife.name_args = ["getting-started", "1pass"]
@knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should install the specified version if a specific version is given" do
@knife.name_args = ["getting-started", "0.1.0"]
@knife.config[:no_deps] = true
upstream_file = File.join(@install_path, "getting-started.tar.gz")
@knife.should_receive(:download_cookbook_to).with(upstream_file)
@knife.should_receive(:extract_cookbook).with(upstream_file, "0.1.0")
@knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started"))
@repo.should_receive(:merge_updates_from).with("getting-started", "0.1.0")
@knife.run
end
it "should install the latest version if only a cookbook name is given" do
@knife.name_args = ["getting-started"]
@knife.config[:no_deps] = true
upstream_file = File.join(@install_path, "getting-started.tar.gz")
@knife.should_receive(:download_cookbook_to).with(upstream_file)
@knife.should_receive(:extract_cookbook).with(upstream_file, "0.3.0")
@knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started"))
@repo.should_receive(:merge_updates_from).with("getting-started", "0.3.0")
@knife.run
end
end
end
CHEF-2512: More tests.
#
# Author:: Steven Danna (<steve@opscode.com>)
# Copyright:: Copyright (c) 2011 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper"))
describe Chef::Knife::CookbookSiteInstall do
before(:each) do
require 'chef/knife/core/cookbook_scm_repo'
@knife = Chef::Knife::CookbookSiteInstall.new
@knife.config = {}
@install_path = "/var/tmp/chef"
@knife.config[:cookbook_path] = [ @install_path ]
@stdout = StringIO.new
@stderr = StringIO.new
@knife.stub!(:stderr).and_return(@stdout)
@knife.stub!(:stdout).and_return(@stdout)
#Assume all external commands would have succeed. :(
@knife.stub!(:shell_out!).and_return(true)
#CookbookSiteDownload Stup
@downloader = {}
@knife.stub!(:download_cookbook_to).and_return(@downloader)
@downloader.stub!(:version).and_return do
if @knife.name_args.size == 2
@knife.name_args[1]
else
"0.3.0"
end
end
#Stubs for CookbookSCMRepo
@repo = {}
Chef::Knife::CookbookSCMRepo.stub!(:new).and_return(@repo)
@repo.stub!(:sanity_check).and_return(true)
@repo.stub!(:reset_to_default_state).and_return(true)
@repo.stub!(:prepare_to_import).and_return(true)
@repo.stub!(:finalize_updates_to).and_return(true)
@repo.stub!(:merge_updates_from).and_return(true)
end
describe "run" do
it "should return an error if a cookbook name is not provided" do
@knife.name_args = []
@knife.ui.should_receive(:error).with("Please specify a cookbook to download and install.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should return an error if more than two arguments are given" do
@knife.name_args = ["foo", "bar", "baz"]
@knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should return an error if the second argument is not a version" do
@knife.name_args = ["getting-started", "1pass"]
@knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should return an error if the second argument is a four-digit version" do
@knife.name_args = ["getting-started", "0.0.0.1"]
@knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should return an error if the second argument is a one-digit version" do
@knife.name_args = ["getting-started", "1"]
@knife.ui.should_receive(:error).with("Installing multiple cookbooks at once is not supported.")
lambda { @knife.run }.should raise_error(SystemExit)
end
it "should install the specified version if second argument is a three-digit version" do
@knife.name_args = ["getting-started", "0.1.0"]
@knife.config[:no_deps] = true
upstream_file = File.join(@install_path, "getting-started.tar.gz")
@knife.should_receive(:download_cookbook_to).with(upstream_file)
@knife.should_receive(:extract_cookbook).with(upstream_file, "0.1.0")
@knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started"))
@repo.should_receive(:merge_updates_from).with("getting-started", "0.1.0")
@knife.run
end
it "should install the specified version if second argument is a two-digit version" do
@knife.name_args = ["getting-started", "0.1"]
@knife.config[:no_deps] = true
upstream_file = File.join(@install_path, "getting-started.tar.gz")
@knife.should_receive(:download_cookbook_to).with(upstream_file)
@knife.should_receive(:extract_cookbook).with(upstream_file, "0.1")
@knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started"))
@repo.should_receive(:merge_updates_from).with("getting-started", "0.1")
@knife.run
end
it "should install the latest version if only a cookbook name is given" do
@knife.name_args = ["getting-started"]
@knife.config[:no_deps] = true
upstream_file = File.join(@install_path, "getting-started.tar.gz")
@knife.should_receive(:download_cookbook_to).with(upstream_file)
@knife.should_receive(:extract_cookbook).with(upstream_file, "0.3.0")
@knife.should_receive(:clear_existing_files).with(File.join(@install_path, "getting-started"))
@repo.should_receive(:merge_updates_from).with("getting-started", "0.3.0")
@knife.run
end
end
end
|
# -*- encoding: utf-8 -*-
VERSION = "1.1.0"
Gem::Specification.new do |spec|
spec.name = "motion-giphy"
spec.version = VERSION
spec.authors = ["Will Raxworthy"]
spec.email = ["git@willrax.com"]
spec.description = %q{Giphy API wrapper for RubyMotion}
spec.summary = %q{Giphy API wrapper for RubyMotion}
spec.homepage = ""
spec.license = ""
files = []
files << "README.md"
files.concat(Dir.glob("lib/**/*.rb"))
spec.files = files
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_dependency "bubble-wrap"
spec.add_development_dependency "rake"
end
Bump version
# -*- encoding: utf-8 -*-
VERSION = "1.2.0"
Gem::Specification.new do |spec|
spec.name = "motion-giphy"
spec.version = VERSION
spec.authors = ["Will Raxworthy"]
spec.email = ["git@willrax.com"]
spec.description = %q{Giphy API wrapper for RubyMotion}
spec.summary = %q{Giphy API wrapper for RubyMotion}
spec.homepage = ""
spec.license = ""
files = []
files << "README.md"
files.concat(Dir.glob("lib/**/*.rb"))
spec.files = files
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_dependency "bubble-wrap"
spec.add_development_dependency "rake"
end
|
require "formula"
class Vtk5 < Formula
homepage "http://www.vtk.org"
url "http://www.vtk.org/files/release/5.10/vtk-5.10.1.tar.gz" # update libdir below, too!
sha1 "deb834f46b3f7fc3e122ddff45e2354d69d2adc3"
head "git://vtk.org/VTK.git", :branch => "release-5.10"
revision 1
bottle do
root_url "https://downloads.sf.net/project/machomebrew/Bottles/science"
sha1 "ddebd8c0d9dc9315f36762b4179d7c4264460b0f" => :yosemite
sha1 "365ec2a27a039bc01a7b9ffcb3ff08a2d65d169f" => :mavericks
sha1 "78c4a464bf75f62b4b162a015562646aa9f572be" => :mountain_lion
end
deprecated_option "examples" => "with-examples"
deprecated_option "qt-extern" => "with-qt-extern"
deprecated_option "tcl" => "with-tcl"
deprecated_option "remove-legacy" => "without-legacy"
option :cxx11
option "with-examples", "Compile and install various examples"
option "with-qt-extern", "Enable Qt4 extension via non-Homebrew external Qt4"
option "with-tcl", "Enable Tcl wrapping of VTK classes"
option "without-legacy", "Disable legacy APIs"
depends_on "cmake" => :build
depends_on :x11 => :optional
depends_on "qt" => :optional
depends_on :python => :recommended
# If --with-qt and --with-python, then we automatically use PyQt, too!
if build.with? "qt" and build.with? "python"
depends_on "sip"
depends_on "pyqt"
end
depends_on "boost" => :recommended
depends_on "hdf5" => :recommended
depends_on "jpeg" => :recommended
depends_on "libpng" => :recommended
depends_on "libtiff" => :recommended
keg_only "Different versions of the same library"
# Fix bug in Wrapping/Python/setup_install_paths.py: http://vtk.org/Bug/view.php?id=13699
# and compilation on mavericks backported from head.
patch :DATA
stable do
patch do
# apply upstream patches for C++11 mode
url "https://gist.github.com/sxprophet/7463815/raw/165337ae10d5665bc18f0bad645eff098f939893/vtk5-cxx11-patch.diff"
sha1 "5511c8a48327824443f321894e3ea3ac289bf40e"
end
end
def install
libdir = if build.head? then lib; else "#{lib}/vtk-5.10"; end
args = std_cmake_args + %W[
-DVTK_REQUIRED_OBJCXX_FLAGS=''
-DVTK_USE_CARBON=OFF
-DVTK_USE_TK=OFF
-DBUILD_TESTING=OFF
-DBUILD_SHARED_LIBS=ON
-DIOKit:FILEPATH=#{MacOS.sdk_path}/System/Library/Frameworks/IOKit.framework
-DCMAKE_INSTALL_RPATH:STRING=#{libdir}
-DCMAKE_INSTALL_NAME_DIR:STRING=#{libdir}
-DVTK_USE_SYSTEM_EXPAT=ON
-DVTK_USE_SYSTEM_LIBXML2=ON
-DVTK_USE_SYSTEM_ZLIB=ON
]
args << "-DBUILD_EXAMPLES=" + ((build.with? "examples") ? "ON" : "OFF")
if build.with? "qt" or build.with? "qt-extern"
args << "-DVTK_USE_GUISUPPORT=ON"
args << "-DVTK_USE_QT=ON"
args << "-DVTK_USE_QVTK=ON"
end
args << "-DVTK_WRAP_TCL=ON" if build.with? "tcl"
# Cocoa for everything except x11
if build.with? "x11"
args << "-DVTK_USE_COCOA=OFF"
args << "-DVTK_USE_X=ON"
else
args << "-DVTK_USE_COCOA=ON"
end
unless MacOS::CLT.installed?
# We are facing an Xcode-only installation, and we have to keep
# vtk from using its internal Tk headers (that differ from OSX's).
args << "-DTK_INCLUDE_PATH:PATH=#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Headers"
args << "-DTK_INTERNAL_PATH:PATH=#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Headers/tk-private"
end
args << "-DVTK_USE_BOOST=ON" if build.with? "boost"
args << "-DVTK_USE_SYSTEM_HDF5=ON" if build.with? "hdf5"
args << "-DVTK_USE_SYSTEM_JPEG=ON" if build.with? "jpeg"
args << "-DVTK_USE_SYSTEM_PNG=ON" if build.with? "libpng"
args << "-DVTK_USE_SYSTEM_TIFF=ON" if build.with? "libtiff"
args << "-DVTK_LEGACY_REMOVE=ON" if build.without? "legacy"
ENV.cxx11 if build.cxx11?
mkdir "build" do
if build.with? "python"
args << "-DVTK_WRAP_PYTHON=ON"
# CMake picks up the system's python dylib, even if we have a brewed one.
args << "-DPYTHON_LIBRARY='#{%x(python-config --prefix).chomp}/lib/libpython2.7.dylib'"
# Set the prefix for the python bindings to the Cellar
args << "-DVTK_PYTHON_SETUP_ARGS:STRING='--prefix=#{prefix} --single-version-externally-managed --record=installed.txt'"
if build.with? "pyqt"
args << "-DVTK_WRAP_PYTHON_SIP=ON"
args << "-DSIP_PYQT_DIR="#{HOMEBREW_PREFIX}/share/sip""
end
end
args << ".."
system "cmake", *args
system "make"
system "make", "install"
end
(share+"vtk").install "Examples" if build.with? "examples"
end
def caveats
s = ""
s += <<-EOS.undent
Even without the --with-qt option, you can display native VTK render windows
from python. Alternatively, you can integrate the RenderWindowInteractor
in PyQt, PySide, Tk or Wx at runtime. Read more:
import vtk.qt4; help(vtk.qt4) or import vtk.wx; help(vtk.wx)
VTK5 is keg only in favor of VTK6. Add
#{opt_prefix}/lib/python2.7/site-packages
to your PYTHONPATH before using the python bindings.
EOS
if build.with? "examples"
s += <<-EOS.undent
The scripting examples are stored in #{HOMEBREW_PREFIX}/share/vtk
EOS
end
return s.empty? ? nil : s
end
end
__END__
diff --git a/Wrapping/Python/setup_install_paths.py b/Wrapping/Python/setup_install_paths.py
index 00f48c8..014b906 100755
--- a/Wrapping/Python/setup_install_paths.py
+++ b/Wrapping/Python/setup_install_paths.py
@@ -35,7 +35,7 @@ def get_install_path(command, *args):
option, value = string.split(arg,"=")
options[option] = value
except ValueError:
- options[option] = 1
+ options[arg] = 1
# check for the prefix and exec_prefix
try:
vtk5: add --qt --python deprecated_options
require "formula"
class Vtk5 < Formula
homepage "http://www.vtk.org"
url "http://www.vtk.org/files/release/5.10/vtk-5.10.1.tar.gz" # update libdir below, too!
sha1 "deb834f46b3f7fc3e122ddff45e2354d69d2adc3"
head "git://vtk.org/VTK.git", :branch => "release-5.10"
revision 1
bottle do
root_url "https://downloads.sf.net/project/machomebrew/Bottles/science"
sha1 "ddebd8c0d9dc9315f36762b4179d7c4264460b0f" => :yosemite
sha1 "365ec2a27a039bc01a7b9ffcb3ff08a2d65d169f" => :mavericks
sha1 "78c4a464bf75f62b4b162a015562646aa9f572be" => :mountain_lion
end
deprecated_option "examples" => "with-examples"
deprecated_option "qt-extern" => "with-qt-extern"
deprecated_option "qt" => "with-qt"
deprecated_option "python" => "with-python"
deprecated_option "tcl" => "with-tcl"
deprecated_option "remove-legacy" => "without-legacy"
option :cxx11
option "with-examples", "Compile and install various examples"
option "with-qt-extern", "Enable Qt4 extension via non-Homebrew external Qt4"
option "with-tcl", "Enable Tcl wrapping of VTK classes"
option "without-legacy", "Disable legacy APIs"
depends_on "cmake" => :build
depends_on :x11 => :optional
depends_on "qt" => :optional
depends_on :python => :recommended
# If --with-qt and --with-python, then we automatically use PyQt, too!
if build.with? "qt" and build.with? "python"
depends_on "sip"
depends_on "pyqt"
end
depends_on "boost" => :recommended
depends_on "hdf5" => :recommended
depends_on "jpeg" => :recommended
depends_on "libpng" => :recommended
depends_on "libtiff" => :recommended
keg_only "Different versions of the same library"
# Fix bug in Wrapping/Python/setup_install_paths.py: http://vtk.org/Bug/view.php?id=13699
# and compilation on mavericks backported from head.
patch :DATA
stable do
patch do
# apply upstream patches for C++11 mode
url "https://gist.github.com/sxprophet/7463815/raw/165337ae10d5665bc18f0bad645eff098f939893/vtk5-cxx11-patch.diff"
sha1 "5511c8a48327824443f321894e3ea3ac289bf40e"
end
end
def install
libdir = if build.head? then lib; else "#{lib}/vtk-5.10"; end
args = std_cmake_args + %W[
-DVTK_REQUIRED_OBJCXX_FLAGS=''
-DVTK_USE_CARBON=OFF
-DVTK_USE_TK=OFF
-DBUILD_TESTING=OFF
-DBUILD_SHARED_LIBS=ON
-DIOKit:FILEPATH=#{MacOS.sdk_path}/System/Library/Frameworks/IOKit.framework
-DCMAKE_INSTALL_RPATH:STRING=#{libdir}
-DCMAKE_INSTALL_NAME_DIR:STRING=#{libdir}
-DVTK_USE_SYSTEM_EXPAT=ON
-DVTK_USE_SYSTEM_LIBXML2=ON
-DVTK_USE_SYSTEM_ZLIB=ON
]
args << "-DBUILD_EXAMPLES=" + ((build.with? "examples") ? "ON" : "OFF")
if build.with? "qt" or build.with? "qt-extern"
args << "-DVTK_USE_GUISUPPORT=ON"
args << "-DVTK_USE_QT=ON"
args << "-DVTK_USE_QVTK=ON"
end
args << "-DVTK_WRAP_TCL=ON" if build.with? "tcl"
# Cocoa for everything except x11
if build.with? "x11"
args << "-DVTK_USE_COCOA=OFF"
args << "-DVTK_USE_X=ON"
else
args << "-DVTK_USE_COCOA=ON"
end
unless MacOS::CLT.installed?
# We are facing an Xcode-only installation, and we have to keep
# vtk from using its internal Tk headers (that differ from OSX's).
args << "-DTK_INCLUDE_PATH:PATH=#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Headers"
args << "-DTK_INTERNAL_PATH:PATH=#{MacOS.sdk_path}/System/Library/Frameworks/Tk.framework/Headers/tk-private"
end
args << "-DVTK_USE_BOOST=ON" if build.with? "boost"
args << "-DVTK_USE_SYSTEM_HDF5=ON" if build.with? "hdf5"
args << "-DVTK_USE_SYSTEM_JPEG=ON" if build.with? "jpeg"
args << "-DVTK_USE_SYSTEM_PNG=ON" if build.with? "libpng"
args << "-DVTK_USE_SYSTEM_TIFF=ON" if build.with? "libtiff"
args << "-DVTK_LEGACY_REMOVE=ON" if build.without? "legacy"
ENV.cxx11 if build.cxx11?
mkdir "build" do
if build.with? "python"
args << "-DVTK_WRAP_PYTHON=ON"
# CMake picks up the system's python dylib, even if we have a brewed one.
args << "-DPYTHON_LIBRARY='#{%x(python-config --prefix).chomp}/lib/libpython2.7.dylib'"
# Set the prefix for the python bindings to the Cellar
args << "-DVTK_PYTHON_SETUP_ARGS:STRING='--prefix=#{prefix} --single-version-externally-managed --record=installed.txt'"
if build.with? "pyqt"
args << "-DVTK_WRAP_PYTHON_SIP=ON"
args << "-DSIP_PYQT_DIR="#{HOMEBREW_PREFIX}/share/sip""
end
end
args << ".."
system "cmake", *args
system "make"
system "make", "install"
end
(share+"vtk").install "Examples" if build.with? "examples"
end
def caveats
s = ""
s += <<-EOS.undent
Even without the --with-qt option, you can display native VTK render windows
from python. Alternatively, you can integrate the RenderWindowInteractor
in PyQt, PySide, Tk or Wx at runtime. Read more:
import vtk.qt4; help(vtk.qt4) or import vtk.wx; help(vtk.wx)
VTK5 is keg only in favor of VTK6. Add
#{opt_prefix}/lib/python2.7/site-packages
to your PYTHONPATH before using the python bindings.
EOS
if build.with? "examples"
s += <<-EOS.undent
The scripting examples are stored in #{HOMEBREW_PREFIX}/share/vtk
EOS
end
return s.empty? ? nil : s
end
end
__END__
diff --git a/Wrapping/Python/setup_install_paths.py b/Wrapping/Python/setup_install_paths.py
index 00f48c8..014b906 100755
--- a/Wrapping/Python/setup_install_paths.py
+++ b/Wrapping/Python/setup_install_paths.py
@@ -35,7 +35,7 @@ def get_install_path(command, *args):
option, value = string.split(arg,"=")
options[option] = value
except ValueError:
- options[option] = 1
+ options[arg] = 1
# check for the prefix and exec_prefix
try:
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'steam_club_api/version'
Gem::Specification.new do |spec|
spec.name = "steam_club_api"
spec.version = SteamClubAPI::VERSION
spec.authors = ["andrerpbts", "rodrigovirgilio"]
spec.email = ["andrerpbts@gmail.com", "virgilio@virgilio.eti.br"]
spec.summary = %q{Handles the interactions with Steam}
spec.description = %q{Handles the interactions with Steam}
spec.homepage = ""
spec.license = ""
spec.files = `git ls-files -z`.split("\x0")
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.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "factory_girl", "~> 4.0"
spec.add_development_dependency "codeclimate-test-reporter"
spec.add_development_dependency "webmock", "~> 1.18.0"
spec.add_development_dependency "pry"
spec.add_dependency "activesupport"
spec.add_dependency "virtus"
spec.add_dependency "httparty"
end
Add Rspec-virtus matchers
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'steam_club_api/version'
Gem::Specification.new do |spec|
spec.name = "steam_club_api"
spec.version = SteamClubAPI::VERSION
spec.authors = ["andrerpbts", "rodrigovirgilio"]
spec.email = ["andrerpbts@gmail.com", "virgilio@virgilio.eti.br"]
spec.summary = %q{Handles the interactions with Steam}
spec.description = %q{Handles the interactions with Steam}
spec.homepage = ""
spec.license = ""
spec.files = `git ls-files -z`.split("\x0")
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.6"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "factory_girl", "~> 4.0"
spec.add_development_dependency "codeclimate-test-reporter"
spec.add_development_dependency "webmock", "~> 1.18.0"
spec.add_development_dependency "pry"
spec.add_development_dependency "rspec-virtus"
spec.add_dependency "activesupport"
spec.add_dependency "virtus"
spec.add_dependency "httparty"
end
|
Patch the GWT addon to ensure it supports version 2.8.2-v20191108.
require 'buildr/gwt'
module Buildr
module GWT
class << self
# The specs for requirements
def dependencies(version = nil)
validation_deps =
%w(javax.validation:validation-api:jar:1.0.0.GA javax.validation:validation-api:jar:sources:1.0.0.GA)
v = version || self.version
gwt_dev_jar = "com.google.gwt:gwt-dev:jar:#{v}"
if v <= '2.6.1'
[gwt_dev_jar] + validation_deps
elsif v == '2.7.0'
[
gwt_dev_jar,
'org.ow2.asm:asm:jar:5.0.3'
] + validation_deps
elsif v == '2.8.0'
%w(
com.google.jsinterop:jsinterop-annotations:jar:1.0.1
com.google.jsinterop:jsinterop-annotations:jar:sources:1.0.1
org.w3c.css:sac:jar:1.3
com.google.gwt:gwt-dev:jar:2.8.0
com.google.gwt:gwt-user:jar:2.8.0
com.google.code.gson:gson:jar:2.6.2
org.ow2.asm:asm:jar:5.0.3
org.ow2.asm:asm-util:jar:5.0.3
org.ow2.asm:asm-tree:jar:5.0.3
org.ow2.asm:asm-commons:jar:5.0.3
colt:colt:jar:1.2.0
ant:ant:jar:1.6.5
commons-collections:commons-collections:jar:3.2.2
commons-io:commons-io:jar:2.4
com.ibm.icu:icu4j:jar:50.1.1
tapestry:tapestry:jar:4.0.2
javax.annotation:javax.annotation-api:jar:1.2
javax.servlet:javax.servlet-api:jar:3.1.0
org.eclipse.jetty:jetty-annotations:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-continuation:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-http:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-io:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-jndi:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-plus:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-security:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-server:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlet:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlets:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-util:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-webapp:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-xml:jar:9.2.14.v20151106
org.eclipse.jetty.toolchain:jetty-schemas:jar:3.1.M0
) + validation_deps
elsif v == '2.8.1'
%w(
com.google.jsinterop:jsinterop-annotations:jar:1.0.1
com.google.jsinterop:jsinterop-annotations:jar:sources:1.0.1
org.w3c.css:sac:jar:1.3
com.google.gwt:gwt-dev:jar:2.8.1
com.google.gwt:gwt-user:jar:2.8.1
com.google.code.gson:gson:jar:2.6.2
org.ow2.asm:asm:jar:5.0.3
org.ow2.asm:asm-util:jar:5.0.3
org.ow2.asm:asm-tree:jar:5.0.3
org.ow2.asm:asm-commons:jar:5.0.3
colt:colt:jar:1.2.0
ant:ant:jar:1.6.5
commons-collections:commons-collections:jar:3.2.2
commons-io:commons-io:jar:2.4
com.ibm.icu:icu4j:jar:50.1.1
tapestry:tapestry:jar:4.0.2
javax.annotation:javax.annotation-api:jar:1.2
javax.servlet:javax.servlet-api:jar:3.1.0
org.eclipse.jetty:jetty-annotations:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-continuation:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-http:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-io:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-jndi:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-plus:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-security:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-server:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlet:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlets:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-util:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-webapp:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-xml:jar:9.2.14.v20151106
org.eclipse.jetty.toolchain:jetty-schemas:jar:3.1.M0
) + validation_deps
elsif v == '2.8.2'
%w(
com.google.jsinterop:jsinterop-annotations:jar:1.0.2
com.google.jsinterop:jsinterop-annotations:jar:sources:1.0.2
org.w3c.css:sac:jar:1.3
com.google.gwt:gwt-dev:jar:2.8.2
com.google.gwt:gwt-user:jar:2.8.2
com.google.code.gson:gson:jar:2.6.2
org.ow2.asm:asm:jar:5.0.3
org.ow2.asm:asm-util:jar:5.0.3
org.ow2.asm:asm-tree:jar:5.0.3
org.ow2.asm:asm-commons:jar:5.0.3
colt:colt:jar:1.2.0
ant:ant:jar:1.6.5
commons-collections:commons-collections:jar:3.2.2
commons-io:commons-io:jar:2.4
com.ibm.icu:icu4j:jar:50.1.1
tapestry:tapestry:jar:4.0.2
javax.annotation:javax.annotation-api:jar:1.2
javax.servlet:javax.servlet-api:jar:3.1.0
org.eclipse.jetty:jetty-annotations:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-continuation:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-http:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-io:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-jndi:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-plus:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-security:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-server:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlet:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlets:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-util:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-webapp:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-xml:jar:9.2.14.v20151106
org.eclipse.jetty.toolchain:jetty-schemas:jar:3.1.M0
) + validation_deps
elsif v == '2.8.2-v20191108'
%w(
org.realityforge.com.google.jsinterop:jsinterop-annotations:jar:2.8.2-v20191108
org.realityforge.com.google.jsinterop:jsinterop-annotations:jar:sources:2.8.2-v20191108
org.w3c.css:sac:jar:1.3
org.realityforge.com.google.gwt:gwt-dev:jar:2.8.2-v20191108
org.realityforge.com.google.gwt:gwt-user:jar:2.8.2-v20191108
com.google.code.gson:gson:jar:2.6.2
org.ow2.asm:asm:jar:7.1
org.ow2.asm:asm-util:jar:7.1
org.ow2.asm:asm-tree:jar:7.1
org.ow2.asm:asm-commons:jar:7.1
colt:colt:jar:1.2.0
ant:ant:jar:1.6.5
commons-collections:commons-collections:jar:3.2.2
commons-io:commons-io:jar:2.4
com.ibm.icu:icu4j:jar:63.1
tapestry:tapestry:jar:4.0.2
javax.annotation:javax.annotation-api:jar:1.2
javax.servlet:javax.servlet-api:jar:3.1.0
org.eclipse.jetty:jetty-annotations:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-continuation:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-http:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-io:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-jndi:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-plus:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-security:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-server:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlet:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-servlets:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-util:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-webapp:jar:9.2.14.v20151106
org.eclipse.jetty:jetty-xml:jar:9.2.14.v20151106
org.eclipse.jetty.toolchain:jetty-schemas:jar:3.1.M0
) + validation_deps
else
raise "Unknown GWT version #{v}"
end
end
end
module ProjectExtension
protected
def gwt_detect_version(dependencies)
version = nil
dependencies.each do |dep|
if dep.respond_to?(:to_spec_hash)
hash = dep.to_spec_hash
if %w(org.realityforge.com.google.gwt com.google.gwt).include?(hash[:group]) && 'gwt-user' == hash[:id] && :jar == hash[:type]
version = hash[:version]
end
end
end
version
end
end
end
end
|
require 'yaml'
class Hash
def deep_merge(other)
# deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
merger = proc { |key, v1, v2| (Hash === v1 && Hash === v2) ? v1.merge(v2, &merger) : v2 }
merge(other, &merger)
end
def set(keys, value)
key = keys.shift
if keys.empty?
self[key] = value
else
self[key] ||= {}
self[key].set keys, value
end
end
if ENV['SORT']
# copy of ruby's to_yaml method, prepending sort.
# before each so we get an ordered yaml file
def to_yaml( opts = {} )
YAML::quick_emit( self, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
sort.each do |k, v| #<- Adding sort.
map.add( k, v )
end
end
end
end
end
end
namespace :translate do
desc "Show untranslated keys for locale LOCALE"
task :untranslated => :environment do
from_locale = I18n.default_locale
untranslated = Translate::Keys.new.untranslated_keys
if untranslated.present?
untranslated.each do |locale, keys|
keys.each do |key|
from_text = I18n.backend.send(:lookup, from_locale, key)
puts "#{locale}.#{key} (#{from_locale}.#{key}='#{from_text}')"
end
end
else
puts "No untranslated keys"
end
end
desc "Show I18n keys that are missing in the config/locales/default_locale.yml YAML file"
task :missing => :environment do
missing = Translate::Keys.new.missing_keys.inject([]) do |keys, (key, filename)|
keys << "#{key} in \t #{filename} is missing"
end
puts missing.present? ? missing.join("\n") : "No missing translations in the default locale file"
end
desc "Remove all translation texts that are no longer present in the locale they were translated from"
task :remove_obsolete_keys => :environment do
I18n.backend.send(:init_translations)
master_locale = ENV['LOCALE'] || I18n.default_locale
Translate::Keys.translated_locales.each do |locale|
texts = {}
Translate::Keys.new.i18n_keys(locale).each do |key|
if I18n.backend.send(:lookup, master_locale, key).to_s.present?
texts[key] = I18n.backend.send(:lookup, locale, key)
end
end
I18n.backend.send(:translations)[locale] = nil # Clear out all current translations
I18n.backend.store_translations(locale, Translate::Keys.to_deep_hash(texts))
Translate::Storage.new(locale).write_to_file
end
end
desc "Merge I18n keys from log/translations.yml into config/locales/*.yml (for use with the Rails I18n TextMate bundle)"
task :merge_keys => :environment do
I18n.backend.send(:init_translations)
new_translations = YAML::load(IO.read(File.join(Rails.root, "log", "translations.yml")))
raise("Can only merge in translations in single locale") if new_translations.keys.size > 1
locale = new_translations.keys.first
overwrites = false
Translate::Keys.to_shallow_hash(new_translations[locale]).keys.each do |key|
new_text = key.split(".").inject(new_translations[locale]) { |hash, sub_key| hash[sub_key] }
existing_text = I18n.backend.send(:lookup, locale.to_sym, key)
if existing_text && new_text != existing_text
puts "ERROR: key #{key} already exists with text '#{existing_text.inspect}' and would be overwritten by new text '#{new_text}'. " +
"Set environment variable OVERWRITE=1 if you really want to do this."
overwrites = true
end
end
if !overwrites || ENV['OVERWRITE']
I18n.backend.store_translations(locale, new_translations[locale])
Translate::Storage.new(locale).write_to_file
end
end
desc "Apply Google translate to auto translate all texts in locale ENV['FROM'] to locale ENV['TO']"
task :google => :environment do
raise "Please specify FROM and TO locales as environment variables" if ENV['FROM'].blank? || ENV['TO'].blank?
# Depends on httparty gem
# http://www.robbyonrails.com/articles/2009/03/16/httparty-goes-foreign
class GoogleApi
include HTTParty
base_uri 'ajax.googleapis.com'
def self.translate(string, to, from)
tries = 0
begin
get("/ajax/services/language/translate",
:query => {:langpair => "#{from}|#{to}", :q => string, :v => 1.0},
:format => :json)
rescue
tries += 1
puts("SLEEPING - retrying in 5...")
sleep(5)
retry if tries < 10
end
end
end
I18n.backend.send(:init_translations)
start_at = Time.now
translations = {}
Translate::Keys.new.i18n_keys(ENV['FROM']).each do |key|
from_text = I18n.backend.send(:lookup, ENV['FROM'], key).to_s
to_text = I18n.backend.send(:lookup, ENV['TO'], key)
if !from_text.blank? && to_text.blank?
print "#{key}: '#{from_text[0, 40]}' => "
if !translations[from_text]
response = GoogleApi.translate(from_text, ENV['TO'], ENV['FROM'])
translations[from_text] = response["responseData"] && response["responseData"]["translatedText"]
end
if !(translation = translations[from_text]).blank?
translation.gsub!(/\(\(([a-z_.]+)\)\)/i, '{{\1}}')
# Google translate sometimes replaces {{foobar}} with (()) foobar. We skip these
if translation !~ /\(\(\)\)/
puts "'#{translation[0, 40]}'"
I18n.backend.store_translations(ENV['TO'].to_sym, Translate::Keys.to_deep_hash({key => translation}))
else
puts "SKIPPING since interpolations were messed up: '#{translation[0,40]}'"
end
else
puts "NO TRANSLATION - #{response.inspect}"
end
end
end
puts "\nTime elapsed: #{(((Time.now - start_at) / 60) * 10).to_i / 10.to_f} minutes"
Translate::Storage.new(ENV['TO'].to_sym).write_to_file
end
desc "List keys that have changed I18n texts between YAML file ENV['FROM_FILE'] and YAML file ENV['TO_FILE']. Set ENV['VERBOSE'] to see changes"
task :changed => :environment do
from_hash = Translate::Keys.to_shallow_hash(Translate::File.new(ENV['FROM_FILE']).read)
to_hash = Translate::Keys.to_shallow_hash(Translate::File.new(ENV['TO_FILE']).read)
from_hash.each do |key, from_value|
if (to_value = to_hash[key]) && to_value != from_value
key_without_locale = key[/^[^.]+\.(.+)$/, 1]
if ENV['VERBOSE']
puts "KEY: #{key_without_locale}"
puts "FROM VALUE: '#{from_value}'"
puts "TO VALUE: '#{to_value}'"
else
puts key_without_locale
end
end
end
end
end
Fixed translate:untranslated task so that it outputs 'No untranslated keys' if no keys are untranslated
require 'yaml'
class Hash
def deep_merge(other)
# deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809
merger = proc { |key, v1, v2| (Hash === v1 && Hash === v2) ? v1.merge(v2, &merger) : v2 }
merge(other, &merger)
end
def set(keys, value)
key = keys.shift
if keys.empty?
self[key] = value
else
self[key] ||= {}
self[key].set keys, value
end
end
if ENV['SORT']
# copy of ruby's to_yaml method, prepending sort.
# before each so we get an ordered yaml file
def to_yaml( opts = {} )
YAML::quick_emit( self, opts ) do |out|
out.map( taguri, to_yaml_style ) do |map|
sort.each do |k, v| #<- Adding sort.
map.add( k, v )
end
end
end
end
end
end
namespace :translate do
desc "Show untranslated keys for locale LOCALE"
task :untranslated => :environment do
from_locale = I18n.default_locale
untranslated = Translate::Keys.new.untranslated_keys
messages = []
untranslated.each do |locale, keys|
keys.each do |key|
from_text = I18n.backend.send(:lookup, from_locale, key)
messages << "#{locale}.#{key} (#{from_locale}.#{key}='#{from_text}')"
end
end
if messages.present?
messages.each { |m| puts m }
else
puts "No untranslated keys"
end
end
desc "Show I18n keys that are missing in the config/locales/default_locale.yml YAML file"
task :missing => :environment do
missing = Translate::Keys.new.missing_keys.inject([]) do |keys, (key, filename)|
keys << "#{key} in \t #{filename} is missing"
end
puts missing.present? ? missing.join("\n") : "No missing translations in the default locale file"
end
desc "Remove all translation texts that are no longer present in the locale they were translated from"
task :remove_obsolete_keys => :environment do
I18n.backend.send(:init_translations)
master_locale = ENV['LOCALE'] || I18n.default_locale
Translate::Keys.translated_locales.each do |locale|
texts = {}
Translate::Keys.new.i18n_keys(locale).each do |key|
if I18n.backend.send(:lookup, master_locale, key).to_s.present?
texts[key] = I18n.backend.send(:lookup, locale, key)
end
end
I18n.backend.send(:translations)[locale] = nil # Clear out all current translations
I18n.backend.store_translations(locale, Translate::Keys.to_deep_hash(texts))
Translate::Storage.new(locale).write_to_file
end
end
desc "Merge I18n keys from log/translations.yml into config/locales/*.yml (for use with the Rails I18n TextMate bundle)"
task :merge_keys => :environment do
I18n.backend.send(:init_translations)
new_translations = YAML::load(IO.read(File.join(Rails.root, "log", "translations.yml")))
raise("Can only merge in translations in single locale") if new_translations.keys.size > 1
locale = new_translations.keys.first
overwrites = false
Translate::Keys.to_shallow_hash(new_translations[locale]).keys.each do |key|
new_text = key.split(".").inject(new_translations[locale]) { |hash, sub_key| hash[sub_key] }
existing_text = I18n.backend.send(:lookup, locale.to_sym, key)
if existing_text && new_text != existing_text
puts "ERROR: key #{key} already exists with text '#{existing_text.inspect}' and would be overwritten by new text '#{new_text}'. " +
"Set environment variable OVERWRITE=1 if you really want to do this."
overwrites = true
end
end
if !overwrites || ENV['OVERWRITE']
I18n.backend.store_translations(locale, new_translations[locale])
Translate::Storage.new(locale).write_to_file
end
end
desc "Apply Google translate to auto translate all texts in locale ENV['FROM'] to locale ENV['TO']"
task :google => :environment do
raise "Please specify FROM and TO locales as environment variables" if ENV['FROM'].blank? || ENV['TO'].blank?
# Depends on httparty gem
# http://www.robbyonrails.com/articles/2009/03/16/httparty-goes-foreign
class GoogleApi
include HTTParty
base_uri 'ajax.googleapis.com'
def self.translate(string, to, from)
tries = 0
begin
get("/ajax/services/language/translate",
:query => {:langpair => "#{from}|#{to}", :q => string, :v => 1.0},
:format => :json)
rescue
tries += 1
puts("SLEEPING - retrying in 5...")
sleep(5)
retry if tries < 10
end
end
end
I18n.backend.send(:init_translations)
start_at = Time.now
translations = {}
Translate::Keys.new.i18n_keys(ENV['FROM']).each do |key|
from_text = I18n.backend.send(:lookup, ENV['FROM'], key).to_s
to_text = I18n.backend.send(:lookup, ENV['TO'], key)
if !from_text.blank? && to_text.blank?
print "#{key}: '#{from_text[0, 40]}' => "
if !translations[from_text]
response = GoogleApi.translate(from_text, ENV['TO'], ENV['FROM'])
translations[from_text] = response["responseData"] && response["responseData"]["translatedText"]
end
if !(translation = translations[from_text]).blank?
translation.gsub!(/\(\(([a-z_.]+)\)\)/i, '{{\1}}')
# Google translate sometimes replaces {{foobar}} with (()) foobar. We skip these
if translation !~ /\(\(\)\)/
puts "'#{translation[0, 40]}'"
I18n.backend.store_translations(ENV['TO'].to_sym, Translate::Keys.to_deep_hash({key => translation}))
else
puts "SKIPPING since interpolations were messed up: '#{translation[0,40]}'"
end
else
puts "NO TRANSLATION - #{response.inspect}"
end
end
end
puts "\nTime elapsed: #{(((Time.now - start_at) / 60) * 10).to_i / 10.to_f} minutes"
Translate::Storage.new(ENV['TO'].to_sym).write_to_file
end
desc "List keys that have changed I18n texts between YAML file ENV['FROM_FILE'] and YAML file ENV['TO_FILE']. Set ENV['VERBOSE'] to see changes"
task :changed => :environment do
from_hash = Translate::Keys.to_shallow_hash(Translate::File.new(ENV['FROM_FILE']).read)
to_hash = Translate::Keys.to_shallow_hash(Translate::File.new(ENV['TO_FILE']).read)
from_hash.each do |key, from_value|
if (to_value = to_hash[key]) && to_value != from_value
key_without_locale = key[/^[^.]+\.(.+)$/, 1]
if ENV['VERBOSE']
puts "KEY: #{key_without_locale}"
puts "FROM VALUE: '#{from_value}'"
puts "TO VALUE: '#{to_value}'"
else
puts key_without_locale
end
end
end
end
end
|
Adds last homebrew version of class-dump (probably a dud)
|
#
# Be sure to run `pod lib lint FIDynamicViewController.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# Any lines starting with a # are optional, but encouraged
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "FIDynamicViewControllerNew"
s.version = "1.4.0"
s.summary = "Frameworks to create dynamic complex view controller"
s.description = <<-DESC
FIDynamicViewController built makes it easy to create a dynamic and flexible view controller with its contents.
For example, when you want to create a view controller with the components within it are loaded depends on a particular configuration.
DESC
s.homepage = "https://github.com/congncif/FIDynamicViewControllerNew"
# s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2"
s.license = 'MIT'
s.author = { "NGUYEN CHI CONG" => "congnc.if@gmail.com" }
s.source = { :git => "https://github.com/congncif/FIDynamicViewControllerNew.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/congncif'
s.platform = :ios, '7.0'
s.requires_arc = true
#s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'FIDynamicViewController' => ['Pod/Assets/*.png']
}
#s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit', 'CoreGraphics'
# s.dependency 'AFNetworking', '~> 2.3'
s.ios.vendored_frameworks = 'Pod/FIDynamicViewController.framework'
end
update fix
#
# Be sure to run `pod lib lint FIDynamicViewController.podspec' to ensure this is a
# valid spec and remove all comments before submitting the spec.
#
# Any lines starting with a # are optional, but encouraged
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = "FIDynamicViewControllerNew"
s.version = "1.4.1"
s.summary = "Frameworks to create dynamic complex view controller"
s.description = <<-DESC
FIDynamicViewController built makes it easy to create a dynamic and flexible view controller with its contents.
For example, when you want to create a view controller with the components within it are loaded depends on a particular configuration.
DESC
s.homepage = "https://github.com/congncif/FIDynamicViewControllerNew"
# s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2"
s.license = 'MIT'
s.author = { "NGUYEN CHI CONG" => "congnc.if@gmail.com" }
s.source = { :git => "https://github.com/congncif/FIDynamicViewControllerNew.git", :tag => s.version.to_s }
s.social_media_url = 'https://twitter.com/congncif'
s.platform = :ios, '7.0'
s.requires_arc = true
#s.source_files = 'Pod/Classes/**/*'
s.resource_bundles = {
'FIDynamicViewController' => ['Pod/Assets/*.png']
}
#s.public_header_files = 'Pod/Classes/**/*.h'
s.frameworks = 'UIKit', 'CoreGraphics'
# s.dependency 'AFNetworking', '~> 2.3'
s.ios.vendored_frameworks = 'Pod/FIDynamicViewController.framework'
end
|
class OpenlibertyWebprofile8 < Formula
desc "Lightweight open framework for Java (Jakarta EE Web Profile 8)"
homepage "https://openliberty.io"
url "https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/22.0.0.10/openliberty-webProfile8-22.0.0.10.zip"
sha256 "ad50290521282446459d9f104e2989ec321330ef3be23945ab2794159bc323d1"
license "EPL-1.0"
livecheck do
url "https://openliberty.io/api/builds/data"
regex(/openliberty[._-]v?(\d+(?:\.\d+)+)\.zip/i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "008a4459f618374b891cc6acd71830b59dc608f1637ff76beadda9872a5ab869"
end
depends_on "openjdk"
def install
rm_rf Dir["bin/**/*.bat"]
prefix.install_metafiles
libexec.install Dir["*"]
(bin/"openliberty-webprofile8").write_env_script "#{libexec}/bin/server",
Language::Java.overridable_java_home_env
end
def caveats
<<~EOS
The home of Open Liberty Jakarta EE Web Profile 8 is:
#{opt_libexec}
EOS
end
test do
ENV["WLP_USER_DIR"] = testpath
begin
system bin/"openliberty-webprofile8", "start"
assert_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
ensure
system bin/"openliberty-webprofile8", "stop"
end
refute_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
assert_match "<feature>webProfile-8.0</feature>", (testpath/"servers/defaultServer/server.xml").read
end
end
openliberty-webprofile8: update 22.0.0.10 bottle.
class OpenlibertyWebprofile8 < Formula
desc "Lightweight open framework for Java (Jakarta EE Web Profile 8)"
homepage "https://openliberty.io"
url "https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/22.0.0.10/openliberty-webProfile8-22.0.0.10.zip"
sha256 "ad50290521282446459d9f104e2989ec321330ef3be23945ab2794159bc323d1"
license "EPL-1.0"
livecheck do
url "https://openliberty.io/api/builds/data"
regex(/openliberty[._-]v?(\d+(?:\.\d+)+)\.zip/i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "b3428d4c3f9a5d265143e71b228a797c5ad2394678e7535ae83822cd6bd9d222"
end
depends_on "openjdk"
def install
rm_rf Dir["bin/**/*.bat"]
prefix.install_metafiles
libexec.install Dir["*"]
(bin/"openliberty-webprofile8").write_env_script "#{libexec}/bin/server",
Language::Java.overridable_java_home_env
end
def caveats
<<~EOS
The home of Open Liberty Jakarta EE Web Profile 8 is:
#{opt_libexec}
EOS
end
test do
ENV["WLP_USER_DIR"] = testpath
begin
system bin/"openliberty-webprofile8", "start"
assert_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
ensure
system bin/"openliberty-webprofile8", "stop"
end
refute_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
assert_match "<feature>webProfile-8.0</feature>", (testpath/"servers/defaultServer/server.xml").read
end
end
|
#!/usr/bin/env ruby
url = 'http://127.0.0.1:4100/articles'
server = 'unicorn_6'
users = [1, 2, 4, 8, 16, 32, 64, 128]
puts "Warming up..."
`ab #{url}`
users.each do |user_count|
puts "Runnning test with #{user_count} users"
`ab -c #{user_count} -t 30 #{url} &> ab/#{server}/#{user_count}.txt`
end
Update script to receive server and port
#!/usr/bin/env ruby
server, port = *ARGV
server ||= 'unamed_server'
port ||= '3000'
url = "http://127.0.0.1:#{port}/articles"
users = [1, 2, 4, 8, 16, 32, 64, 128]
`mkdir -p ab/#{server}`
puts 'Warming up...'
5.times { `ab #{url}` }
users.each do |user_count|
puts "Runnning test with #{user_count} users"
`ab -c #{user_count} -t 30 #{url} &> ab/#{server}/#{user_count}.txt`
end
|
cask "dcp-o-matic-encode-server" do
version "2.14.57"
sha256 "5a52cfa03a64b3c0e124f01a4d858480cbbb3a0d660b511f62b2403f8c870ba4"
url "https://dcpomatic.com/dl.php?id=osx-10.9-server&version=#{version}"
name "DCP-o-matic Encode Server"
desc "Convert video, audio and subtitles into DCP (Digital Cinema Democratized)"
homepage "https://dcpomatic.com/"
livecheck do
cask "dcp-o-matic"
end
app "DCP-o-matic #{version.major} Encode Server.app"
end
Update dcp-o-matic-encode-server from 2.14.57 to 2.16.5 (#121483)
cask "dcp-o-matic-encode-server" do
version "2.16.5"
sha256 "70acd5eb2b2a09d82bf0d615bae0754ba6750da734c4575f4918efdf4d3c1417"
url "https://dcpomatic.com/dl.php?id=osx-10.10-server&version=#{version}"
name "DCP-o-matic Encode Server"
desc "Convert video, audio and subtitles into DCP (Digital Cinema Democratized)"
homepage "https://dcpomatic.com/"
livecheck do
cask "dcp-o-matic"
end
app "DCP-o-matic #{version.major} Encode Server.app"
end
|
cask 'dcp-o-matic-encode-server' do
version '2.14.10'
sha256 '1a9454ee430a15ea9891a059eb5957cb32753b6e324736807f3f728ef35f6f6f'
url "https://dcpomatic.com/dl.php?id=osx-server&version=#{version}"
appcast 'https://dcpomatic.com/download'
name 'DCP-o-matic Encode Server'
homepage 'https://dcpomatic.com/'
app "DCP-o-matic #{version.major} Encode Server.app"
end
Update dcp-o-matic-encode-server from 2.14.10 to 2.14.11 (#71031)
cask 'dcp-o-matic-encode-server' do
version '2.14.11'
sha256 'b8fbd56f3c8749ff9b69f8276d68fbd44399928fbfcbf997a0a50ad133977ad4'
url "https://dcpomatic.com/dl.php?id=osx-server&version=#{version}"
appcast 'https://dcpomatic.com/download'
name 'DCP-o-matic Encode Server'
homepage 'https://dcpomatic.com/'
app "DCP-o-matic #{version.major} Encode Server.app"
end
|
class FontSauceCodePowerline < Cask
version '1.017'
sha256 :no_check
url 'https://github.com/Lokaltog/powerline-fonts/trunk/SourceCodePro',
:using => :svn,
:revision => '50',
:trust_cert => true
homepage 'https://github.com/Lokaltog/powerline-fonts/tree/master/SourceCodePro'
font 'Sauce Code Powerline Black.otf'
font 'Sauce Code Powerline Bold.otf'
font 'Sauce Code Powerline ExtraLight.otf'
font 'Sauce Code Powerline Light.otf'
font 'Sauce Code Powerline Medium.otf'
font 'Sauce Code Powerline Regular.otf'
font 'Sauce Code Powerline Semibold.otf'
end
version 'latest' for font-sauce-code-powerline.rb
preserve known version in comment for later use
class FontSauceCodePowerline < Cask
# version '1.017'
version 'latest'
sha256 :no_check
url 'https://github.com/Lokaltog/powerline-fonts/trunk/SourceCodePro',
:using => :svn,
:revision => '50',
:trust_cert => true
homepage 'https://github.com/Lokaltog/powerline-fonts/tree/master/SourceCodePro'
font 'Sauce Code Powerline Black.otf'
font 'Sauce Code Powerline Bold.otf'
font 'Sauce Code Powerline ExtraLight.otf'
font 'Sauce Code Powerline Light.otf'
font 'Sauce Code Powerline Medium.otf'
font 'Sauce Code Powerline Regular.otf'
font 'Sauce Code Powerline Semibold.otf'
end
|
cask 'libreoffice-language-pack' do
version '5.2.3'
language 'af' do
sha256 'd5009312d432832bc90c2564b1491c112b476330a45b3acd8699f1c6a8f3e1b6'
'af'
end
language 'am' do
sha256 'ff3431ebd29d2dbe8bbe39aeb6f6006041eeb7bf72d71eaac12b6186d99eee19'
'am'
end
language 'ar' do
sha256 '35070e52f6cae28a0e8e3911a24e3002d1af94b218e4d7dc9d616b2615d4031d'
'ar'
end
language 'as' do
sha256 'b4cf937e225722f4f72f1e87465400a17e1032c56bca1c738d8f53ffda9b66b7'
'as'
end
language 'ast' do
sha256 '77f2b61a0b6527410060d3301eef0bd4c77073aa6469bcaac6f0da31317fdd20'
'ast'
end
language 'be' do
sha256 '98465e1720f0f175f09eb9e0c5e9261ecf2ca93ba36683f852a510d5c4ef0094'
'be'
end
language 'bg' do
sha256 'c21539441f2c20d1d4ac2872bc8db8e9e4230b6d0c74d125bbcc74130d7c094f'
'bg'
end
language 'bn-IN' do
sha256 'e5536a6765668fa64831c2317e673c9dfb3a6ca676fe0a2288b3095c37f66699'
'bn-IN'
end
language 'bn' do
sha256 '4aea516aeb8241e3cde93b41e92319c39e6bea56342087c56c26850d6047f28c'
'bn'
end
language 'bo' do
sha256 '5f9b89303502d5c6dd16e632a47da525d5a6951b4732e0e4e7a6f7b83056d479'
'bo'
end
language 'br' do
sha256 '9ca5043328dfdab26a73a997718081271c1604643d5122d3c9dc820f6faa7f54'
'br'
end
language 'brx' do
sha256 '2f31173e18b12bc2e35ede6406cb6cb5d2f0ed6ff97f8b4f2f902d80e57f04b6'
'brx'
end
language 'bs' do
sha256 '2904d69b1b9349bfc306679349382b551bc9d77c924156c87c87a5c86e8277b8'
'bs'
end
language 'ca' do
sha256 'cf5cefe1318bb50c056703bb72eae9c9361c026b602dbc85a7060c1ef851e1f9'
'ca'
end
language 'cs' do
sha256 '288c419e633968eacff11594bcfb14f6bfa952584d994c4767dedf739f94e852'
'cs'
end
language 'cy' do
sha256 'c81557baf678f12eef6af6e9f99c89986ec79e61dba88ea254799d20bff911cd'
'cy'
end
language 'da' do
sha256 '71282a8a39e67003d9081c6c0fc3030fe7c84a384f1d8b59ee8fb8e18d25c27e'
'da'
end
language 'de' do
sha256 'cb7fe65c8532285e86633b138cc6da185f972da5c454ede793f186e17ffc9d48'
'de'
end
language 'dgo' do
sha256 'd647e194877b9963416d66094195bec7fbfc838a97cd9ea5917d4148b1aae00d'
'dgo'
end
language 'dz' do
sha256 '447ca2760b3aa30f48c4247509f2566c6ad38525ff422d50823dc804b978a5a0'
'dz'
end
language 'el' do
sha256 '225c28228cab01b34abded9bafcb4fca6d44cc7c5124ea7946b0ebaacaff319a'
'el'
end
language 'en-GB', default: true do
sha256 '82df20bdfc602a92019d8a404a2ab8980f751304bd19331d2e71f7b2c5284ff6'
'en-GB'
end
language 'en-ZA' do
sha256 'cdf3ab4de10b746e77b891816cafc2beaa6508d514f57ddeb9fa55ed725aa8c8'
'en-ZA'
end
language 'eo' do
sha256 'c17194be7bfb3356feb99b6e4571adc7b048e7cae3c47fb87673120e641c9c08'
'eo'
end
language 'es' do
sha256 'c377f416b57b97df2b7837e65887898cce37d07afb1c84fc9bf7e41ab30cf1f2'
'es'
end
language 'et' do
sha256 'a3012646b646af345a2867a98813755b661faf15a8060f43e0e3a06b9ccc0d82'
'et'
end
language 'eu' do
sha256 '49afdcb9c74d04d1688e7e72c88ad362b8a53ddab1582c89ecc3aeea1c465bae'
'eu'
end
language 'fa' do
sha256 'd5c7193678cef77b8919143d04bfefa02121fc816f6bdb4258b350070f129019'
'fa'
end
language 'fi' do
sha256 '3cc89a7eb0cbf2687e363f5e8494aae81043822a4cb740ab8307bebce28c2464'
'fi'
end
language 'fr' do
sha256 'd841458189b90ae5f3e208620707833b4def2e9d8c2be71ae395ec25bec1908c'
'fr'
end
language 'ga' do
sha256 'f7aa663be019e40a0bdc9ae356ca63b43d590be39b47edf1496542c185209c24'
'ga'
end
language 'gd' do
sha256 '52b31554f81384f0ccac76e77b884e48a9e6c32f09e06620e62745a3238dedb7'
'gd'
end
language 'gl' do
sha256 '743afa8db12737b556a48b330afba83878c20f5daf354c2794bfd90f08781cfd'
'gl'
end
language 'gu' do
sha256 '7e0e878248d7a396da93f3d814d6467724b42358c402d6b185bce690b557ce4d'
'gu'
end
language 'gug' do
sha256 '92e445a64e9c767c4369d201c2f68964a60b232c0814c415a6eac1b02240b7bb'
'gug'
end
language 'he' do
sha256 '15d9cd689454cd27a0dcf21ef6cd9f4e4151d5bc6e8f67fa19f5e156fcc3bfe6'
'he'
end
language 'hi' do
sha256 '39a25396f0314e20366d340b784a6672fbe183f8a54faac03eab60538383e1ba'
'hi'
end
language 'hr' do
sha256 'a89415a7f93ed8ce7ea9e1dfab6d562805838b817a1d0229a114258f8b3203db'
'hr'
end
language 'hu' do
sha256 '542b45a5f188c650e4c98a5e9424cf920d22a025cb9873dd7b71b29810efefa8'
'hu'
end
language 'id' do
sha256 '450e9ebff9a22e886c8aeb5c37727c1dfe90cb9668f5de7c7247d72c233c6076'
'id'
end
language 'is' do
sha256 '0fd35404f256b73ddbc8a3a59536971df9b256fa959ee476ce936e1e5cb15e92'
'is'
end
language 'it' do
sha256 'bc46c7917eabea915769f091a271b738a7d6659ea88b043137b31f67df122dd7'
'it'
end
language 'ja' do
sha256 'fc9bcbd84e46322dfc503efebd76785ac774e86ca3ec078151c2671637d76fdf'
'ja'
end
language 'ka' do
sha256 '0651e9b7a6e05869ebef1b78c20189721bdd48414f8bd38088dae8b6c19ff414'
'ka'
end
language 'kk' do
sha256 '6b5cd715ca325a7d35e91c0d50dd647c5a4b8cfd3c40465702e3bf086ac63c14'
'kk'
end
language 'km' do
sha256 'ef089970324ca25e2e5f7de63cf267d554d580b13bb39fb706cfa076cee7465b'
'km'
end
language 'kmr-Latn' do
sha256 '8ff30d162f859efe8da91c24ee9e6babfb8b909591a07b8b30fd0f2b172046bd'
'kmr-Latn'
end
language 'kn' do
sha256 '2802d4e0be0b675dd8605d2492ce9faca1044b4309f264bb98fe6ee4b1062d28'
'kn'
end
language 'ko' do
sha256 'ef1589600ffb46635316d69076d87e9d87f7085ac9ec3a78c43886d3c516b333'
'ko'
end
language 'kok' do
sha256 'fe80158e0abf52a39d7e88cdcb70abdead066ac455a12d8fc334071e1aa583c6'
'kok'
end
language 'ks' do
sha256 'ba653831d1d7a459b1cb4c5d79e0ecfd82dc010243a8907371a8550224a3a711'
'ks'
end
language 'lb' do
sha256 'd390a2a699c39c1262833940151b3e5003cf68916c2c22eacbb5a145d56d522e'
'lb'
end
language 'lo' do
sha256 '36564c618508a96d79fcf65ffaf22d8e739c8d32066cfaa334bc937cb4247f24'
'lo'
end
language 'lt' do
sha256 '555dbf57e97e138277b95696f80ee1e5318945961d802ac16f931f0398ddf4df'
'lt'
end
language 'lv' do
sha256 '70a7f2969c636364c4d1757c1da4f9f08938e0f8f303886c17d9abcdefd2d09a'
'lv'
end
language 'mai' do
sha256 '788dabe556015533c7d3eb52b19dc6c30f0ec228e0403020d4f986b2393db888'
'mai'
end
language 'mk' do
sha256 '851eac7769dcee0ef363dcae6c66c5218db676af2d774be71dcd0a64a462b9d6'
'mk'
end
language 'ml' do
sha256 '32c874e661e00e38392aae5dff16c6bf92d7f0a069db5e88d1e32001402635c0'
'ml'
end
language 'mn' do
sha256 '163a4db92bef94030b10ba5765c3a14fd9ace2123a9667893d006ad6e252a168'
'mn'
end
language 'mni' do
sha256 '049a73176f1f426a5c3aef439ac87c1051f8ff1848c5eeae4bde53e86870b5a7'
'mni'
end
language 'mr' do
sha256 'f6a15fa36086fb875f100d77cd32d06886ca762807f0285b6550970b6513b853'
'mr'
end
language 'my' do
sha256 '79bc7cf596b8e63521f72a94b5e06a6d88f8787e2249166c582635ca41239e64'
'my'
end
language 'nb' do
sha256 '8c1a63da3d911645683b9b2bcca24b34c5bccd37f82db572c565a6edbfe040f7'
'nb'
end
language 'ne' do
sha256 '60d2ad5a0183202a6afba4082fd1f18680a97fd023ac75fd34e5557aea58aa28'
'ne'
end
language 'nl' do
sha256 '3ef1a0c0ceb49a27c584dc5bfd5b384ac5397d2740e277d2e7e2b60c6e5dfc11'
'nl'
end
language 'nn' do
sha256 '0e6931c16538fdac46d295920904c4eb3bda8d761c8dd6bafbed6c9cafd9ea20'
'nn'
end
language 'nr' do
sha256 '09f7cb67a721938fd4c796b9745c33798c9659b650375ae92002a663d655a383'
'nr'
end
language 'nso' do
sha256 'f7622330a186076f65341381ac949b40841c96c72dbe88e6c95ef52463a3ab10'
'nso'
end
language 'oc' do
sha256 '7014d22eebcb9ec965a36516c2c0e2f4ff14c6cc859201b3ced7723daa19b135'
'oc'
end
language 'om' do
sha256 '56cb3e16178ef7ae6a49489eaa40a82c0c38820ea4ac705e258022dfa83554f8'
'om'
end
language 'or' do
sha256 '1e39fb17ce192006b66e15617188d31e4caf70814668e2e55eb39efaed6ee42c'
'or'
end
language 'pa-IN' do
sha256 '17517e12fa28e5f8ac9dfe00e3b86598225e06cd37e40ad61aaccf3fd94a0cc7'
'pa-IN'
end
language 'pl' do
sha256 '5b4c0e784facd5b2fe89677d719ac6de1aff44e89bc4f5fdc9eafd12fcf502c9'
'pl'
end
language 'pt-BR' do
sha256 '5075453c8cf3c27fbd36517fb2a26cf6ab8961d8f52316baa59a99cd1266d1ee'
'pt-BR'
end
language 'pt' do
sha256 '8a56305b4629af4694ab4181bfbedc07dbe72f33a88d1a286da4154278d1efb9'
'pt'
end
language 'ro' do
sha256 '0ee78fbc6ae00c84572d4f5b9d76e5d50fcfd1efaa792f10588171cccfeea0d7'
'ro'
end
language 'ru' do
sha256 '7e64b57acef1f801f7f292bf186d4638cedaf30f3b3641e8e558db33dd961a5e'
'ru'
end
language 'rw' do
sha256 '0c52879c16f358332b59becbb12f24f6d6fff7f45d03040264211690b8246053'
'rw'
end
language 'sa-IN' do
sha256 '0d751199a7b8d94bd5b1242043ea1ee7aebe17499fb68b4ce90872e9ce7b065e'
'sa-IN'
end
language 'sat' do
sha256 'e3153fad150a535e8863fd2ac5f85f2f30183065e1b24046c1a340b50931cde0'
'sat'
end
language 'sd' do
sha256 '3921b8210c3a623a908ad0e7157c9757f37467259c41fcdebaf58ab155222c27'
'sd'
end
language 'si' do
sha256 'a338dcbbf0fd5e468c84294ea89cbcf6c6ca27970df7daafffd64ba724359bfd'
'si'
end
language 'sid' do
sha256 'e8dc323cc34900ad8eff1889653411804fd5414eaf5e3131237c893ead213616'
'sid'
end
language 'sk' do
sha256 'f3185d509604bbde6a8f3e74c2239196c6eb485d1867bbd6fc9b65839bd2acb2'
'sk'
end
language 'sl' do
sha256 '528976a9f58cc727105c37aaa2d93aaad6e55b58833f16fd740dd9de4b7cf17b'
'sl'
end
language 'sq' do
sha256 '94c7c9de3ef6e988fdb5e23dbc6fdbeaf8c2b228fc6d598f2c08eebb38c3939a'
'sq'
end
language 'sr-Latn' do
sha256 '53d2b55c199b881e6346b45c538f5aa33479115e1c367cf071c62a6c8027511f'
'sr-Latn'
end
language 'sr' do
sha256 '4c1f7c337f5dc3fc223e81913582b4c85f682ca2de0166111ae263442b85d74b'
'sr'
end
language 'ss' do
sha256 '9ba622bc73df8ba41eb8e9a52396ab5f8fddc7d283845976eb18bfd840b29cd4'
'ss'
end
language 'st' do
sha256 'c7c49c0a552b2ee317800a6c5b4af4200a3cd6eb6fe9013ea99012c027b51fab'
'st'
end
language 'sv' do
sha256 'e34257318a33925d2300ad56df1e9dae4810417cac0118ce13c9634226216802'
'sv'
end
language 'sw-TZ' do
sha256 '04b8f433b24ec8b972428b43791d9ec00b44b25cdf1e7f40b7cf8aa31d2c9d15'
'sw-TZ'
end
language 'ta' do
sha256 '0dacd4a85aebfd63906ff7c4b39a0f4216637d32272e8f0be3f3bf172889dd23'
'ta'
end
language 'te' do
sha256 'c071feec32f8e75f4a471c63fa129cedb96960447d4c8e9463b1f10dadf83565'
'te'
end
language 'tg' do
sha256 '0640dc9d140b6579f69d7e0b7eae57fa0fbf43e77687e40733f5a69a4e04c28a'
'tg'
end
language 'th' do
sha256 'd7fe5f86765cb8a9273dedab39786f8faaa13fc330a37b0e42f95be4e33c3902'
'th'
end
language 'tn' do
sha256 '174563fa03cc5eae3d3e59c471d1e7c4602c0b166b2020b2ad2563319414d922'
'tn'
end
language 'tr' do
sha256 'b708810df7cb5381cf5ad017c4b2622124c02b4a32d4a7414a543a1b9fd1053f'
'tr'
end
language 'ts' do
sha256 '3f96277fb114b51a1eeb21b988d497a324f546cd9640bb055d2c2d5c6f1ea6e7'
'ts'
end
language 'tt' do
sha256 'd2651f3743548577cbc51dfeeb7b14be943df5eb9d94d9a340913de8008a62e7'
'tt'
end
language 'ug' do
sha256 '7837d6b623b87d49cf3a26c101ddbeb2ad4773ebad0c20524a61de115c88202c'
'ug'
end
language 'uk' do
sha256 '043cce4d8939106983dd61e56093eae2dd945e12d9cce991eb194a4066a0ef57'
'uk'
end
language 'uz' do
sha256 'f18b1112d37ab1740bcca49178a79e26d4faff4d5285d724d7c1b0c338347a79'
'uz'
end
language 've' do
sha256 'c525562b6b8169bc95e4b75f9cd72536a6e53815b3e6a936c23759432e7d6138'
've'
end
language 'vi' do
sha256 'c61014a9a5a5a7973d87654b11194a19b809745ad59e80833aa70841b61fcd29'
'vi'
end
language 'xh' do
sha256 '8c29a6ed054de06707b01bb2627a964380bc62fa29649a580c0f547498294895'
'xh'
end
language 'zh-CN' do
sha256 'dccb82fbbf17fb409dda0e9b1cd9b4e70862441c87fcb6e97ed6c22f0f7d8669'
'zh-CN'
end
language 'zh-TW' do
sha256 '69d078a007ba8a22ced33b66e84371ed6ea6773729b3d1b77709679d5e347832'
'zh-TW'
end
language 'zu' do
sha256 'cf898f1de9a4b66fc06049a4ccc1ec620debeea747fd4e2b80e4d380c1941604'
'zu'
end
# documentfoundation.org was verified as official when first introduced to the cask
url "http://download.documentfoundation.org/libreoffice/stable/#{version}/mac/x86_64/LibreOffice_#{version}_MacOS_x86-64_langpack_#{language}.dmg"
name 'LibreOffice Language Pack'
homepage 'https://www.libreoffice.org/'
gpg "#{url}.asc", key_id: 'c2839ecad9408fbe9531c3e9f434a1efafeeaea3'
depends_on cask: 'libreoffice'
stage_only true
preflight do
system_command '/usr/bin/tar', args: ['-C', "#{appdir}/LibreOffice.app/", '-xjf', "#{staged_path}/LibreOffice Language Pack.app/Contents/tarball.tar.bz2"]
system_command '/usr/bin/touch', args: ["#{appdir}/LibreOffice.app/Contents/Resources/extensions"]
end
caveats do
<<-EOS.undent
#{token} assumes LibreOffice is installed in #{appdir}. If it is not, you’ll need to run #{staged_path}/LibreOffice Language Pack.app manually.
EOS
end
end
Update libreoffice-language-pack to 5.2.4 (#28169)
* Update libreoffice-language-pack to 5.2.4
* Update libreoffice-language-pack: add language vec
cask 'libreoffice-language-pack' do
version '5.2.4'
language 'af' do
sha256 '987b6e82d7b2bced2d21fc72fbf9f25fce5512a5ad4b29fbe6f0cd76c26643c8'
'af'
end
language 'am' do
sha256 '64236a9548e2ccfab83fe2328cb35a5350f60788f83b084edbdca8da58b29ed4'
'am'
end
language 'ar' do
sha256 'd185c5127043918158d889e444f972e929c5a7ff0cd851a445218b02a0d26d8c'
'ar'
end
language 'as' do
sha256 '7ef0d459c92eb07b4cade347d1cda2670c37c9af5cdc3d8000b38acef9c06f7b'
'as'
end
language 'ast' do
sha256 '25a150e5a021300451f79b23d13585dfd353ae6b3c821c8d1268cd57272f7391'
'ast'
end
language 'be' do
sha256 '6ddc4bb2e9762cc5d497cf896df2ef6188b0621c03ae847df864cfe3a45cbb1d'
'be'
end
language 'bg' do
sha256 '5cf5b97bf97b2ad976e130fd3a3f8cdf7fd9382b3f0fb556f965b90ad9fb2156'
'bg'
end
language 'bn-IN' do
sha256 '68986d381dcd52f5ece4376c3ffd6401fb697d8d08960498e533d116c8de8741'
'bn-IN'
end
language 'bn' do
sha256 'a0f4d9e7c9b83a461e716e5cb04b603cb61a2939f62f4ae71a8b9fcdf8070639'
'bn'
end
language 'bo' do
sha256 '16da06484b9e33f4bf96c4cf6cbd74fd736870909b5bc547a98be63d18e5e5f0'
'bo'
end
language 'br' do
sha256 '227089e481fe00df0aa289f4c59c04ef200eb6fbb7de666b18aaa7f561a518e7'
'br'
end
language 'brx' do
sha256 'b97178acd6821afe0cf0c5a5abb9b0a7b8cfc118cc0681f1e78fa856a50bf3da'
'brx'
end
language 'bs' do
sha256 '7c10130ac2157041209b9fd1068cdbca9043db3c7519959a8f4382418ead0d43'
'bs'
end
language 'ca' do
sha256 'e90d89698ed6bbcdc2e06795a28bed3073f9648f1fdaeae63a38a53b8aea94b4'
'ca'
end
language 'cs' do
sha256 'a5bd49785a609e46998d99a43a7d3ff8a9632b43c7e5d3fb7c381227f232516c'
'cs'
end
language 'cy' do
sha256 'db44cc4a058fdb800954b10a6c84f56244c9a9c9e84bc632155fd6402cf22658'
'cy'
end
language 'da' do
sha256 'b7fe87bd77a7a81cefd5927060f5c22ed10f6f08dd3e2e2e51ed1ebda1cf6e2a'
'da'
end
language 'de' do
sha256 'fe3222341b071ccaa330b48a29c70e747647e572dec5b4ceadb907f01fa899ca'
'de'
end
language 'dgo' do
sha256 '5dd3643ddd3adc661fd2ca0c3cea27af39cbbc0bf41f598826b14a05a7260c49'
'dgo'
end
language 'dz' do
sha256 '928b9ba269debee929fe1181fe1c0ca4df0ee7d6d1717b704d66e17dbf0e6e3a'
'dz'
end
language 'el' do
sha256 '63fe95f55fd3cf373b8815add935b5e5959072f8c25ce89bf69f9301c811f877'
'el'
end
language 'en-GB', default: true do
sha256 '0774a1a698fec402e17f6b53d8d8e9fc238668e93c084444132a76defa4b4e03'
'en-GB'
end
language 'en-ZA' do
sha256 '04e6cee888bddb68b0c21ae1c8c2ed4b56b4ebd3ceb59fa5ade4223c7033fd69'
'en-ZA'
end
language 'eo' do
sha256 '080263f3c09903a3dba030cf3fa109a40ae395bf62c020136aad4d47000d25a8'
'eo'
end
language 'es' do
sha256 'f6a84a0e8273576a7bb3094a20d9529d3700551f40a5896810ca2dbe4aa1a395'
'es'
end
language 'et' do
sha256 '3a623bca9ee0c9ed7afc7928715dd8c8eb10b6ed715eb424af9873474db87c40'
'et'
end
language 'eu' do
sha256 'ef5026a638d88886b7797e1f45bdf23ea4e793de329cdacd518d151006068a69'
'eu'
end
language 'fa' do
sha256 '00612fc843d612d2a4e29c06478dfffceefea40b6a569fb81d817e2a2895e0f2'
'fa'
end
language 'fi' do
sha256 '2ab640b7724d9a93c9561705a3ba083a069fd009aa7d4c2e80a21bb450a23f0a'
'fi'
end
language 'fr' do
sha256 '3c0d7cf4e1c4f474e6f4561466e7fe3fdf6a0685865493c4653fe0360ce0e12b'
'fr'
end
language 'ga' do
sha256 '8413760a80e35cff6494258fa9b858bdef7b4375acea33c6ef87e35a8d1f2d3d'
'ga'
end
language 'gd' do
sha256 'c6c17b6ff685a971ce419f72d2657ecd1b63e72b6f47871290784d41574d33a0'
'gd'
end
language 'gl' do
sha256 '68affad15763b1411244241529368a569d89d30ad1a55fe22399f3b785d05fbc'
'gl'
end
language 'gu' do
sha256 'fd326d32383b3261a6d644832d29c1a3aefd1cbe866f99664be779851e98ebbc'
'gu'
end
language 'gug' do
sha256 'b49c126c3ecf92e51a63e70c16ce9746a7a5138b79a6f2ea66082c0a7e24fc6c'
'gug'
end
language 'he' do
sha256 '47e3df8da24d8328fe2fcbb19155b1c9318bc28d188ef1e0d1fb83ed37ff6abb'
'he'
end
language 'hi' do
sha256 'c0e87f50b14db7fb3d788817d31af4734eac74cf42fc72daee62396ff246014d'
'hi'
end
language 'hr' do
sha256 'f3c97c2524c3d03d70e8d03595654601249e83da56befa96f8685628998bb72e'
'hr'
end
language 'hu' do
sha256 '2ed2c15007321201526b766ef2e1a4165cf521de3661e5abaa93c49c4d51a65b'
'hu'
end
language 'id' do
sha256 'db8caf99494a86b255d82af49c28e3e7cd052b77d8ac310e28ca3081cc4d5516'
'id'
end
language 'is' do
sha256 '8eea4031cd4cf9d8904454234126f0ea8ecedd3b8b13488e52321ad8e364c459'
'is'
end
language 'it' do
sha256 '7c0e21e4f85d8823cdec1b79a69d81d6ed24cf9fd5163d2c3e8103c23326df8a'
'it'
end
language 'ja' do
sha256 '9e33105526ed0ff1f74164b4de9d26363cca223b6e9b6c250ed9f70c17c0967d'
'ja'
end
language 'ka' do
sha256 '5377faef06a2c34250645125993ff489e5a14c6de4c76c7c12dcc849a9977403'
'ka'
end
language 'kk' do
sha256 '64a1ebab8d90b57ba9e47f77640971af2bd00c1986d5665218539717ea2bc6d3'
'kk'
end
language 'km' do
sha256 '32b1069c6bf0c273449a485993731b63727ab6f9c30d0fe2d63aec4a4061bd49'
'km'
end
language 'kmr-Latn' do
sha256 '692db25bb1cbb68bc4579f3ae6f762c945b9418acb7b9b8b60f51efba3cf1397'
'kmr-Latn'
end
language 'kn' do
sha256 '99b0f8ee5b1eadfc4debeb7e30e6cff1d7112129970273a6513e016f1505102d'
'kn'
end
language 'ko' do
sha256 '5244909a75fa22c444aa9cb26ac3d96090e4a211c68551b41d2f1fe4407a6d5f'
'ko'
end
language 'kok' do
sha256 '1237723fcf6afef6a660aaad094c02449643d811b88697ddf8a90ad86b1dc21e'
'kok'
end
language 'ks' do
sha256 'c4986a031a63374ad1381150fc55a7d8f7fd8b62cd9ba11ada52ac8cabef83d5'
'ks'
end
language 'lb' do
sha256 '1c56d2b30110b12a082d72929d2ee7e55ad28455df8ca1539b8b987960f5b3f9'
'lb'
end
language 'lo' do
sha256 '5c51b05332b2c60944931104796695e64904af9385e781c6d06f0eb07853901f'
'lo'
end
language 'lt' do
sha256 '8a1a90f3274a81c12eb918f2909fb7e601fb3d56dd764f65c7b82e9f37e95bfe'
'lt'
end
language 'lv' do
sha256 '51919d9a5393b9995e2871eb7f3401bea3de5d5c1b90fb2b342c0a8bfe7c12ab'
'lv'
end
language 'mai' do
sha256 '125ef24390899c6eaf4529188aaceec38d3148d19b4ac96e05dcb63a07ffc040'
'mai'
end
language 'mk' do
sha256 'd0ff0864958779db06089a8ed140e82e355ea1257b32edd78c875413e982ad91'
'mk'
end
language 'ml' do
sha256 '7199f9dd087f22648a8128f5c058fcd6d743bf642d9238023be1bab73b1f66fb'
'ml'
end
language 'mn' do
sha256 '76f5f097cb7b390bde48f926d9d7d307ad0bdb19e225f07aac73e8bff0267e5b'
'mn'
end
language 'mni' do
sha256 '745cd39c79142850e010723b7768c515fa6ff01623f85461aaabc0879d087fda'
'mni'
end
language 'mr' do
sha256 '6b63a740d6ba2c247b6a26469cbe4c6958911a3231f57c048756aead0727fa0b'
'mr'
end
language 'my' do
sha256 '981dc0371e653aeada2afeee4ce4219bf48db4dd141cff526296b09a32ec2bc8'
'my'
end
language 'nb' do
sha256 '51ca00fde878fb5a5e57d5861523c4488530864f6f9476ce455a72595a00e71f'
'nb'
end
language 'ne' do
sha256 '2c59bcbb9c9bfd71f8f126f27729ff073fd8a1e3ef3ed64a881e1fce4924a593'
'ne'
end
language 'nl' do
sha256 '4d6bda111ef79992c614308fc9014c8b8373fe52a0285e02ae91b07b79142fe7'
'nl'
end
language 'nn' do
sha256 'd2f1110c4fa1ee128a674fa8c188d046fbdece67a660c763e56a2be6e0aa4d5e'
'nn'
end
language 'nr' do
sha256 'e26b8900db5e8895ad967aa53e389f8d63459e5f6c85081cbff1cd0915789562'
'nr'
end
language 'nso' do
sha256 '1d20f6ed7db8a8c35bd045e7ee6a291b4e1df853c9c4673e1d08e29a0011c657'
'nso'
end
language 'oc' do
sha256 '13d6f86592340a0050dd6d71c6f196677e3d5ffffccd4d3468a593f8d11d9e8b'
'oc'
end
language 'om' do
sha256 '0edf097441e76f779dbe0d7e474216eadd17c4c52bbe30fa4641cdd2b1521ff3'
'om'
end
language 'or' do
sha256 '5e4092853972ca689fdf7fa0548bebaaa27e3cdc4db4855777a9db26049e6bb1'
'or'
end
language 'pa-IN' do
sha256 '86daffbda877b37d4fdbc816703d859603f5910925a5e13ffd4cce5737816598'
'pa-IN'
end
language 'pl' do
sha256 '236d913f61bf6f4e92d0f8a695dfbb2f617d9288d12c27d6a539b904a6b01946'
'pl'
end
language 'pt-BR' do
sha256 '7ed724c19cb9950e01a6182d4dc4f110dfdf423205cc97fe4d88c13c6fc1dd19'
'pt-BR'
end
language 'pt' do
sha256 '1a47cb952e7b2b061593c0ad9894f3501256079ba39b9361857e92258f535223'
'pt'
end
language 'ro' do
sha256 '638df781ceb1292de1ee8e7d3e8b05411b5d07db0c46bb36f405bbe984c550ba'
'ro'
end
language 'ru' do
sha256 'd7373d60b51f7c93fae0e71308b2e06c30917b13b02da19485a8ba178759f60b'
'ru'
end
language 'rw' do
sha256 '2866f43841180a7830ca95d6ec34983ded7931b8802923a00fc75996fe83a912'
'rw'
end
language 'sa-IN' do
sha256 '94188c422c9b37bcdff9b31b9fdcd0a4fc533fbe1482497c7a44cc5a5efce57b'
'sa-IN'
end
language 'sat' do
sha256 'c275129c67516f1b282632775e7058b669d45f58591426e0eed8dc14e27cecf7'
'sat'
end
language 'sd' do
sha256 'ba7c260103709e5d0cf0232c2e64abbbb3d2ea2bb95d6b16881862e0cf47e891'
'sd'
end
language 'si' do
sha256 '91699299c64bc7a008be8733f846a4fc026b0e5ba1026c70e4147cb43a14d909'
'si'
end
language 'sid' do
sha256 'ab3f957d5071a6d786781348daa36b9dff79550f60a2ec92c819f43dc017826e'
'sid'
end
language 'sk' do
sha256 '9bedcda76832ec5f508b243e0b558fdc6458b05f8c1c7a253775f2d3e87ce7c0'
'sk'
end
language 'sl' do
sha256 'c79f00aef28363bea61e60b48de7cd910756e8bac03db12410ef8b7ea5123697'
'sl'
end
language 'sq' do
sha256 'cd36f25892338a0e3b958b59b3a304d706a1762baf0b65579e447b61c9dfe627'
'sq'
end
language 'sr-Latn' do
sha256 'e099832e1f0f3625d700e0d1ae0351e265db90be0a10a7a27577563f1d55b8a1'
'sr-Latn'
end
language 'sr' do
sha256 '0a0af0586aae6ca94e82205457996863917705538bb3468f4d6e4cd3d57dec06'
'sr'
end
language 'ss' do
sha256 '0ee66c01f800f51499bb933436b490255383d844bcf8e3d5fcc7a4fbddcd62e8'
'ss'
end
language 'st' do
sha256 '00a9ed34ae45c863a964ef45c6cbb543ec0809126f3f21bd595269e7694a2c78'
'st'
end
language 'sv' do
sha256 '1fc792ba78f70c6c66c1be8f3f08e818aec76b4b7452186afedcc9e955887b7f'
'sv'
end
language 'sw-TZ' do
sha256 'e2b86a79be8e88183ae9fe45cb5773433e9414a4032729f4d800f36367df3e80'
'sw-TZ'
end
language 'ta' do
sha256 '4cf3cc7242c45bba30222cad06d38cae38a4bdb1a944fb7f28f932176dd14fd7'
'ta'
end
language 'te' do
sha256 '76fb2aa8707e9a92ae5a0090356351c6d1065f98ef3670c2e92a6eea8dc35eaa'
'te'
end
language 'tg' do
sha256 '7330b3e1d3c2c40a6ce880a70742cdf20609af33b2d458c5ac020a32afa97d2e'
'tg'
end
language 'th' do
sha256 'b7d239cb94e7aacf6bb7aeb472714692e99044b8211296574272daa74835ed91'
'th'
end
language 'tn' do
sha256 '9d815c2d3e1d33ce24116ccbf4b599114760bca0b05e76e9297fc27d8f428534'
'tn'
end
language 'tr' do
sha256 '929e9ecc18c6531131ec323245ee2508be2a0164abd7461631fba26e11750836'
'tr'
end
language 'ts' do
sha256 'b892a880b32f912c88519ce255f0780db3d8e91bdb0dac3c03f6f4301660970f'
'ts'
end
language 'tt' do
sha256 '72b4eb11dae315a60701db179a0f4fbc77709186e03cbde14d1878298eb3ad52'
'tt'
end
language 'ug' do
sha256 '68819036dd33a1aa47f5378fee1a833b17737bacbe21359d42200f9f3b9a092c'
'ug'
end
language 'uk' do
sha256 '2feeda0d3f950e05b971ebfd6639da67926f75274a0f87880c5bf077d039356a'
'uk'
end
language 'uz' do
sha256 'b4a913160c39ee3b1e85866de48c1fc0b4c699e1a90673a78bf73f9fef489939'
'uz'
end
language 've' do
sha256 'e831cd76da1360666129a51d3edb48d5970deed48a9b5574745e4e40d2bd46c0'
've'
end
language 'vec' do
sha256 '7179b634698ed90e5442663ba58018656ec1335ff80576aef94e2561f628b687'
'vec'
end
language 'vi' do
sha256 '985fdceff434b31650a4a836121b8da6d2496018b6cc8f035e46ff7ec2d90476'
'vi'
end
language 'xh' do
sha256 '0e782ce03156656ee212a0072b1954e0d961a6639abfbab11cbe95dfc2001645'
'xh'
end
language 'zh-CN' do
sha256 'f897ff33346b6c0b9df6ee8718d3fb7365ccd8a31a0e6ed368100fe77d579bbc'
'zh-CN'
end
language 'zh-TW' do
sha256 '1cae7e32c35f9a90739ad5a174fdbb19f6ac21865043ef6c15913b707907bd0f'
'zh-TW'
end
language 'zu' do
sha256 '2c1fe88092fe626eadee307ca7f1eac4113acb84f4bfa8ef04a296f3d647c65c'
'zu'
end
# documentfoundation.org was verified as official when first introduced to the cask
url "http://download.documentfoundation.org/libreoffice/stable/#{version}/mac/x86_64/LibreOffice_#{version}_MacOS_x86-64_langpack_#{language}.dmg"
name 'LibreOffice Language Pack'
homepage 'https://www.libreoffice.org/'
gpg "#{url}.asc", key_id: 'c2839ecad9408fbe9531c3e9f434a1efafeeaea3'
depends_on cask: 'libreoffice'
stage_only true
preflight do
system_command '/usr/bin/tar', args: ['-C', "#{appdir}/LibreOffice.app/", '-xjf', "#{staged_path}/LibreOffice Language Pack.app/Contents/tarball.tar.bz2"]
system_command '/usr/bin/touch', args: ["#{appdir}/LibreOffice.app/Contents/Resources/extensions"]
end
caveats do
<<-EOS.undent
#{token} assumes LibreOffice is installed in #{appdir}. If it is not, you’ll need to run #{staged_path}/LibreOffice Language Pack.app manually.
EOS
end
end
|
cask "libreoffice-language-pack" do
arch = Hardware::CPU.intel? ? "x86-64" : "aarch64"
folder = Hardware::CPU.intel? ? "x86_64" : "aarch64"
version "7.2.2"
if Hardware::CPU.intel?
language "af" do
sha256 "2469d035ce2f17d57af8c4c6102e96101b3be7bb5b2ab7c32ff762b7772de363"
"af"
end
language "am" do
sha256 "4396f54eaaa70918b7858daa317187e759e0a65a88bb96b63cf84bc532f83917"
"am"
end
language "ar" do
sha256 "ec359cc3265bda4b4dd88f6611672a492ee69f9b98a81931611ccc06177670a6"
"ar"
end
language "as" do
sha256 "9f1325584d4cb23229630059c596e2c0d0a405fc203b1307c0cdb186e08adeba"
"as"
end
language "be" do
sha256 "7bc0f8aca120d64135a45f77579aac21211ee6f023cf947ccf8bc8aae1bc0527"
"be"
end
language "bg" do
sha256 "40336e358f7fae1f721e9106795ec2597697973aa680b2dca542d2807395c19d"
"bg"
end
language "bn-IN" do
sha256 "e7b419034fd90b7f20c67a73ac8a5916d61d3d169bbbbc615cbe23614e841128"
"bn-IN"
end
language "bn" do
sha256 "b8c239f556527553f30b4e6290883530f351fdfaaf0005ce1fdda03e2f2bf06b"
"bn"
end
language "bo" do
sha256 "7d2240480abc34326304af1e744a92e16511f56dcbeae2adea49f635876c0662"
"bo"
end
language "br" do
sha256 "a9ce960e8805adbddd2c7df40990110c4fa4f63b1d0cbee6c2ac2c77d4f6ae19"
"br"
end
language "bs" do
sha256 "d1a02bb4c25ea141098fea813476c5aab424aa1d003033737b8b4e2a30079ea6"
"bs"
end
language "ca" do
sha256 "5494550865335108dacef8302d8b3823e86714e3fc3f80a3101ca2e10fea79f3"
"ca"
end
language "cs" do
sha256 "32013d1ae2950436576bc543d07c5d2a72ed43e801a8674dccaf78807d13a590"
"cs"
end
language "cy" do
sha256 "af011916d5184ea7c4239443f945ff3b0408fc73533f97b1133cbe17487e5a9d"
"cy"
end
language "da" do
sha256 "cfe488e528be891cf4e26008123965032a5a92146ed0004cc3027ed7aca234db"
"da"
end
language "de" do
sha256 "1451dd1917677c42c2eea6ffd4c0018f1bdaa08ceb0aefeb606ae721230dc332"
"de"
end
language "dz" do
sha256 "de213de9857a936f8a1fa795e583467e6ce6302dc9b1af305df3078bf27a29f9"
"dz"
end
language "el" do
sha256 "a7ba1bd0a7b75d1cccb82e10141f77c899aea5b15e745feaeb2e11249850f207"
"el"
end
language "en-GB", default: true do
sha256 "d05a192f6cbcd3b84e0f8933deb4eda73ab0a2b548e5148daffa37d14e37c7b2"
"en-GB"
end
language "en-ZA" do
sha256 "f56ede30e265fbf60537c147b2f5417957a3123abb6e2c3968c038f7d0e0d648"
"en-ZA"
end
language "eo" do
sha256 "4bbffd981a83491b8aa6314f0476b2f330627b8f1556afd3bae67b35a232fe67"
"eo"
end
language "es" do
sha256 "25209c05378399d36e6ff897b620fb83df8ace8842ca1efeeba0d00da140b825"
"es"
end
language "et" do
sha256 "b41f5fed488c0b4fbf068cb1072d94fc6ba6c068498340282ff5aec903dd2961"
"et"
end
language "eu" do
sha256 "c219db96d19191a10b5595563d1200ec63719263b97d9660d0e05fd5269ea170"
"eu"
end
language "fa" do
sha256 "06dc151db98a436d5478a0762cc71a26fe94419d0b3c45b4cfee7a1556cce734"
"fa"
end
language "fi" do
sha256 "82cb3dd513cad09023cb6df36b345d93443b5af189758e99e50a883fd57f47eb"
"fi"
end
language "fr" do
sha256 "8b89bf83dc03f2538b43b84e847cae5858d87d3f64c6548c3dd7273f74ff872b"
"fr"
end
language "fy" do
sha256 "d518f2a0bd703fdd66e5f8b16b871ed105a91a4380b0a2c088a1a6a08fd4f799"
"fy"
end
language "ga" do
sha256 "975cf891d0f05386a5e1edb708f8459eb9a97a57b91e8f6899410c10f6255325"
"ga"
end
language "gd" do
sha256 "a7659dcc6c6436946de9e07a6b022ec8a2224432449985caaf4513883fb66853"
"gd"
end
language "gl" do
sha256 "8885e30850aab68bd67847aab58af762a29752fbe5858a72920bdd624cd67220"
"gl"
end
language "gu" do
sha256 "15cf81bc7ec965dad9cb20e5f83f7f0038754c05553e5ddbed637616dfbb906c"
"gu"
end
language "he" do
sha256 "4409e9ed4c2875379558db1e658e07de7bae3f2a22376707b796f78e81fddc1d"
"he"
end
language "hi" do
sha256 "bc1b18ce8429c16f56f460472a2d0d9787d883d9b6c96d7d8cbb3b2d9ddc8929"
"hi"
end
language "hr" do
sha256 "19f108ec4f61ca95bc4d2708d9d76366b7ef21b0d4531016d37d486fb214f2e0"
"hr"
end
language "hu" do
sha256 "6ddfcbf41b0192acebb9ca1689cd42e215eba22fd332aaec286f54ee149f9684"
"hu"
end
language "id" do
sha256 "f6b0f3f6d69dde362f39a836dbfe3f99396bb58a0b5237ca7eb7667cd7c30c3c"
"id"
end
language "is" do
sha256 "0e839e0e138446b8365816c33eb6dae84ee8f7294518723d4f98d4a9a849aa7f"
"is"
end
language "it" do
sha256 "4a8f3c176b0d22438c4e12dd83d9df5b1fe943391094b8c9f68fc0daa4b3c1fa"
"it"
end
language "ja" do
sha256 "76d91e56fb4a0af60d85ab258b1ee2e33d2b80b88c62883e173fd978ec815bc1"
"ja"
end
language "ka" do
sha256 "dcac179efb9dab21cdf74ff2ba3fc89baae3181671d7a97c7148c121b08eb5e7"
"ka"
end
language "kk" do
sha256 "3baf8ca23e1dd323bba4f20d604ec5606aac56a8ba174fda320ad826bf32c83d"
"kk"
end
language "km" do
sha256 "ddf526696b159fb27e17bc0f017a630c9feb2e2336a45cd5450a1c57e0826dde"
"km"
end
language "kn" do
sha256 "870b97ca2a601825317498ee5c22a2863fcaade8c1a78b0d25b3ec9a8cbd3d99"
"kn"
end
language "ko" do
sha256 "451ba46a289ffa7a307cb52063f5dcf96dd2eef6d2a1c8caddb7718e05f77ace"
"ko"
end
language "ks" do
sha256 "7bbae1085bb769edce915dba1502297a9f99f784023b51e2a575aa0eacf5e03e"
"ks"
end
language "lb" do
sha256 "4a5b011e1add79ac876d1c2cb1109c110a84cd688554e7c1df45c3d14a80614e"
"lb"
end
language "lo" do
sha256 "8450e8e92c778cb09e2e009217b1a2d6472b0fe8eaebadee76d8e07058998127"
"lo"
end
language "lt" do
sha256 "60b79b86fc8f915e203515673acd320771107041964de7634dc5d7cfd500fbb9"
"lt"
end
language "lv" do
sha256 "2cacdaa6e4cf8beb58b0cb4677206c7a7611fbc4e48b59769adf289688e35365"
"lv"
end
language "mk" do
sha256 "e4b8ad68ee05935190a755db5648baa07ffccecdeaa7f9319a439d635dc0735f"
"mk"
end
language "ml" do
sha256 "5ef14874df2a9f0fd8f20745c70293817ee2f6d818980c8f3da0899058c28ed6"
"ml"
end
language "mn" do
sha256 "bd9ae00f39b7e012f46d8b3e4f98714d6074bfad247c245f93baeed7e3cb0f8c"
"mn"
end
language "mr" do
sha256 "75492113d15a550ea9fa60f6d8e70ba6e8c97f649c5aa5918d626974db3178d7"
"mr"
end
language "my" do
sha256 "6a648d149b2c2250ac2bbd8c44b38318474e79a2211be827870a3aa6404b6b1e"
"my"
end
language "nb" do
sha256 "b39bd9b026821287bee15b2ed49166be465b8f36284660c0581a9eb39fe4a1ef"
"nb"
end
language "ne" do
sha256 "443fa0bcedcf961b0321e2d63febc19ec3a61454cfa3d9adacc929f20e669d21"
"ne"
end
language "nl" do
sha256 "29e315bd5aad707a01c682e57c3954c49a2e9ea51a514a1987ddf92d111c5993"
"nl"
end
language "nn" do
sha256 "0bd9abee73b21209f7d6228c846de08545e305c2a97ae14a99a8549428c66471"
"nn"
end
language "nr" do
sha256 "9274de4d60122edef2c4c2002b6619db442d87c8d98df07ea44d98c0c6661156"
"nr"
end
language "oc" do
sha256 "1a72f20639780a27ad68ce357c7d83d8ec176bbcdaa724901bafb885226a8ede"
"oc"
end
language "om" do
sha256 "f1581ad9cf06156e15a8c06589d0aa19a1e7306ff74b87ab5a129a204b44f415"
"om"
end
language "or" do
sha256 "a212a56d7c21ef0d5f75f1202b5b8ff537fc9d21aec2de5b258c5eaedf08e435"
"or"
end
language "pa-IN" do
sha256 "381450a92e500fb563104ed9bfc3d3a4a622929f79777af8af598b7ab4dbb269"
"pa-IN"
end
language "pl" do
sha256 "f7f371f9555fc6a9b3fd9db3f288e243c39929a380a7ad2676a9c7a854de7b71"
"pl"
end
language "pt-BR" do
sha256 "9e4ec0dca65867d34106c075db409bd807bf005d700956e7c64773d2d1bb37a8"
"pt-BR"
end
language "pt" do
sha256 "a702f09ec68da5b3d44fa7360466b70b3fd27c9c40f5830e210f2e81c4e58e7b"
"pt"
end
language "ro" do
sha256 "a1ce96edca0c1903e99e417a053c6906c0c9911f6e64450d14f6fdae6fec5fd0"
"ro"
end
language "ru" do
sha256 "78f85663e7cffe1e256c87bcb3133c3214ae54959a7df2137a0071f95f047ce2"
"ru"
end
language "rw" do
sha256 "4c49cf5b2be8fcd58b65f19e3b70855dfe1d735f224a0ba331173efe9c03b55f"
"rw"
end
language "sa-IN" do
sha256 "7ebb73a7645ccad4783b5da2a82913e9c59207ba95042843ffe6e406a90e4a57"
"sa-IN"
end
language "sd" do
sha256 "c12dac0c20698a781484ca15c2498888d19761d5c8d6d4454d272b727f5043a4"
"sd"
end
language "si" do
sha256 "9f04f936e23cc5566acd477da5ec3720e3296d0e7ebf00ef7d5e47ccd643fb88"
"si"
end
language "sk" do
sha256 "327a53fd11fc0a789db9d5652122fc17599555d5167392aab1cf46b7586ec8b5"
"sk"
end
language "sl" do
sha256 "592d5053164ec2af491e56b91448813b735246270def6d76002f72016f1d5762"
"sl"
end
language "sq" do
sha256 "eb7b56eb2ec0886296515d2fa8c73cc580c882786c06fe583e32352a689d984f"
"sq"
end
language "sr" do
sha256 "fd2620b004af326b7eadad1c296676dbcc41e9cc56520388b9edaaac8e5f8981"
"sr"
end
language "ss" do
sha256 "7ae74ee503ff2593306c8efe47eb377b5069f69ef8fcbb765daa672c58301dcd"
"ss"
end
language "st" do
sha256 "6ad77b23b08d485ed6ab35284e6cbf9be244f9658277a1afed2ba505dc064d31"
"st"
end
language "sv" do
sha256 "772a69d687e16a4e8560150db27405e35b099190d7b09017951aa12a4c2e433e"
"sv"
end
language "sw-TZ" do
sha256 "41fae2dd59529c089a9d3e895ad6b42bb34da39f157a0e9892ce61dfab44c29c"
"sw-TZ"
end
language "ta" do
sha256 "d5eb73ac7469befa016009342f498eb682be2bbed0f1c1c7c3555710236d8cf4"
"ta"
end
language "te" do
sha256 "e61d1f1783b7126e7bc4fd591eaacb4ae9dcefd37e314478856de45f6f3a55f6"
"te"
end
language "tg" do
sha256 "12716465191afcc5383568d8573df62d92279f66e2d8e4fb9b445ccfc808137f"
"tg"
end
language "th" do
sha256 "6ed6415e9f49bce78c891c9bf90da38590fb540c428d13eaf6a1418abd2f898f"
"th"
end
language "tn" do
sha256 "70c22a63586937ecf4425e66f08546783bd106bd73056abcd3733dc602c8c25d"
"tn"
end
language "tr" do
sha256 "2b9e45a3add31a1f442450bc0702e57a2b04d7b84abc6bac94237145f278d2b5"
"tr"
end
language "ts" do
sha256 "8dcbfa48c207fae7787db97f8ea90f0da352a24689acbb59eabd980db83a4d6f"
"ts"
end
language "tt" do
sha256 "bb1e138c53c39c1e8960922e69010decb0adc6c4b14c86c550a25c8b6c90b1b3"
"tt"
end
language "ug" do
sha256 "4ac55fcb890d970057bb37305d437aac80ace396c060b0cc47f0f4e325c1c1e6"
"ug"
end
language "uk" do
sha256 "311aed0d9fa15c1fdc0982283b574e3920c1f4290f2ae9fa1409c2e4566fbf3e"
"uk"
end
language "uz" do
sha256 "73f2f5ef2353c65c3ebd33beb0321072a7261cca11b8b5e39bdf6bdc40deb1f1"
"uz"
end
language "ve" do
sha256 "d6d38172f8d6f15d794d8e00262843ee669339fdc529d05d4eab066d0509d619"
"ve"
end
language "vi" do
sha256 "905c072b6f1c24e0baf84ceaba528d4296c48ae36f08f06ad8298da9aec163a1"
"vi"
end
language "xh" do
sha256 "e0f27e96ee41430875ed9a2824b18f33518b0933f8e873707f244c7c1a61a90c"
"xh"
end
language "zh-CN" do
sha256 "87d16eae720d09866eeaef2e4d7ef484e4bc07340f8fac2a7812807cb0737b8b"
"zh-CN"
end
language "zh-TW" do
sha256 "038093665b07aeac258f8f1de489d57f641bf91c57a2f35e3e710335df6390bd"
"zh-TW"
end
language "zu" do
sha256 "2a7cc99d24e40b1f621b27cf9f55635d31d702f9c65c7a82e173f95343500d6e"
"zu"
end
else
language "af" do
sha256 "7b606105b03e422182617ced13c6ae7a7d6bfee8ab9a37f51a42787c879a4747"
"af"
end
language "am" do
sha256 "9c93a77e319e264618f75b8e0bae19b4e4b21d488d2b0b964377c912fbb25fa7"
"am"
end
language "ar" do
sha256 "118c5bef9f1532717900a597f6b64e2d51ef3e4ccaf02e6d3ad5d08c15c10a4d"
"ar"
end
language "as" do
sha256 "76ed1f13c84d55f2b9579663eddff4cc34e078502568b58216d529775df84da9"
"as"
end
language "be" do
sha256 "9fa13e3cabf658dba7c1da55bb99d2942530fdea3220d0ea9cf10139243d1ce0"
"be"
end
language "bg" do
sha256 "f111e494659d6df5f3dfd31f5334ef2870895009377fc34064ade0897abdb767"
"bg"
end
language "bn-IN" do
sha256 "be5320215832f506579e7e8c2ccb123aaeb704a265bf6f0ec4ea97be35387202"
"bn-IN"
end
language "bn" do
sha256 "67911f32a92e3bac177e94c005978525536cc84a449dfb78e0d0c779ffee1fea"
"bn"
end
language "bo" do
sha256 "dc2e5dbd89d0fda2b21361b520afe4d73156ce9dede10e82fb32e51dd818cd76"
"bo"
end
language "br" do
sha256 "d83c52a272eb972f118ec398175d64cc4137c44aadc4efe85dbaef26c578f2e0"
"br"
end
language "bs" do
sha256 "035c622ff7adfe29bfbbb3d0e51c81722c18266df9f9581efbd00632b5eed572"
"bs"
end
language "ca" do
sha256 "3d194afaa1ba8d9770f3d88f3e2c0e01135f1b545ae34ad4c85756176f18ff46"
"ca"
end
language "cs" do
sha256 "163dbde697416491783c505056f29a8cd60994c9359e185b7c28fba0a8c41d63"
"cs"
end
language "cy" do
sha256 "b4f42fefd8ea15f8bc920c8cdea17edc6734b4401b8f32512c041c8f62f0ed2d"
"cy"
end
language "da" do
sha256 "6329875d4a4e23385543fe5df6d0b3c2846b8b2d5dbf481647beb243e4d0af67"
"da"
end
language "de" do
sha256 "e7ae3f2bd6f03bcf789cb726a7104cf504230313bd93c3fc0e8e34e3f8d3eed2"
"de"
end
language "dz" do
sha256 "6fe2ff773f0018c3281926646c021ef5cdf01fb328e80679cad0b1bba9af5787"
"dz"
end
language "el" do
sha256 "745b7541e14831694772a7cb61e7d40b6f2b24568d686598794ad542c588eca5"
"el"
end
language "en-GB", default: true do
sha256 "f853d9fd01a2f057d838bc61b9a90d3f70c855518039ecaca89c6321fcc064b6"
"en-GB"
end
language "en-ZA" do
sha256 "72dab95cad59363dd5f54e78b7a04ae6825b123e764d6940ae2251d31f9a78f8"
"en-ZA"
end
language "eo" do
sha256 "eb9bc4abffc646668336d4cd68ef5f0611723f27e40898c7ef19376e47e77276"
"eo"
end
language "es" do
sha256 "8b4468130450cf0fed24d3fc501ff611a1624f2140ba1c7f23da9ce71cd82261"
"es"
end
language "et" do
sha256 "0ce798f2df48ab0c105de692ab7f5a09d9cd25e268d576499c2c2e25b8f1fcbc"
"et"
end
language "eu" do
sha256 "202b120ef8bf6f853570655dc6b91a4e5737bb81a5c9e256a9e04285d74d74ae"
"eu"
end
language "fa" do
sha256 "68174e0d2779b93cce6ce9b4438de74c7e602c2c1261164442078fc5a98db954"
"fa"
end
language "fi" do
sha256 "6dc2f14662ee4cc135f75e48ce70e182e9b767fbad2cc9fbb0dfb76735d05949"
"fi"
end
language "fr" do
sha256 "65658c9bfa1cc44044b9baefcf5ebad5b7067a4bf160757096685a4df0932427"
"fr"
end
language "fy" do
sha256 "acb63eec4704c382a095251bd7d0296d1dec4eb38a7251211d446e65b0e0d44a"
"fy"
end
language "ga" do
sha256 "1ca6c5d1a699367628146c07533b6305bbdaffc436e48d718b61a687b4e6662e"
"ga"
end
language "gd" do
sha256 "2318fab5ede7fba39e433870f59c006a01acabbebba03088c24f9031032935a5"
"gd"
end
language "gl" do
sha256 "7ec88634f670292cf06239e678fc713efa95b821da781da81741ab66d7a7dcbf"
"gl"
end
language "gu" do
sha256 "2f9ae9ca5c950c1d5861925bccdaf50e2ecd2776da8e78df9f0dc0b06f479bc2"
"gu"
end
language "he" do
sha256 "1885adc77fb6dbe1b19de8a8780db0ba94fc868c3737e4ccf935e73ded454e43"
"he"
end
language "hi" do
sha256 "80c98a8b806436200b39a507c3c401f87bab82baf0296049286fda293756f55c"
"hi"
end
language "hr" do
sha256 "3fdd3c7739c382894aeff89f39d7e60472607aa28862fc5afee1e0346189c921"
"hr"
end
language "hu" do
sha256 "b539a3ee8f7f79dab5da865c50e1ba4b892a7c8a7b22cc4f3f799b861d583f46"
"hu"
end
language "id" do
sha256 "562ac15b9515c4c761ee48f1342a43b785433be1f605e94584d306171a6b393e"
"id"
end
language "is" do
sha256 "45ec525f2ae18ebd691930d51675df3b7cbc358714843288f7101f59630214f8"
"is"
end
language "it" do
sha256 "79102949e642179b6e0684373c3e7b9f8a5fe5fe51796d6e808e312529349094"
"it"
end
language "ja" do
sha256 "b8455e4e06401905757eb520323e4e3ed07963d7a74085785f9f32a533f182a2"
"ja"
end
language "ka" do
sha256 "b0d2cf10d468fce94eb798ad69a4528aa9ac7f4c2ae179ad4581aa6e3b18fc10"
"ka"
end
language "kk" do
sha256 "32682e633f2052f73e04a25151cb24f8b73380ddf1c3ac1f851d83e89bb683f0"
"kk"
end
language "km" do
sha256 "7afec34b8fb7d26f0fdd3b328d6a793e3bec7742af1e4f0355a64691f0996d7f"
"km"
end
language "kn" do
sha256 "760396e2daf5bbab407b2385ad8abb59f576894e087b3889d96ead86230596b4"
"kn"
end
language "ko" do
sha256 "94dae9d2cd800a35db7a759e3605de0164e98dd39276a77287746671e88121de"
"ko"
end
language "ks" do
sha256 "c07bde8538762296ffaf83300322ada455f4e8b3fcd4679047759e773b1ffe81"
"ks"
end
language "lb" do
sha256 "061223ca522443ce0b5deb50b360dcc1910922eec7916bdcb7d01766c4a71bfc"
"lb"
end
language "lo" do
sha256 "2be39bbd48b8b11d5e7d2f67daf981e2133d0409e13606b75788745e96fce954"
"lo"
end
language "lt" do
sha256 "dc1f45a873569ea34f58fe56c94cfb67c18205239f5a3e5a30460aab876116bf"
"lt"
end
language "lv" do
sha256 "a19cb7f6cff87c88785f555561eac340115e859688c3500f1277a421716b6746"
"lv"
end
language "mk" do
sha256 "a0ed9f8e0e0527ee15f87f07efdc67fdd2f4e736e53b364737cc0f02369a1f34"
"mk"
end
language "ml" do
sha256 "dbbddac966b1a57c72a82e0b46f05532d408ad8d9b632f1898803a58dba6101e"
"ml"
end
language "mn" do
sha256 "d46873e9d6bc0a68fca53764858933a0d1d989680b35b0fa24e1a005f437e75d"
"mn"
end
language "mr" do
sha256 "659a6e17280cf36a090b6031699f06113aaefe6c5eff53a873890ae452409f08"
"mr"
end
language "my" do
sha256 "036cd1b936c152ae237f5403de81d5706c93976ffebdfd1518922c1c3f2d5db7"
"my"
end
language "nb" do
sha256 "b46cc26c541a0d8d061bf918fc4b4db033192a5a3bd628e5a74b40943f9dc405"
"nb"
end
language "ne" do
sha256 "e14c6357af0120214576f2991f88625372c4a68ff8ee6662131ed3a9e07be4eb"
"ne"
end
language "nl" do
sha256 "b3706c3fa8810c289ddb8ae3e5cc03b17573df960a55e0d39d14a6736686ecdf"
"nl"
end
language "nn" do
sha256 "e9f4f4bef9b6a6b12b32f6b1083dfb9cbf5b4a1e89fa4f9a65749ce7e4a33442"
"nn"
end
language "nr" do
sha256 "5b29711310d435b16cc461f7c529623e94e97140cf1a1c5172d02459f6c79d5c"
"nr"
end
language "oc" do
sha256 "8140580583cdb2ab58f211dae9bc51e2cc95a800daf9aece1045d89697bce0ec"
"oc"
end
language "om" do
sha256 "b4ddfa77c50ae446d6c1164f75e3e290b74b8796132ec69336cc3bdfe243010c"
"om"
end
language "or" do
sha256 "864e6ea55f57166f30b034ad8438837b9e5ed9e7dc68e346bd90b40e820533d6"
"or"
end
language "pa-IN" do
sha256 "49dadb68675a7178ea2fb8f257fef324a51acebddea6d331490c8e700d6506ef"
"pa-IN"
end
language "pl" do
sha256 "736548263e7a93a3d79b6f745c655b3c91249ff049b36b3b48a6cbe1b5c1d415"
"pl"
end
language "pt-BR" do
sha256 "27abe1b5b067bb769026f5aa0b355bd3bb51f07c69819ffc41ba72e00d63ec6e"
"pt-BR"
end
language "pt" do
sha256 "def14348ddf8dc044141b9f82d56048a32244c3bba06456c1ced11523542a6e0"
"pt"
end
language "ro" do
sha256 "02a5d42dbf492ed3bcefb4235d7bd51b842d43f137ced0c402695c43125d957d"
"ro"
end
language "ru" do
sha256 "a1cd43d033f051cf42ece1d1b7a92d7002ebeac5e4ab15a8ac180255cf292cc6"
"ru"
end
language "rw" do
sha256 "00cf34b9b5081b9bb93a1d652d201263ab89a61869de4162bd4101960c36ac35"
"rw"
end
language "sa-IN" do
sha256 "1898883d99fed4ae5f510634e524b4e323ab21b1de4bb11406640a0c7b7c4c5f"
"sa-IN"
end
language "sd" do
sha256 "74f4d0da3267701564a5e911fd5d6b893bf5611b2de5fb861926201c3ed8a6e7"
"sd"
end
language "si" do
sha256 "c7823e5224a4b3f83fa568262d31207e2df9a1bef7167e9ba6a22e227c43552c"
"si"
end
language "sk" do
sha256 "e3f70fb63b02838d4cb6d7a669cffc0589cfaf21ac4c1019ecb130a36818a7ab"
"sk"
end
language "sl" do
sha256 "14208ab0acb98cb8cc805bac7a8051221cfddd388a2a8b6c739f8f7026cfb8c9"
"sl"
end
language "sq" do
sha256 "e0d683d7d937cbdf21eb7160584de733b864f6e09e84519c2f14b58bbee06e87"
"sq"
end
language "sr" do
sha256 "e078240875d57c3027951e11badd5d799beff87042d1b019e2ac966878375222"
"sr"
end
language "ss" do
sha256 "28823e775422092dfdcb2664655b99a0456cb41dc2c4cd36351d8493536e2efd"
"ss"
end
language "st" do
sha256 "43e07a7daa9081e194e69e087ed06881443def8b7c3c49c1e92700d51e6a7624"
"st"
end
language "sv" do
sha256 "570e08efc364cd32f1d693d7698e0aee32a75905a5085b74ae0d2b8d563b9eef"
"sv"
end
language "sw-TZ" do
sha256 "e36b08dcaf9fe541ae18463689f4af1bd2314d227ecee005e1e1d25c25d7cf18"
"sw-TZ"
end
language "ta" do
sha256 "8343abd2565154692b0d3975d132a7a86680d28d4f1b2a4cd35a75cf2e229ba7"
"ta"
end
language "te" do
sha256 "13f4915701221f98293b91fcf811b44ddbdc5591bd5f7d7e27debe19261a7952"
"te"
end
language "tg" do
sha256 "f9600b59b9797003651a1fb1e5552333683758481f91e1e35ae7c107d62f4fd2"
"tg"
end
language "th" do
sha256 "bc328061b6c8999e74c76285dbb5e4f5a385bac91c022fe370f3bb7e0e1e9213"
"th"
end
language "tn" do
sha256 "4e48df1cf916f1cb0792ecf1e88271b53488426fad767725abbbeaade5678a85"
"tn"
end
language "tr" do
sha256 "7f76f4f8d0b982b507d48bb0600e4e34f655db00376fdfbb8ecb6b85dbdc0d5e"
"tr"
end
language "ts" do
sha256 "6423ee49fc1c8dc67bd7a0f305b30de15841ee255d1288a9aa23fe1303c0d0d8"
"ts"
end
language "tt" do
sha256 "6a9168c8d3b44128b8b1b528050f6f0ec22b598f0200563f9bcc7a573aed3620"
"tt"
end
language "ug" do
sha256 "71c4bb59708d485f585d694d06ee84cee17f08e4b0ea1a7af7e642cf8ba9424e"
"ug"
end
language "uk" do
sha256 "0e3f8b055e55319bf407e0589f537d9adb969d4d151468854276e061ef70be9b"
"uk"
end
language "uz" do
sha256 "ffaa139cb01a6edee39d851dcee218e2a5c16f10fbc5c6db83e564c6498af695"
"uz"
end
language "ve" do
sha256 "82c80a1a9ff0ce69fa53c0b78e93387a72e56755b259d2182331859f09cceb72"
"ve"
end
language "vi" do
sha256 "a3b70ab7c9325f02d8c35d6904df27626f307fcf8bdfe2f19c9d6513c4fecbed"
"vi"
end
language "xh" do
sha256 "497cb6b02894944b0d462cb11c86a5feb6f7d885bcee13bea4272523388efe9e"
"xh"
end
language "zh-CN" do
sha256 "686ba348bd4defe6b9b723df1e9a4b6a668adc0b84d14130238e809c47a7e8a5"
"zh-CN"
end
language "zh-TW" do
sha256 "51c7a90e2c4c50130cea86615131f16079f6dd1cb9e5564d02c32e1e6a0f3609"
"zh-TW"
end
language "zu" do
sha256 "f3be827d60fe08a60d2fd86a235afc56ddacdc6eb790608205dc2759e51cb09e"
"zu"
end
end
url "https://download.documentfoundation.org/libreoffice/stable/#{version}/mac/#{folder}/LibreOffice_#{version}_MacOS_#{arch}_langpack_#{language}.dmg",
verified: "download.documentfoundation.org/libreoffice/stable/"
name "LibreOffice Language Pack"
desc "Collection of alternate languages for LibreOffice"
homepage "https://www.libreoffice.org/"
livecheck do
url "https://download.documentfoundation.org/libreoffice/stable/"
strategy :page_match
regex(%r{href="(\d+(?:\.\d+)*)/"}i)
end
depends_on cask: "libreoffice"
depends_on macos: ">= :yosemite"
installer manual: "LibreOffice Language Pack.app"
# Not actually necessary, since it would be deleted anyway.
# It is present to make clear an uninstall was not forgotten
# and that for this cask it is indeed this simple.
# See https://github.com/Homebrew/homebrew-cask/pull/52893
uninstall delete: "#{staged_path}/#{token}"
end
Update libreoffice-language-pack from 7.2.2 to 7.2.3 (#114926)
* Update libreoffice-language-pack from 7.2.2 to 7.2.3
Signed-off-by: Yurii Kolesnykov <dc76e9f0c0006e8f919e0c515c66dbba3982f785@yurikoles.com>
* Update libreoffice-language-pack.rb
Co-authored-by: Miccal Matthews <a53b0df86fcdccc56e90f3003dd9230c49f140c6@gmail.com>
cask "libreoffice-language-pack" do
arch = Hardware::CPU.intel? ? "x86-64" : "aarch64"
folder = Hardware::CPU.intel? ? "x86_64" : "aarch64"
version "7.2.3"
if Hardware::CPU.intel?
language "af" do
sha256 "bc45db8d41f2084f2182b6af1615e1dfe8892113db2f347e56936c46f41c1afe"
"af"
end
language "am" do
sha256 "acfb700f50da9d7ddc6f2de21d7de920fb4228ef93d6079244b43da9fbab8842"
"am"
end
language "ar" do
sha256 "06e4719fe7d3320265eeb5bd680312811368721d4d33e56de5e67b3f1b5efc2c"
"ar"
end
language "as" do
sha256 "d81660a7f27b428e5ba8ab163464161d9228fda6553805a55b7168d58b807c70"
"as"
end
language "be" do
sha256 "435ecb3579d52cae991debc7895c55a7caf6f1ca2892e2234dc3b988d4dcf7b1"
"be"
end
language "bg" do
sha256 "ea876cada7dc10d3c56095bbe365cdfff3566e8f90370f3d009112f349582c23"
"bg"
end
language "bn-IN" do
sha256 "0cb893459deac6051e99b81ccfd358664aae81df8cd72715d78c60079d01d849"
"bn-IN"
end
language "bn" do
sha256 "663d563647a22395e3d1decbb99ac7b54eee6390956e4017c0223e6ec9e89ad7"
"bn"
end
language "bo" do
sha256 "d868d92d0f9a2c5caf35f0ae6905d53a523c0ae43cd828f4a1ebe31aaa23a740"
"bo"
end
language "br" do
sha256 "2c70d859dae499a4a454914a1a798443979294ce665b2cd4429518c75a12aead"
"br"
end
language "bs" do
sha256 "4f5c7c4e171b5b969f6e437ddee4fa056212aa369dc82129f46f1838ee5924a3"
"bs"
end
language "ca" do
sha256 "c4c2dcc540e53cac97e96465388c149cee1b6d9e64fe76337c92fcc7799012a7"
"ca"
end
language "cs" do
sha256 "6e4d96fe7790f7c54cfc220602535e598aa97a350dc5ed9dc39e483312d93376"
"cs"
end
language "cy" do
sha256 "6b736a26b667dabac9bea1321775a3320fe9df3a3c7a05eb0336ea15771459e3"
"cy"
end
language "da" do
sha256 "30e46a75221b180192a1f03aad7270fdbadbbe36865bfc2c081ecc72a2a0c0e4"
"da"
end
language "de" do
sha256 "36e8ba49d2fd68b8bed4def4557cc5d50557fefcebd18bb119822e1259c5abba"
"de"
end
language "dz" do
sha256 "31f356d09084828eacd358251d35c2bdb3e1a747b6f3c052aacde2c9b6ddf52a"
"dz"
end
language "el" do
sha256 "82de51600238dc23ca6d90a134339d91ffd1af970e1441cb6c9b2ac1f20f4b1c"
"el"
end
language "en-GB", default: true do
sha256 "1f22197403c31431638db8eeb4ce79d64b30f2e907f66a9833901292aa3b008e"
"en-GB"
end
language "en-ZA" do
sha256 "6e47313f99c69ece43729e80f2977a5c0cbb9ef752a5755d7027e60e9b37c3e2"
"en-ZA"
end
language "eo" do
sha256 "4960b7e994cd068267484619d316a1b3c6ee83e64b56fb185c35be7ac1623861"
"eo"
end
language "es" do
sha256 "34d933ad556a2c7c2e34bd38f87c369ff0b30cb315f7781728f3378791ca127c"
"es"
end
language "et" do
sha256 "6d13de486b11e5c56e6d929f308ec505acc7faf93cad2f2c4f77527d81480bde"
"et"
end
language "eu" do
sha256 "44e747ec6dcaadfd6d80eace730ed0e89d9b858b6ff666bca012b05af287f8ce"
"eu"
end
language "fa" do
sha256 "dc99a61c0755699bf4ee2b3d7a01fd945ca1d360ea3126e94093d658b561ee2b"
"fa"
end
language "fi" do
sha256 "92cac1130398a12da80e177206633ea95a7d48cbe100725d7b99ef9f5017c555"
"fi"
end
language "fr" do
sha256 "c3b45c01002a1975f4f360e146eb78971446943115e88cfae72bd9973dccbc53"
"fr"
end
language "fy" do
sha256 "dfb39be7ed3f9574cf9c01d0187b76e4abee696cc832fda08872b598151d6b55"
"fy"
end
language "ga" do
sha256 "723a558425e72a760c8c2df24ea981d430d8ecefda071df4857ce4d6791652a0"
"ga"
end
language "gd" do
sha256 "2ba93bb11f383c787634354cb0544138c28e952bfdfead22414badbe3102eb03"
"gd"
end
language "gl" do
sha256 "46336c339bada02d810f18cf8aadc66d15105ca6763b4e3145c22bde657aba86"
"gl"
end
language "gu" do
sha256 "1de35867c1b234d72caefd7d246125cd05ded9591aa2a2f6c99f5a46819a7535"
"gu"
end
language "he" do
sha256 "94a7df39ed2aac8aa10bb59302381f71b1b3007b9cc5532b9a288849f9968686"
"he"
end
language "hi" do
sha256 "76568d41ad823ef77d42e432fec8151bbde3cf71c8da91ee8bedd650318cc056"
"hi"
end
language "hr" do
sha256 "a109b79269f4e677a0646e53c996c375fd6d029e6016c6ff9f8440ef91a44ba1"
"hr"
end
language "hu" do
sha256 "e40b20eda534d0cc59636d3bd03aa10eaed5a566e8fdf682f717b28f525beb14"
"hu"
end
language "id" do
sha256 "44c67f51a50083c07f8960e1684d0d815bae799ce14c45b08649c169ff1e5666"
"id"
end
language "is" do
sha256 "2175db63c92003776b2b6207bf24426ecf5f5b8febfa975e804da2b52396b16e"
"is"
end
language "it" do
sha256 "44da5182261dbde72e581aa30dfacdae7a78f262a76d6c6015cab39c9d92836a"
"it"
end
language "ja" do
sha256 "6fb36ba5997b2e090f7d6fc19bb4a0530973aff01ef848533841648234b4dbc5"
"ja"
end
language "ka" do
sha256 "8d0577fb3f138ff8693cd2da415059a21171f7dfb79385aff22d9f6342b56a40"
"ka"
end
language "kk" do
sha256 "706b5878890c2522dd37e871c8f6a5179ac2e5452218fe97912391dfe3584d3d"
"kk"
end
language "km" do
sha256 "146dcc6160378a5dcd8cfb7a5f79e32634da5acfaec36d316e4f8404fc13fb5f"
"km"
end
language "kn" do
sha256 "040d3d45b2cb9fe5cccc13c773b88272d5059f4794c1f1da5d0ff50a974a98f8"
"kn"
end
language "ko" do
sha256 "ad2520f630f233e59673751f18ca520f1a6cbb20b1dfcd559314a57f941dfb87"
"ko"
end
language "ks" do
sha256 "6789d06ddbbc308deab8892a537865d284887cd68879a4b23cd384335ff4c710"
"ks"
end
language "lb" do
sha256 "8ef2aa4c7fc85c13d166452f1331d750815a35a39b420baa9ef12d4a28c134b2"
"lb"
end
language "lo" do
sha256 "4288e74309930450d0ad048365e336627865d42f136e44089ad9145c938295ae"
"lo"
end
language "lt" do
sha256 "52e484b92cafa42a79b30b9479a5165d73c3832ebf29fac82fda8eb8934b350b"
"lt"
end
language "lv" do
sha256 "e2bf05b18c49a789151b5e133bae8a09a6d3e3e79ab0f2b8d572ab371e667af9"
"lv"
end
language "mk" do
sha256 "e13d3261b80eb75fbccaaa08fee2735279f08616948ea9298283110557d8194e"
"mk"
end
language "ml" do
sha256 "88163b0f1c88c21e3814de5752bfb62712d75f6d18b0dc6f4adc6177c7fd751e"
"ml"
end
language "mn" do
sha256 "8516001f3addae4d0a64cb70d434cb5007a8f37ab637df19298dd6a669be1e52"
"mn"
end
language "mr" do
sha256 "e54a625af3bf1dc2a934c9cdd0d2f68e07e908bdbcf47e120818995d8f312fa6"
"mr"
end
language "my" do
sha256 "98b1b52b2dc70c071b404db515e6fdc0c8b41409445ebd59595fa0fb7ca073e8"
"my"
end
language "nb" do
sha256 "6054465c9d34645172d2134910576cf880e35054ec8416d02798185ea5b397e7"
"nb"
end
language "ne" do
sha256 "6e5246a752516a38ff772e3cfca7337fe275fd82b8741b3ab2fd5da78aded0a2"
"ne"
end
language "nl" do
sha256 "fcf6e63d7717d6bef309941fa9d80aa5b0ad256281b69d9bfd99d8735d31ffdd"
"nl"
end
language "nn" do
sha256 "57fe70eef070634e727b57a4348ec3cfb5eca47f7228c0eca61630493315f83d"
"nn"
end
language "nr" do
sha256 "0b441d58f830ac5cb5f5b180991593ba34855bfd89bc1a0645117bcc53023cd1"
"nr"
end
language "oc" do
sha256 "306ae585845ccfcd68c4495bc16034a235ee8015ebc93a83381e382db64f0a80"
"oc"
end
language "om" do
sha256 "3c4bf0c28dfdaa0dc7fe786619fe848c969c2b5f7494d61499d6cdfefcfe8d5f"
"om"
end
language "or" do
sha256 "80daa1b111a6cac103846eb50f8248a10689681126ce0051f75653467506c2d5"
"or"
end
language "pa-IN" do
sha256 "c4761286398ddb81d5e8f733344052066fd09000178e5df770193ca89f8b6645"
"pa-IN"
end
language "pl" do
sha256 "b93600659a2bfe6b408e071d9492a63307defacf5d10c0abac1836178bf662d0"
"pl"
end
language "pt-BR" do
sha256 "3895b55712f1e3230e2f1a196f5dbed8ac28d7fefac2caaf356263148ecba837"
"pt-BR"
end
language "pt" do
sha256 "e432bf08b96189ddbe31a0a1652216adc9e93f3a45649a9b38c2921a69ac7cd4"
"pt"
end
language "ro" do
sha256 "bf26ed16946b7eae2f8e34d1e065fa8780a62057e5601a9b25daa410e805ac51"
"ro"
end
language "ru" do
sha256 "1e2cb477ada20c3137415130b61bac28cbae9e28c1a7c34504972203ff36347c"
"ru"
end
language "rw" do
sha256 "cf8b4209ea6099f0a59d577e7ca25d1f9616cf2858e439dbc53e49ced8c9ddf8"
"rw"
end
language "sa-IN" do
sha256 "255e030581faa327faed2dce531ff9b500b3d560038686b8e8607bfdfd8940bb"
"sa-IN"
end
language "sd" do
sha256 "75688cea2e3dd9409b622c439abc978f9e900e49987b4efa9d32048e216156a7"
"sd"
end
language "si" do
sha256 "b07fc8adee3e7e54fb7afdd0bde1e60fa6100a6d5578a236d498e36132b0373c"
"si"
end
language "sk" do
sha256 "2a94bc173720de4be523ef77c4cd7791689e9fa0cc6600dc141a7af788eaa5cb"
"sk"
end
language "sl" do
sha256 "208cb5d7b3b13a6f3237baa79d243129f41d06cf9a998be7c099f901fe637ff9"
"sl"
end
language "sq" do
sha256 "8e0e6687cf8d0b77996091cd554f7dac6b017e3a5199c7d3c2d5166f6d1913b4"
"sq"
end
language "sr" do
sha256 "9c8d54424512702df5e73e4f408f5726e0be6087e2314e32d951b53cce66a964"
"sr"
end
language "ss" do
sha256 "2da7d9437edcab9264c85f7dc5a58ffe9153d91852b0b9676c4c6b2ec705e013"
"ss"
end
language "st" do
sha256 "de2efa2d9a325dff4af750349593fcdb719f4098b539933ee8a946ed7ba5d654"
"st"
end
language "sv" do
sha256 "21a6133357a5bff123008bafffbe23ca8587feca93e19a592529d91f3069b22c"
"sv"
end
language "sw-TZ" do
sha256 "7c5afca1f876f369a6660574ed0dba5d053c09b7969bc4ac61d53112a1bb76bd"
"sw-TZ"
end
language "ta" do
sha256 "38cefeb568743f07a62e927ae38c4f0d904a344419255ddb4a777ea5d9b31afb"
"ta"
end
language "te" do
sha256 "53c2b721016f0ed8dcf087bf4a90cfa304f642bf226e5a80acd59dda0df0c6f9"
"te"
end
language "tg" do
sha256 "767ec9495e4842a61e8991695efc510dcb796fec6159f49f7d8144017d5453b8"
"tg"
end
language "th" do
sha256 "b1e6c96449dc82ee6120b58335969a061f8662df39a0480f70738ae9c1d5a07c"
"th"
end
language "tn" do
sha256 "e16d9b5672ea5097815195e257bd2e7996eb2cef41ce9c189084385913c7cd2d"
"tn"
end
language "tr" do
sha256 "db3c038444a98f5c3e33e24cddd5825a4d34a7418a9e06afab118c2187ad11b7"
"tr"
end
language "ts" do
sha256 "58a83a76d49a6331e59b68093023033f384e884348db9f35660cac6e720f238a"
"ts"
end
language "tt" do
sha256 "5a666fdf5fa15bbd50c9d7e7c0b02080df8008a8031dbeeb205ed55cedaa5810"
"tt"
end
language "ug" do
sha256 "0251eb29aab89587b5d9a193ea6a5917d17c6b9df28304d5a71f3643287bfe7b"
"ug"
end
language "uk" do
sha256 "945f7f7cdcf833a62e304480038adc27ff95f932065ad0be29f413543e828bcb"
"uk"
end
language "uz" do
sha256 "ea97a75a1c3cf11f9df612b79dd998dd35297bc03e224b236706fa97b58ff069"
"uz"
end
language "ve" do
sha256 "a3a723af903642e854fd8bbab255b6a4181107796b31a49258d79d7a2e3977f6"
"ve"
end
language "vi" do
sha256 "03e5c609c005ca4b5d564ea87652bed1f7a0db5062f486cb2f6445abbc2cc19e"
"vi"
end
language "xh" do
sha256 "ccc87267cefb3f29522672f476c3da51a9a0a20db425bf1fff8e10f52b73c7ed"
"xh"
end
language "zh-CN" do
sha256 "78d50883df67f9cabb8fe8d7966760f4ccbad5e20f8d24fe1eeee968b3149198"
"zh-CN"
end
language "zh-TW" do
sha256 "cbdfdfc650ac12993fcfffb42317e744fb354058f6951b66d7c32255887de781"
"zh-TW"
end
language "zu" do
sha256 "303e60ef6ece17ac4b7d989d4bab4e6de69dbb0bfbdf648052d7b8d996faf1e3"
"zu"
end
else
language "af" do
sha256 "b4e8835bc6d88626f4ec8fe23640ec8ab435837af5e40f337070ae6c1a7efca0"
"af"
end
language "am" do
sha256 "3813c369166723ee86bd736598aca2d9f91a99810ef403bd9ae46633835964c9"
"am"
end
language "ar" do
sha256 "b3ca8da94b6bbaba7a5e6aad834817c84cbc588cebd80b01a88c540465a40ead"
"ar"
end
language "as" do
sha256 "3ed1f8293787561ca8bc2db5de049901c9c933f4aa53da66ad9cacd545d09a21"
"as"
end
language "be" do
sha256 "d8eecaf65746ac6f1804f61bbd295b0fb0a755aeb297339add141b9af4cb918c"
"be"
end
language "bg" do
sha256 "0e9a09dae23dc0084f824c15f3fb7b80f9d9747e9dcb0100c6dfb346b76385b4"
"bg"
end
language "bn-IN" do
sha256 "66eddc43082c51a099d462a925fd5c2a1c188d578172556a89e94b0462e91cb6"
"bn-IN"
end
language "bn" do
sha256 "1df15f2da381a8d4c2b4fbf753b933688954348d4ad38a407fd94d57622e1c37"
"bn"
end
language "bo" do
sha256 "97825573fcd30d4616c654aea35ab2006926863af70ca992462a66e9d8224811"
"bo"
end
language "br" do
sha256 "90650357614edfdeda55a00a73cbde6bf3da040bb37d3aaf9bf41c16dcf7cc3f"
"br"
end
language "bs" do
sha256 "2c074fac5624f4b4707d9087df1523b4a3b989edf0f8dac67d3565cf8c973bcf"
"bs"
end
language "ca" do
sha256 "f390262a55e63530e84841c708ee3178bb6c8d80a7703f9682f8af7408bbb4d9"
"ca"
end
language "cs" do
sha256 "1a4bc571314b768f6daf98bee72a522994cfafc1d5dcf891d9ff080222f14c06"
"cs"
end
language "cy" do
sha256 "69260e05452d1ecad6596f4318cd9851ec355adcdcfafc3bc690c9e4de8437f2"
"cy"
end
language "da" do
sha256 "3a099e568f6ef9de4b539fb005c6294a7e450207e45a3ffa9ce240a7266549d4"
"da"
end
language "de" do
sha256 "0ab5f6bc03a5360a6469ecae038296509910427e41748fea6d32ea6c1457170d"
"de"
end
language "dz" do
sha256 "bd4915d11d4f096275fdd714c297d2f361137acd3b8864670a2006d74d18d02b"
"dz"
end
language "el" do
sha256 "2dba158e652e1bdbe22030947e86b4749c0dec516a8ec5053fdbaa3dd9c417f9"
"el"
end
language "en-GB", default: true do
sha256 "fdbd250417c4b0b25e13543984f2d161af853481e0324139f6d6e6815463c977"
"en-GB"
end
language "en-ZA" do
sha256 "9da7ba1082d7aa5d741631eba3a1577603d8b0cd6a547b2eac9e44dbe2205058"
"en-ZA"
end
language "eo" do
sha256 "8344d8862db85318f0e3e9dc74a4881dccbe678577517ee173f98a119b622bd1"
"eo"
end
language "es" do
sha256 "5419cb7eecaba8471f896c81f2d8d72c51a3d5670fbcf83d24376294a43ca73c"
"es"
end
language "et" do
sha256 "e1fabe4d44b1b06bce2bcccb578af6d443e9a575a345d8257497cbb18a3294d4"
"et"
end
language "eu" do
sha256 "9a5908dc6e7ccda6d164a07ed1e1b03fb60b049c88c068e201a7a645ee33528b"
"eu"
end
language "fa" do
sha256 "9bf3dd3e89fa5f9944e49761ff274a35465f39469d1675641ce541e16057d6de"
"fa"
end
language "fi" do
sha256 "e4dc0e57b0e25f8bafab5e9f1a4e7bf6a3a3184af5474adba579317d5fb14298"
"fi"
end
language "fr" do
sha256 "21acb2188a32249431aa7a7035b5986177a6f86fe7e0e82df07dcb084d3f9c6e"
"fr"
end
language "fy" do
sha256 "0487f40510e2a0e0fa56283d80f55457eba1e79a5d8439fdeaf6aafdd9cd3946"
"fy"
end
language "ga" do
sha256 "cce357afbbdbda6f14d1147570c115adae3cbc1685a3432ad648369bb5c10865"
"ga"
end
language "gd" do
sha256 "af2a273733b06b5cc82ff083c32d7ee0c35f1feab96187a86b59cd4e7b9d5f07"
"gd"
end
language "gl" do
sha256 "a371f379a42c9ed6fc4a03f900fc72adff72468705dffcd71d475d66599f7108"
"gl"
end
language "gu" do
sha256 "5cbcb2b4b468d8c516c2c3f63c9f5bded35ba04f904535e45ee53d70959957f9"
"gu"
end
language "he" do
sha256 "e678131a36693a1703b93e3252d48fd4c1716ba3e7010afbfa0967633c8d67b4"
"he"
end
language "hi" do
sha256 "b4d17a09eaa5bd85d31c10bb97a2454bb445a8f1a55808599eb58a9dd96f7eb6"
"hi"
end
language "hr" do
sha256 "c6cd556b8fb2ed88766782f0d5f99f67aae39dde30c08756ee11ead8381ca047"
"hr"
end
language "hu" do
sha256 "bc82d01c0d54172fd774fba79375a3a28f632556ee51d1c07ce765eb1b6ec983"
"hu"
end
language "id" do
sha256 "16680af21e7025b7ca22bea2bdea299a85eb9e128b78f3e06b26d4317cba5b1c"
"id"
end
language "is" do
sha256 "55949b5ee96628bb9a720a777ec966f365c0066f72b0e0712850d770c9802379"
"is"
end
language "it" do
sha256 "c563a1364e9b13351c8dee0ea4dedaf6921d2a8891e8e40a2e82e485528183d0"
"it"
end
language "ja" do
sha256 "71e6698eb04ad5223af728e277bd2577b4fddda76a9b730ff8f1f714d0a9eb7f"
"ja"
end
language "ka" do
sha256 "9e540c2a8d6de75844dc8d6008c895dac7a0b047d80cf71eef8bd35d7fcbcee5"
"ka"
end
language "kk" do
sha256 "e6dae7f4a0de773be86f6deedea8aaec267b669419c7f5d4cb9fdd56069d8ff6"
"kk"
end
language "km" do
sha256 "6b4ef6d9e3bfcd574d424e6ff291149bef7c8782c6d4d1464918dbc6a9387e0f"
"km"
end
language "kn" do
sha256 "37ad006f783c884fad397ab087e729001f180c5fdd7a5b6665153680deb64f1d"
"kn"
end
language "ko" do
sha256 "68e58776fe69e3c8258129428449595627ac6bf6dfa66347709987f621ba3ed3"
"ko"
end
language "ks" do
sha256 "4b37602e64f77a63203032df78bcc41a623b4781556e9e464f47204213636bc7"
"ks"
end
language "lb" do
sha256 "075a01d98750d20a1df9e9edefc26600150e8f86eee8d90ec3f5d9d6456a43e5"
"lb"
end
language "lo" do
sha256 "dd5ce62e8667447c1de3d8ce10bb7796161ebfeb7ee739278b2788fe11425820"
"lo"
end
language "lt" do
sha256 "91ad967b09143f965e1a6110612361dc0f98e69c4438f78c5118162418b4c5d7"
"lt"
end
language "lv" do
sha256 "44347a4de2519bc7cfe7752cb913c2dbf8b970b56f3e042e3a345dd8f93949d2"
"lv"
end
language "mk" do
sha256 "30113d14c318ca4083b3de342f1339cf13aa190c593b1e9f88d90f8c3e0f146c"
"mk"
end
language "ml" do
sha256 "6a4be6bb9d085b236e210b574d51bcdf2e1d0671db78c7249ac4f31367b8a641"
"ml"
end
language "mn" do
sha256 "9b642a77ad8385b201030828765df4e4525d07b2d61b54f33994de184b02eff0"
"mn"
end
language "mr" do
sha256 "d55e8436fdefa85594ae4ee69cc2cdbabd2cb31356a3c076d2e114b190571e5f"
"mr"
end
language "my" do
sha256 "c8626168ab3f1c02eb36a99639dd4500c431254bbd8d82034dfd3592c2b3850c"
"my"
end
language "nb" do
sha256 "5b9770e86dea462f79e02a9d5fb9afa332fc768dd3a585b772559a40f36d65e2"
"nb"
end
language "ne" do
sha256 "7f8a2500f5b411447f99216198bf0735aaff3b877218f12d94f300db6d89113e"
"ne"
end
language "nl" do
sha256 "c0e261d66bd02fb3d4339611cf229318074b65bcd43e75e49980710cf90ee27b"
"nl"
end
language "nn" do
sha256 "4faf6ec14e38b05f10434b2d5f980993304e63354ce7a86e548050b7aed196e0"
"nn"
end
language "nr" do
sha256 "c107f9cf5927c663a032520e1eebfb61cb6ca4231816122f4dcb41ea1076573e"
"nr"
end
language "oc" do
sha256 "59d658b690597f8e2e918fd210db394d526096c56834693d3b18aa1973ad9316"
"oc"
end
language "om" do
sha256 "9cc9a73cf037b8c51558378ccce8cbe9b4d1862990c47eba67b839c54c987fdc"
"om"
end
language "or" do
sha256 "a0eff1a8f564bfb8c32a22c170853df8f5a7672099f2768fec6bdc3c2c11dd94"
"or"
end
language "pa-IN" do
sha256 "721d8b7514533925023264c86028e0a038bb76fd438aa5974571be4f7703d110"
"pa-IN"
end
language "pl" do
sha256 "347e3f1d9e31ffc20a7e950b7f24c5e0bebc4af3e1e3886d6362aa334c261731"
"pl"
end
language "pt-BR" do
sha256 "6941128042435e7552c28e70221da7ad6b7ab6a2c48680bdea0282bf8f685d3d"
"pt-BR"
end
language "pt" do
sha256 "27e1dbc9ccc1598a12a1fb61260cbda985edd6993919ddaea3a6908b93cf2a55"
"pt"
end
language "ro" do
sha256 "67a7ff5a0c4340698c5a70dd654ae2b03578d018fcd70c06cd663a9eb89e49e2"
"ro"
end
language "ru" do
sha256 "b15c84106ea1ede592e13e9cb1a0ba6e7f994b45dc5e9f5ca5cd7150a55e63a5"
"ru"
end
language "rw" do
sha256 "abc484bbe85ca5f5afd41e6c4813e81f124ee77038883e9308a5f683559e711a"
"rw"
end
language "sa-IN" do
sha256 "ab674dd35f7d72531489f0cd46c2a0bf0605b24d3931d1a715eae7d627ad7f49"
"sa-IN"
end
language "sd" do
sha256 "e706f1d85b1ecbbce2f806d6f39922edec0a6c82e891d09f79e131b9535f05da"
"sd"
end
language "si" do
sha256 "a3f80b1ad9b75b99ec5b6a78529e18a2be55d773a0af7a4e2a2a68f1f809d282"
"si"
end
language "sk" do
sha256 "6738d5f3d6628e326c43ad6fef92fdab9723330c8f1477bbc1efe7a514bcbd33"
"sk"
end
language "sl" do
sha256 "b9f75a0ca0c6006ca1f21a123c84fe9b8ea23cd80cf972fcb552d15f64350be2"
"sl"
end
language "sq" do
sha256 "8b605bc9b3b12f57bea1a202d235daf37ba0b3e3ea8c99c76baa6fcb255b3fb7"
"sq"
end
language "sr" do
sha256 "623481c829de709d3ebf0a96cf261af15ebedd615d000176dda46e54067ee1b5"
"sr"
end
language "ss" do
sha256 "5f02bd607bac695e9f6e8da105024096a05f88f29c6b5efc5dcc32d329d9be73"
"ss"
end
language "st" do
sha256 "395ddbb77ac018187663c645abbcbc16760fc27c92a9b36bcd7ef780beb17099"
"st"
end
language "sv" do
sha256 "9f606c6f053fe8386f8655bc6c6c30e5110199a2538aecad37748b2c7c170cba"
"sv"
end
language "sw-TZ" do
sha256 "981fd41645cb0b9265f7e87157e8ff28e1f1565a9c1cda2b5c608ca1b3bb2241"
"sw-TZ"
end
language "ta" do
sha256 "464e33d1c29a612d0cc6b118c9e2838192cbc64b202a2dc1629e50a62482b02d"
"ta"
end
language "te" do
sha256 "61be9de71912c758abb65fc2a918a6e93b2cfcbf0d5f97773e995d45afc4cb75"
"te"
end
language "tg" do
sha256 "5c2b396f81c760e1d1d4964ac273522a7b58c81896a8042383a58b9ca931ad08"
"tg"
end
language "th" do
sha256 "e328b5c3fd2e047827539ff0fe9dfa3754b5d1dbd3e1b8481e51f8f98a076fa4"
"th"
end
language "tn" do
sha256 "3fc7c97ac4f9118358f1bb4232ffd46c28c2d442490faed603e53194f9990e06"
"tn"
end
language "tr" do
sha256 "b8a19eda42d3b0fa7f686e1bd8942173b903f58c859a334e35140316ab904a8e"
"tr"
end
language "ts" do
sha256 "d9ebc4aa9fef19a49a2ff55e7d9c7bf1bdf92754e604a3fca4b26db1c107d5c5"
"ts"
end
language "tt" do
sha256 "37147f1471b6f044933c05d8ffffe7bbf9a6c5d35939d0ced6e0c1f2c5eed2c5"
"tt"
end
language "ug" do
sha256 "4e0e60cc738ad0e7c0a761a3d848a4295446656997f2793e4cab57d78711837e"
"ug"
end
language "uk" do
sha256 "d267ee754ecae2e4a741b362ac5a2cf2bdc3d7c3955b5d14c20468cf1f99e8cd"
"uk"
end
language "uz" do
sha256 "429cb6fca700bd65086404c4fd70c5d68f6accda8d8830273b85901e31913310"
"uz"
end
language "ve" do
sha256 "e8c1a487fb7fda4e7dcd0b6260067020edb2164067e47feea4092fda9f547665"
"ve"
end
language "vi" do
sha256 "4b1c6aeb75c4596becdc22f40bc192672da58f3db10d906d7d9a2d2c144b5a37"
"vi"
end
language "xh" do
sha256 "c83648c3d6912cc1afab16fedbb87ddaaf7fda695bd868af3d412fe9a0f44515"
"xh"
end
language "zh-CN" do
sha256 "e9be08afd75299552255dedbd24be3efbe4546007a014f4bf364bf7ff86cc709"
"zh-CN"
end
language "zh-TW" do
sha256 "c087be2788b0053b0afba792555d36a3065a7b96bbe9b0d6099bb0681890a38b"
"zh-TW"
end
language "zu" do
sha256 "2be00aa99f077600518d4596e64c8a7b72f1942af1caed68d637e3e2fcca49a1"
"zu"
end
end
url "https://download.documentfoundation.org/libreoffice/stable/#{version}/mac/#{folder}/LibreOffice_#{version}_MacOS_#{arch}_langpack_#{language}.dmg",
verified: "download.documentfoundation.org/libreoffice/stable/"
name "LibreOffice Language Pack"
desc "Collection of alternate languages for LibreOffice"
homepage "https://www.libreoffice.org/"
livecheck do
url "https://download.documentfoundation.org/libreoffice/stable/"
strategy :page_match
regex(%r{href="(\d+(?:\.\d+)+)/"}i)
end
depends_on cask: "libreoffice"
depends_on macos: ">= :yosemite"
installer manual: "LibreOffice Language Pack.app"
# Not actually necessary, since it would be deleted anyway.
# It is present to make clear an uninstall was not forgotten
# and that for this cask it is indeed this simple.
# See https://github.com/Homebrew/homebrew-cask/pull/52893
uninstall delete: "#{staged_path}/#{token}"
end
|
cask "safari-technology-preview" do
if MacOS.version <= :catalina
version "111,001-32177-20200728-f459b529-99a7-4707-a85c-e693ddb56eee"
sha256 "f95f72e8cf6a3160fad71411168c8f0eeb805ca1e7a7eec06b6e92d2a0ab6e85"
else
version "111,001-32479-20200728-12c458d1-e348-4ec5-9d55-9e9bad9c805e"
sha256 "6b199cca77be7407f40a62bc1ec576a8751b24da15613dfc0a951ac3d996f45f"
end
url "https://secure-appldnld.apple.com/STP/#{version.after_comma}/SafariTechnologyPreview.dmg"
appcast "https://developer.apple.com/safari/download/"
name "Safari Technology Preview"
homepage "https://developer.apple.com/safari/download/"
auto_updates true
depends_on macos: ">= :catalina"
pkg "Safari Technology Preview.pkg"
uninstall delete: "/Applications/Safari Technology Preview.app"
zap trash: [
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.apple.safaritechnologypreview.sfl*",
"~/Library/Caches/com.apple.SafariTechnologyPreview",
"~/Library/Preferences/com.apple.SafariTechnologyPreview.plist",
"~/Library/SafariTechnologyPreview",
"~/Library/Saved Application State/com.apple.SafariTechnologyPreview.savedState",
"~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.UserRequests.plist",
"~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.WebFeedSubscriptions.plist",
"~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview.plist",
"~/Library/WebKit/com.apple.SafariTechnologyPreview",
]
end
Update safari-technology-preview to 111 (#9478)
cask "safari-technology-preview" do
if MacOS.version <= :catalina
version "112,001-36858-20200817-24aabed5-4c89-4ed0-a1d9-2a50a6b99771"
sha256 "bcf47d0671913cc4e2122a6b54618b620e8c5751c71873e94d2516da065b769e"
else
version "112,001-37237-20200817-e8f512a3-4939-46ec-9404-6e673db90ab0"
sha256 "7729e983a498f45b00bf2e0938085e8b97732b05fb98041960c7ced14082562e"
end
url "https://secure-appldnld.apple.com/STP/#{version.after_comma}/SafariTechnologyPreview.dmg"
appcast "https://developer.apple.com/safari/download/"
name "Safari Technology Preview"
homepage "https://developer.apple.com/safari/download/"
auto_updates true
depends_on macos: ">= :catalina"
pkg "Safari Technology Preview.pkg"
uninstall delete: "/Applications/Safari Technology Preview.app"
zap trash: [
"~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.apple.safaritechnologypreview.sfl*",
"~/Library/Caches/com.apple.SafariTechnologyPreview",
"~/Library/Preferences/com.apple.SafariTechnologyPreview.plist",
"~/Library/SafariTechnologyPreview",
"~/Library/Saved Application State/com.apple.SafariTechnologyPreview.savedState",
"~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.UserRequests.plist",
"~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.WebFeedSubscriptions.plist",
"~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview.plist",
"~/Library/WebKit/com.apple.SafariTechnologyPreview",
]
end
|
cask 'safari-technology-preview' do
version '29'
sha256 'e352cbaa00841ffc0c7492a7d11d68a5dbc4b3c629442e72f0cc71d3a179de63'
url 'https://secure-appldnld.apple.com/STP/091-11341-20170503-44C314F0-2EDB-11E7-93E6-8F282DBC0DB3/SafariTechnologyPreview.dmg'
name 'Safari Technology Preview'
homepage 'https://developer.apple.com/safari/download/'
pkg 'Safari Technology Preview.pkg'
uninstall delete: '/Applications/Safari Technology Preview.app'
zap delete: [
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.apple.safaritechnologypreview.sfl',
'~/Library/Caches/com.apple.SafariTechnologyPreview',
'~/Library/Preferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/SafariTechnologyPreview',
'~/Library/Saved Application State/com.apple.SafariTechnologyPreview.savedState',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.UserRequests.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.WebFeedSubscriptions.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/WebKit/com.apple.SafariTechnologyPreview',
]
end
Update safari-technology-preview to 30 (#3864)
cask 'safari-technology-preview' do
version '30,091-12487-20170517-F2084E30-3A6D-11E7-B9EB-EBFD26FD6CB5'
sha256 '11c5d782f72691a3dfb2d0b328879ec91c2d3a213587ba11ae31488a3ce10476'
url "https://secure-appldnld.apple.com/STP/#{version.after_comma}/SafariTechnologyPreview.dmg"
name 'Safari Technology Preview'
homepage 'https://developer.apple.com/safari/download/'
pkg 'Safari Technology Preview.pkg'
uninstall delete: '/Applications/Safari Technology Preview.app'
zap delete: [
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.apple.safaritechnologypreview.sfl',
'~/Library/Caches/com.apple.SafariTechnologyPreview',
'~/Library/Preferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/SafariTechnologyPreview',
'~/Library/Saved Application State/com.apple.SafariTechnologyPreview.savedState',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.UserRequests.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.WebFeedSubscriptions.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/WebKit/com.apple.SafariTechnologyPreview',
]
end
|
cask 'safari-technology-preview' do
version '44'
if MacOS.version == :sierra
sha256 '022089442e81632d8ef559fca0a54f3337ba67f0f71fceb0671cc41815814ff1'
url 'https://secure-appldnld.apple.com/STP/091-47356-20171115-0BCEE4F0-C97A-11E7-B266-80C0A61DC569/SafariTechnologyPreview.dmg'
else
sha256 '695dde837fb2268f61484370a447186c034b01863f86364c0a625509247c6afb'
url 'https://secure-appldnld.apple.com/STP/091-47387-20171115-0BCEE496-C97A-11E7-B266-7FC0A61DC569/SafariTechnologyPreview.dmg'
end
name 'Safari Technology Preview'
homepage 'https://developer.apple.com/safari/download/'
depends_on macos: '>= :sierra'
pkg 'Safari Technology Preview.pkg'
uninstall delete: '/Applications/Safari Technology Preview.app'
zap trash: [
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.apple.safaritechnologypreview.sfl*',
'~/Library/Caches/com.apple.SafariTechnologyPreview',
'~/Library/Preferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/SafariTechnologyPreview',
'~/Library/Saved Application State/com.apple.SafariTechnologyPreview.savedState',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.UserRequests.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.WebFeedSubscriptions.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/WebKit/com.apple.SafariTechnologyPreview',
]
end
Update safari-technology-preview to 45 (#4922)
cask 'safari-technology-preview' do
version '45'
if MacOS.version == :sierra
sha256 'b29e9eac61ce23f1a356ba29c705bb2afd7f8f369e8a7577f25d3686c2cd69eb'
url 'https://secure-appldnld.apple.com/STP/091-51912-20171206-61A4021C-DA2C-11E7-8DD1-138B61E0607F/SafariTechnologyPreview.dmg'
else
sha256 'a65d93692516acd7ca17ec3f77d8d2b71cfb7ba345545960615a68a1ae2cd5ab'
url 'https://secure-appldnld.apple.com/STP/091-51904-20171206-61A3E30E-DA2C-11E7-B579-128B61E0607F/SafariTechnologyPreview.dmg'
end
name 'Safari Technology Preview'
homepage 'https://developer.apple.com/safari/download/'
depends_on macos: '>= :sierra'
pkg 'Safari Technology Preview.pkg'
uninstall delete: '/Applications/Safari Technology Preview.app'
zap trash: [
'~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.apple.safaritechnologypreview.sfl*',
'~/Library/Caches/com.apple.SafariTechnologyPreview',
'~/Library/Preferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/SafariTechnologyPreview',
'~/Library/Saved Application State/com.apple.SafariTechnologyPreview.savedState',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.UserRequests.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview-com.apple.Safari.WebFeedSubscriptions.plist',
'~/Library/SyncedPreferences/com.apple.SafariTechnologyPreview.plist',
'~/Library/WebKit/com.apple.SafariTechnologyPreview',
]
end
|
class TimemachineschedulerBeta < Cask
version '4.0b3(483)'
sha256 '2cd1c172da73e7ff26ddfa71417dbf323a635b3eef2c8f3025edbaa2686880ba'
url 'http://www.klieme.com/Downloads/TimeMachineScheduler/TimeMachineScheduler_4.0b3Full.zip'
homepage 'http://www.klieme.com/TimeMachineScheduler.html'
nested_container 'TimeMachineScheduler_4.0b3.dmg'
app 'TimeMachineScheduler.app'
end
add license stanza, timemachinescheduler-beta
class TimemachineschedulerBeta < Cask
version '4.0b3(483)'
sha256 '2cd1c172da73e7ff26ddfa71417dbf323a635b3eef2c8f3025edbaa2686880ba'
url 'http://www.klieme.com/Downloads/TimeMachineScheduler/TimeMachineScheduler_4.0b3Full.zip'
homepage 'http://www.klieme.com/TimeMachineScheduler.html'
license :unknown
nested_container 'TimeMachineScheduler_4.0b3.dmg'
app 'TimeMachineScheduler.app'
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'terraforming/version'
Gem::Specification.new do |spec|
spec.name = "terraforming"
spec.version = Terraforming::VERSION
spec.authors = ["Daisuke Fujita"]
spec.email = ["dtanshi45@gmail.com"]
spec.summary = %q{Export existing AWS resources to Terraform style (tf, tfstate)}
spec.description = %q{Export existing AWS resources to Terraform style (tf, tfstate)}
spec.homepage = "https://github.com/dtan4/terraforming"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "aws-sdk", "~> 2.3.0"
spec.add_dependency "oj"
spec.add_dependency "ox", "~> 2.4.0"
spec.add_dependency "thor"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "codeclimate-test-reporter"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.2"
spec.add_development_dependency "simplecov", "~> 0.11.1"
end
Use Oj v2.15.x
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'terraforming/version'
Gem::Specification.new do |spec|
spec.name = "terraforming"
spec.version = Terraforming::VERSION
spec.authors = ["Daisuke Fujita"]
spec.email = ["dtanshi45@gmail.com"]
spec.summary = %q{Export existing AWS resources to Terraform style (tf, tfstate)}
spec.description = %q{Export existing AWS resources to Terraform style (tf, tfstate)}
spec.homepage = "https://github.com/dtan4/terraforming"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "aws-sdk", "~> 2.3.0"
spec.add_dependency "oj", "~> 2.15.0"
spec.add_dependency "ox", "~> 2.4.0"
spec.add_dependency "thor"
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "codeclimate-test-reporter"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.2"
spec.add_development_dependency "simplecov", "~> 0.11.1"
end
|
module JiraMule
# Style is a formula for formatting the results of a query.
# This currently only works with single queries.
class Style
def initialize(name, &block)
@name = name.to_sym
@fields = [:key, :summary]
@header = [:key, :summary]
@footer = nil
@format_type = :strings
@format = %{{{key}} {{summary}}}
@custom_tags = {}
@prefix_query = nil
@default_query = nil
@suffix_query = nil
@bolden_tag = :bolden
block.call(self) if block_given?
end
######################################################
def self.add(style, &block)
@@styles = {} unless defined?(@@styles)
if style.kind_of?(String) or style.kind_of?(Symbol) then
style = Style.new(style, &block)
end
@@styles[style.name] = style
end
def self.fetch(name)
@@styles[name.to_sym]
end
def self.list
@@styles.keys
end
######################################################
# Apply this style to Issues
# @param issues [Array] Issues from the Jira query to format
# @return formatted string
def apply(issues)
if @format_type == :strings then
keys = issues.map do |issue|
fmt = @format
fmt = fmt.join(' ') if fmt.kind_of? Array
res = JiraMule::IssueRender.render(fmt, issue.merge(issue[:fields]), @custom_tags)
bolden(issue, res)
end
(@header or '').to_s + keys.join("\n") + (@footer or '').to_s
elsif [:table, :table_rows, :table_columns].include? @format_type then
@format = [@format] unless @format.kind_of? Array
rows = issues.map do |issue|
issue = issue.merge(issue[:fields])
@format.map do |col|
if col.kind_of? Hash then
col = col.dup
str = col[:value] or ""
res = JiraMule::IssueRender.render(str, issue, @custom_tags)
col[:value] = bolden(issue, res)
col
else
res = JiraMule::IssueRender.render(col, issue, @custom_tags)
bolden(issue, res)
end
end
end
if @format_type == :table_columns then
rows = rows.transpose
end
header = (@header or [])
header = [header] unless header.kind_of? Array
Terminal::Table.new :headings => header, :rows=>rows
end
end
# If this issue should be bolded or not.
def bolden(issue, row, color=:bold)
bld = issue[@bolden_tag]
bld = @custom_tags[@bolden_tag] if bld.nil?
bld = bld.call(issue.dup) if bld.kind_of? Proc
# ? truthy other than Ruby default?
return row unless bld
if row.kind_of? Array then
row.map{|r| HighLine.color(r, color)}
elsif row.kind_of? Hash then
hsh={}
row.each_pair{|k,v| hsh[k] = HighLine.color(v, color)}
else
HighLine.color(row.to_s, color)
end
end
# TODO: Dump method that outputs Ruby
# Build a query based on this Style and other bits from command line
# @param args [Array<String>] Other bits of JQL to use instead of default_query
def build_query(*args)
opts = {}
opts = args.pop if args.last.kind_of? Hash
# Add the default query, if there is one
if not @default_query.nil? then
# make sure there is an AND if working with a cmdline supplied part
args.push('AND') unless args.empty?
case @default_query
when Array
args.push @default_query.join(' AND ')
when Proc
args.push @default_query.call()
else
args.push @default_query.to_s
end
end
# Get prefix as a String.
case @prefix_query
when Array
prefix = @prefix_query.join(' AND ') + ' AND'
when Proc
prefix = @prefix_query.call()
else
prefix = @prefix_query.to_s
end
args.unshift(prefix) unless opts.has_key? :noprefix
# Get suffix as a String.
case @suffix_query
when Array
suffix = 'AND ' + @suffix_query.join(' AND ')
when Proc
suffix = @suffix_query.call()
else
suffix = @suffix_query.to_s
end
args.push(suffix) unless opts.has_key? :nosuffix
args.flatten.compact.join(' ')
end
# May need to split this into two classes. One that is the above methods
# and one that is the below methods. The below one is used just for the
# construction of a Style. While the above is the usage of a style.
#
# Maybe the above are in a Module, that is included as part of fetch?
######################################################
attr_accessor :prefix_query, :suffix_query, :default_query
attr_accessor :header
def name
@name
end
# takes a single flat array of key names.
def fields(*args)
return @fields if args.empty?
@fields = args.flatten.compact.map{|i| i.to_sym}
end
alias_method :fields=, :fields
FORMAT_TYPES = [:strings, :table_rows, :table_columns, :table].freeze
def format_type(type)
return @format_type if type.nil?
raise "Unknown format type: \"#{type}\"" unless FORMAT_TYPES.include? type
@format_type = type
end
alias_method :format_type=, :format_type
def format(*args)
return @format if args.empty?
args.flatten! if args.kind_of? Array
@format = args
end
alias_method :format=, :format
# Create a custom tag for formatted output
def add_tag(name, &block)
@custom_tags[name.to_sym] = block
end
end
##############################################################################
##############################################################################
##############################################################################
Style.add(:basic) do |s|
s.fields [:key, :summary]
s.format %{{{key}} {{summary}}}
s.header = nil
end
Style.add(:info) do |s|
s.fields [:key, :summary, :description, :assignee, :reporter, :priority,
:issuetype, :status, :resolution, :votes, :watches]
s.header = nil
s.format %{ Key: {{key}}
Summary: {{summary}}
Reporter: {{reporter.displayName}}
Assignee: {{assignee.displayName}}
Type: {{issuetype.name}} ({{priority.name}})
Status: {{status.name}} (Resolution: {{resolution.name}})
Watches: {{watches.watchCount}} Votes: {{votes.votes}}
Description: {{description}}
}
end
Style.add(:test_table) do |s|
s.fields [:key, :assignee]
s.format_type :table_columns
s.header = nil
s.format [%{{{key}}}, %{{{assignee.displayName}}}]
end
Style.add(:progress) do |s|
s.fields [:key, :workratio, :aggregatetimespent, :duedate,
:aggregatetimeoriginalestimate]
s.format_type :table_rows
s.header = [:key, :estimated, :progress, :percent, :due]
s.format [%{{{key}}},
{:value=>%{{{estimate}}},:alignment=>:right},
{:value=>%{{{progress}}},:alignment=>:right},
{:value=>%{{{percent}}%},:alignment=>:right},
{:value=>%{{{duedate}}},:alignment=>:center},
]
# Use lambda when there is logic that needs to be deferred.
s.prefix_query = lambda do
r = []
r << %{assignee = #{$cfg['user.name']}} unless $cfg['user.name'].nil?
prjs = $cfg['jira.project']
unless prjs.nil? then
r << '(' + prjs.split(' ').map{|prj| %{project = #{prj}}}.join(' OR ') + ')'
end
r.join(' AND ') + ' AND'
end
s.default_query = %{(status = "In Progress" OR status = "In Design/Estimation")}
s.suffix_query = %{ORDER BY Rank}
s.add_tag(:bolden) do |issue|
estimate = (issue[:aggregatetimeoriginalestimate] or 0)
progress = (issue[:aggregatetimespent] or 0)
due = issue[:duedate]
progress > estimate or (not due.nil? and Date.new >= Date.parse(due))
end
s.add_tag(:estimate) do |issue|
"%.2f"%[(issue[:aggregatetimeoriginalestimate] or 0) / 3600.0]
end
s.add_tag(:progress) do |issue|
"%.2f"%[(issue[:aggregatetimespent] or 0) / 3600.0]
end
s.add_tag(:percent) do |issue|
percent = issue[:workratio]
if percent < 0 then
estimate = (issue[:aggregatetimeoriginalestimate] or 0) / 3600.0
if estimate > 0 then
progress = (issue[:aggregatetimespent] or 0) / 3600.0
percent = (progress / estimate * 100).floor
else
percent = 100 # XXX ??? what is this line doing? why is it here?
end
end
if percent > 1000 then
">1000"
else
"%.1f"%[percent]
end
end
end
Style.add(:todo) do |s|
s.fields [:key, :summary]
s.header = "## Todo\n"
s.format %{- {{fixkey}}\t{{summary}}}
# Use lambda when there is logic that needs to be deferred.
s.prefix_query = lambda do
r = []
r << %{assignee = #{$cfg['user.name']}} unless $cfg['user.name'].nil?
prjs = $cfg['jira.project']
unless prjs.nil? then
r << '(' + prjs.split(' ').map{|prj| %{project = #{prj}}}.join(' OR ') + ')'
end
r.join(' AND ') + ' AND'
end
s.default_query = '(' + [
%{status = "On Deck"},
].join(' OR ') + ')'
s.suffix_query = %{ORDER BY Rank}
s.add_tag(:fixkey) do |issue|
"%-10s" % issue[:key]
end
end
Style.add(:comments) do |s|
s.fields [:key, :comment]
s.header = nil
s.format %{{{#comment.comments}}
---------------------------------------------
> {{author.displayName}} {{created}} {{editied}}
{{body}}
{{/comment.comments}}
}
end
end
# vim: set ai et sw=2 ts=2 :
A style for a github PR title
module JiraMule
# Style is a formula for formatting the results of a query.
# This currently only works with single queries.
class Style
def initialize(name, &block)
@name = name.to_sym
@fields = [:key, :summary]
@header = [:key, :summary]
@footer = nil
@format_type = :strings
@format = %{{{key}} {{summary}}}
@custom_tags = {}
@prefix_query = nil
@default_query = nil
@suffix_query = nil
@bolden_tag = :bolden
block.call(self) if block_given?
end
######################################################
def self.add(style, &block)
@@styles = {} unless defined?(@@styles)
if style.kind_of?(String) or style.kind_of?(Symbol) then
style = Style.new(style, &block)
end
@@styles[style.name] = style
end
def self.fetch(name)
@@styles[name.to_sym]
end
def self.list
@@styles.keys
end
######################################################
# Apply this style to Issues
# @param issues [Array] Issues from the Jira query to format
# @return formatted string
def apply(issues)
if @format_type == :strings then
keys = issues.map do |issue|
fmt = @format
fmt = fmt.join(' ') if fmt.kind_of? Array
res = JiraMule::IssueRender.render(fmt, issue.merge(issue[:fields]), @custom_tags)
bolden(issue, res)
end
(@header or '').to_s + keys.join("\n") + (@footer or '').to_s
elsif [:table, :table_rows, :table_columns].include? @format_type then
@format = [@format] unless @format.kind_of? Array
rows = issues.map do |issue|
issue = issue.merge(issue[:fields])
@format.map do |col|
if col.kind_of? Hash then
col = col.dup
str = col[:value] or ""
res = JiraMule::IssueRender.render(str, issue, @custom_tags)
col[:value] = bolden(issue, res)
col
else
res = JiraMule::IssueRender.render(col, issue, @custom_tags)
bolden(issue, res)
end
end
end
if @format_type == :table_columns then
rows = rows.transpose
end
header = (@header or [])
header = [header] unless header.kind_of? Array
Terminal::Table.new :headings => header, :rows=>rows
end
end
# If this issue should be bolded or not.
def bolden(issue, row, color=:bold)
bld = issue[@bolden_tag]
bld = @custom_tags[@bolden_tag] if bld.nil?
bld = bld.call(issue.dup) if bld.kind_of? Proc
# ? truthy other than Ruby default?
return row unless bld
if row.kind_of? Array then
row.map{|r| HighLine.color(r, color)}
elsif row.kind_of? Hash then
hsh={}
row.each_pair{|k,v| hsh[k] = HighLine.color(v, color)}
else
HighLine.color(row.to_s, color)
end
end
# TODO: Dump method that outputs Ruby
# Build a query based on this Style and other bits from command line
# @param args [Array<String>] Other bits of JQL to use instead of default_query
def build_query(*args)
opts = {}
opts = args.pop if args.last.kind_of? Hash
# Add the default query, if there is one
if not @default_query.nil? then
# make sure there is an AND if working with a cmdline supplied part
args.push('AND') unless args.empty?
case @default_query
when Array
args.push @default_query.join(' AND ')
when Proc
args.push @default_query.call()
else
args.push @default_query.to_s
end
end
# Get prefix as a String.
case @prefix_query
when Array
prefix = @prefix_query.join(' AND ') + ' AND'
when Proc
prefix = @prefix_query.call()
else
prefix = @prefix_query.to_s
end
args.unshift(prefix) unless opts.has_key? :noprefix
# Get suffix as a String.
case @suffix_query
when Array
suffix = 'AND ' + @suffix_query.join(' AND ')
when Proc
suffix = @suffix_query.call()
else
suffix = @suffix_query.to_s
end
args.push(suffix) unless opts.has_key? :nosuffix
args.flatten.compact.join(' ')
end
# May need to split this into two classes. One that is the above methods
# and one that is the below methods. The below one is used just for the
# construction of a Style. While the above is the usage of a style.
#
# Maybe the above are in a Module, that is included as part of fetch?
######################################################
attr_accessor :prefix_query, :suffix_query, :default_query
attr_accessor :header
def name
@name
end
# takes a single flat array of key names.
def fields(*args)
return @fields if args.empty?
@fields = args.flatten.compact.map{|i| i.to_sym}
end
alias_method :fields=, :fields
FORMAT_TYPES = [:strings, :table_rows, :table_columns, :table].freeze
def format_type(type)
return @format_type if type.nil?
raise "Unknown format type: \"#{type}\"" unless FORMAT_TYPES.include? type
@format_type = type
end
alias_method :format_type=, :format_type
def format(*args)
return @format if args.empty?
args.flatten! if args.kind_of? Array
@format = args
end
alias_method :format=, :format
# Create a custom tag for formatted output
def add_tag(name, &block)
@custom_tags[name.to_sym] = block
end
end
##############################################################################
##############################################################################
##############################################################################
Style.add(:basic) do |s|
s.fields [:key, :summary]
s.format %{{{key}} {{summary}}}
s.header = nil
end
Style.add(:pr) do |s|
s.fields [:key, :summary]
s.format %{{{summary}} ({{key}})}
s.header = nil
end
Style.add(:info) do |s|
s.fields [:key, :summary, :description, :assignee, :reporter, :priority,
:issuetype, :status, :resolution, :votes, :watches]
s.header = nil
s.format %{ Key: {{key}}
Summary: {{summary}}
Reporter: {{reporter.displayName}}
Assignee: {{assignee.displayName}}
Type: {{issuetype.name}} ({{priority.name}})
Status: {{status.name}} (Resolution: {{resolution.name}})
Watches: {{watches.watchCount}} Votes: {{votes.votes}}
Description: {{description}}
}
end
Style.add(:test_table) do |s|
s.fields [:key, :assignee]
s.format_type :table_columns
s.header = nil
s.format [%{{{key}}}, %{{{assignee.displayName}}}]
end
Style.add(:progress) do |s|
s.fields [:key, :workratio, :aggregatetimespent, :duedate,
:aggregatetimeoriginalestimate]
s.format_type :table_rows
s.header = [:key, :estimated, :progress, :percent, :due]
s.format [%{{{key}}},
{:value=>%{{{estimate}}},:alignment=>:right},
{:value=>%{{{progress}}},:alignment=>:right},
{:value=>%{{{percent}}%},:alignment=>:right},
{:value=>%{{{duedate}}},:alignment=>:center},
]
# Use lambda when there is logic that needs to be deferred.
s.prefix_query = lambda do
r = []
r << %{assignee = #{$cfg['user.name']}} unless $cfg['user.name'].nil?
prjs = $cfg['jira.project']
unless prjs.nil? then
r << '(' + prjs.split(' ').map{|prj| %{project = #{prj}}}.join(' OR ') + ')'
end
r.join(' AND ') + ' AND'
end
s.default_query = %{(status = "In Progress" OR status = "In Design/Estimation")}
s.suffix_query = %{ORDER BY Rank}
s.add_tag(:bolden) do |issue|
estimate = (issue[:aggregatetimeoriginalestimate] or 0)
progress = (issue[:aggregatetimespent] or 0)
due = issue[:duedate]
progress > estimate or (not due.nil? and Date.new >= Date.parse(due))
end
s.add_tag(:estimate) do |issue|
"%.2f"%[(issue[:aggregatetimeoriginalestimate] or 0) / 3600.0]
end
s.add_tag(:progress) do |issue|
"%.2f"%[(issue[:aggregatetimespent] or 0) / 3600.0]
end
s.add_tag(:percent) do |issue|
percent = issue[:workratio]
if percent < 0 then
estimate = (issue[:aggregatetimeoriginalestimate] or 0) / 3600.0
if estimate > 0 then
progress = (issue[:aggregatetimespent] or 0) / 3600.0
percent = (progress / estimate * 100).floor
else
percent = 100 # XXX ??? what is this line doing? why is it here?
end
end
if percent > 1000 then
">1000"
else
"%.1f"%[percent]
end
end
end
Style.add(:todo) do |s|
s.fields [:key, :summary]
s.header = "## Todo\n"
s.format %{- {{fixkey}}\t{{summary}}}
# Use lambda when there is logic that needs to be deferred.
s.prefix_query = lambda do
r = []
r << %{assignee = #{$cfg['user.name']}} unless $cfg['user.name'].nil?
prjs = $cfg['jira.project']
unless prjs.nil? then
r << '(' + prjs.split(' ').map{|prj| %{project = #{prj}}}.join(' OR ') + ')'
end
r.join(' AND ') + ' AND'
end
s.default_query = '(' + [
%{status = "On Deck"},
].join(' OR ') + ')'
s.suffix_query = %{ORDER BY Rank}
s.add_tag(:fixkey) do |issue|
"%-10s" % issue[:key]
end
end
Style.add(:comments) do |s|
s.fields [:key, :comment]
s.header = nil
s.format %{{{#comment.comments}}
---------------------------------------------
> {{author.displayName}} {{created}} {{editied}}
{{body}}
{{/comment.comments}}
}
end
end
# vim: set ai et sw=2 ts=2 :
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'test/opsbots/version'
Gem::Specification.new do |spec|
spec.name = "test-opsbots"
spec.version = Test::Opsbots::VERSION
spec.authors = ["Pier-Hugues Pellerin"]
spec.email = ["phpellerin@gmail.com"]
spec.summary = 'This gem is only a test and should not be used for anything'
spec.description = 'this shouldnt be used'
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
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.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_runtime_dependency "msgpack-jruby"
spec.add_development_dependency 'logstash-devutils', '~> 0.0.4'
spec.add_development_dependency 'rspec'
end
add ruby version
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'test/opsbots/version'
Gem::Specification.new do |spec|
spec.name = "test-opsbots"
spec.version = Test::Opsbots::VERSION
spec.authors = ["Pier-Hugues Pellerin"]
spec.email = ["phpellerin@gmail.com"]
spec.summary = 'This gem is only a test and should not be used for anything'
spec.description = 'this shouldnt be used'
spec.homepage = ""
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0")
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.platform = RUBY_VERSION
spec.add_development_dependency "bundler", "~> 1.7"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_runtime_dependency "msgpack-jruby"
spec.add_development_dependency 'logstash-devutils', '~> 0.0.4'
spec.add_development_dependency 'rspec'
end
|
#
# Copyright 2019 Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
name "go"
default_version "1.17.7"
license "BSD-3-Clause"
license_file "https://raw.githubusercontent.com/golang/go/master/LICENSE"
# Defaults
platform = "linux"
arch = "amd64"
ext = "tar.gz"
if windows?
platform = "windows"
ext = "zip"
# version_list: url=https://golang.org/dl/ filter=*.windows-amd64.zip
version("1.17.7") { source sha256: "1b648165d62a2f5399f3c42c7e59de9f4aa457212c4ea763e1b650546fac72e2" }
version("1.17.6") { source sha256: "5bf8f87aec7edfc08e6bc845f1c30dba6de32b863f89ae46553ff4bbcc1d4954" }
version("1.17.5") { source sha256: "671faf99cd5d81cd7e40936c0a94363c64d654faa0148d2af4bbc262555620b9" }
version("1.17.2") { source sha256: "fa6da0b829a66f5fab7e4e312fd6aa1b2d8f045c7ecee83b3d00f6fe5306759a" }
version("1.17") { source sha256: "2a18bd65583e221be8b9b7c2fbe3696c40f6e27c2df689bbdcc939d49651d151" }
version("1.16.3") { source sha256: "a4400345135b36cb7942e52bbaf978b66814738b855eeff8de879a09fd99de7f" }
elsif mac_os_x?
platform = "darwin"
# version_list: url=https://golang.org/dl/ filter=*.darwin-amd64.tar.gz
version("1.17.7") { source sha256: "7c3d9cc70ee592515d92a44385c0cba5503fd0a9950f78d76a4587916c67a84d" }
version("1.17.6") { source sha256: "874bc6f95e07697380069a394a21e05576a18d60f4ba178646e1ebed8f8b1f89" }
version("1.17.5") { source sha256: "2db6a5d25815b56072465a2cacc8ed426c18f1d5fc26c1fc8c4f5a7188658264" }
version("1.17.2") { source sha256: "7914497a302a132a465d33f5ee044ce05568bacdb390ab805cb75a3435a23f94" }
version("1.17") { source sha256: "355bd544ce08d7d484d9d7de05a71b5c6f5bc10aa4b316688c2192aeb3dacfd1" }
version("1.16.3") { source sha256: "6bb1cf421f8abc2a9a4e39140b7397cdae6aca3e8d36dcff39a1a77f4f1170ac" }
else
# version_list: url=https://golang.org/dl/ filter=*.linux-amd64.tar.gz
version("1.17.7") { source sha256: "02b111284bedbfa35a7e5b74a06082d18632eff824fd144312f6063943d49259" }
version("1.17.6") { source sha256: "231654bbf2dab3d86c1619ce799e77b03d96f9b50770297c8f4dff8836fc8ca2" }
version("1.17.5") { source sha256: "bd78114b0d441b029c8fe0341f4910370925a4d270a6a590668840675b0c653e" }
version("1.17.2") { source sha256: "f242a9db6a0ad1846de7b6d94d507915d14062660616a61ef7c808a76e4f1676" }
version("1.17") { source sha256: "6bf89fc4f5ad763871cf7eac80a2d594492de7a818303283f1366a7f6a30372d" }
version("1.16.3") { source sha256: "951a3c7c6ce4e56ad883f97d9db74d3d6d80d5fec77455c6ada6c1f7ac4776d2" }
end
source url: "https://dl.google.com/go/go#{version}.%{platform}-%{arch}.%{ext}" % { platform: platform, arch: arch, ext: ext }
build do
# We do not use 'sync' since we've found multiple errors with other software definitions
mkdir "#{install_dir}/embedded/go"
copy "#{project_dir}/go/*", "#{install_dir}/embedded/go"
mkdir "#{install_dir}/embedded/bin"
%w{go gofmt}.each do |bin|
link "#{install_dir}/embedded/go/bin/#{bin}", "#{install_dir}/embedded/bin/#{bin}"
end
end
Whitespace correction
Signed-off-by: poornima <6411b1792ba899670cee160af97f12ca603a25e2@progress.com>
#
# Copyright 2019 Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
name "go"
default_version "1.17.7"
license "BSD-3-Clause"
license_file "https://raw.githubusercontent.com/golang/go/master/LICENSE"
# Defaults
platform = "linux"
arch = "amd64"
ext = "tar.gz"
if windows?
platform = "windows"
ext = "zip"
# version_list: url=https://golang.org/dl/ filter=*.windows-amd64.zip
version("1.17.7") { source sha256: "1b648165d62a2f5399f3c42c7e59de9f4aa457212c4ea763e1b650546fac72e2" }
version("1.17.6") { source sha256: "5bf8f87aec7edfc08e6bc845f1c30dba6de32b863f89ae46553ff4bbcc1d4954" }
version("1.17.5") { source sha256: "671faf99cd5d81cd7e40936c0a94363c64d654faa0148d2af4bbc262555620b9" }
version("1.17.2") { source sha256: "fa6da0b829a66f5fab7e4e312fd6aa1b2d8f045c7ecee83b3d00f6fe5306759a" }
version("1.17") { source sha256: "2a18bd65583e221be8b9b7c2fbe3696c40f6e27c2df689bbdcc939d49651d151" }
version("1.16.3") { source sha256: "a4400345135b36cb7942e52bbaf978b66814738b855eeff8de879a09fd99de7f" }
elsif mac_os_x?
platform = "darwin"
# version_list: url=https://golang.org/dl/ filter=*.darwin-amd64.tar.gz
version("1.17.7") { source sha256: "7c3d9cc70ee592515d92a44385c0cba5503fd0a9950f78d76a4587916c67a84d" }
version("1.17.6") { source sha256: "874bc6f95e07697380069a394a21e05576a18d60f4ba178646e1ebed8f8b1f89" }
version("1.17.5") { source sha256: "2db6a5d25815b56072465a2cacc8ed426c18f1d5fc26c1fc8c4f5a7188658264" }
version("1.17.2") { source sha256: "7914497a302a132a465d33f5ee044ce05568bacdb390ab805cb75a3435a23f94" }
version("1.17") { source sha256: "355bd544ce08d7d484d9d7de05a71b5c6f5bc10aa4b316688c2192aeb3dacfd1" }
version("1.16.3") { source sha256: "6bb1cf421f8abc2a9a4e39140b7397cdae6aca3e8d36dcff39a1a77f4f1170ac" }
else
# version_list: url=https://golang.org/dl/ filter=*.linux-amd64.tar.gz
version("1.17.7") { source sha256: "02b111284bedbfa35a7e5b74a06082d18632eff824fd144312f6063943d49259" }
version("1.17.6") { source sha256: "231654bbf2dab3d86c1619ce799e77b03d96f9b50770297c8f4dff8836fc8ca2" }
version("1.17.5") { source sha256: "bd78114b0d441b029c8fe0341f4910370925a4d270a6a590668840675b0c653e" }
version("1.17.2") { source sha256: "f242a9db6a0ad1846de7b6d94d507915d14062660616a61ef7c808a76e4f1676" }
version("1.17") { source sha256: "6bf89fc4f5ad763871cf7eac80a2d594492de7a818303283f1366a7f6a30372d" }
version("1.16.3") { source sha256: "951a3c7c6ce4e56ad883f97d9db74d3d6d80d5fec77455c6ada6c1f7ac4776d2" }
end
source url: "https://dl.google.com/go/go#{version}.%{platform}-%{arch}.%{ext}" % { platform: platform, arch: arch, ext: ext }
build do
# We do not use 'sync' since we've found multiple errors with other software definitions
mkdir "#{install_dir}/embedded/go"
copy "#{project_dir}/go/*", "#{install_dir}/embedded/go"
mkdir "#{install_dir}/embedded/bin"
%w{go gofmt}.each do |bin|
link "#{install_dir}/embedded/go/bin/#{bin}", "#{install_dir}/embedded/bin/#{bin}"
end
end
|
Adding a gemspec file
Gem::Specification.new do |s|
s.name = 'config_parser'
s.version = "0.0.1"
s.date = '2015-01-14'
s.summary = "Ruby Config Parser for DZAP"
s.description = "A demonstration gem"
s.authors = ["Jonathan Gnagy"]
s.email = 'jonathan.gnagy@gmail.com'
s.files = [
"lib/config_parser.rb",
"lib/config_parser/format.rb",
"lib/config_parser/formats/dzap.rb",
"lib/config_parser/parser.rb",
"LICENSE"
]
s.license = 'MIT'
end |
require 'test_helper'
class BitmaskTest < Test::Unit::TestCase
TEST_MASKS = {
:phone => 0b0000001,
:name => 0b0000010,
:gender => 0b0000100,
:email => 0b0001000,
:birthday => 0b0100000,
:location => 0b1000000,
}
# Replace this with your real tests.
def test_get
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
assert bitmask.get(:phone)
assert bitmask.get(:name)
assert bitmask.get(:email)
assert !bitmask.get(:gender)
assert !bitmask.get(:birthday)
assert !bitmask.get(:location)
end
def test_set
bitmask = Bitmask.new TEST_MASKS, 0
assert !bitmask.get(:phone)
bitmask.set(:phone, true)
assert bitmask.get(:phone)
assert !bitmask.get(:email)
bitmask.set(:email, true)
assert bitmask.get(:email)
end
def test_to_h
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
assert_equal({:phone => true, :name => true, :email => true, :gender => false, :birthday => false, :location => false}, bitmask.to_h)
end
def test_to_a
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
assert_equal([:phone, :name, :email], bitmask.to_a)
end
def test_each
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
results = {}
bitmask.each do |k, v|
results[k] = v
end
assert_equal({:phone => true, :name => true, :email => true, :gender => false, :birthday => false, :location => false}, results)
end
def test_defaults
bitmask = Bitmask.new(TEST_MASKS, nil || {:phone => true, :email => true})
assert bitmask.get(:phone)
assert !bitmask.get(:name)
assert bitmask.get(:email)
assert !bitmask.get(:gender)
assert !bitmask.get(:birthday)
assert !bitmask.get(:location)
end
def test_to_i_and_create_from_integer
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
bitmask_two = Bitmask.new(TEST_MASKS, bitmask.to_i)
assert_equal(bitmask_two.to_h, {:phone => true, :name => true, :email => true, :gender => false, :birthday => false, :location => false})
end
def test_equality
bitmask_one = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
bitmask_two = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
bitmask_three = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => false
assert bitmask_one == bitmask_two
assert bitmask_two != bitmask_three
end
def test_set_array
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true
bitmask.set_array [:phone, :email]
assert_equal(bitmask.to_h, {:phone => true, :name => false, :email => true, :gender => false, :birthday => false, :location => false})
end
def test_set_raises
bitmask = Bitmask.new TEST_MASKS, 0
assert_raises ArgumentError do
bitmask.set :foo, true
end
end
def test_set_array_doesnt_raise
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true
assert_nothing_raised do
bitmask.set_array [:phone, :email, :foodebar]
end
assert_equal(bitmask.to_h, {:phone => true, :name => false, :email => true, :gender => false, :birthday => false, :location => false})
end
end
Force CI to fail to test CI
require 'test_helper'
class BitmaskTest < Test::Unit::TestCase
TEST_MASKS = {
:phone => 0b0000001,
:name => 0b0000010,
:gender => 0b0000100,
:email => 0b0001000,
:birthday => 0b0100000,
:location => 0b1000000,
}
# Replace this with your real tests.
def test_get
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
assert bitmask.get(:phone)
assert bitmask.get(:name)
assert bitmask.get(:email)
assert !bitmask.get(:gender)
assert !bitmask.get(:birthday)
assert !bitmask.get(:location)
end
def test_fail
assert !"Force CI to fail"
end
def test_set
bitmask = Bitmask.new TEST_MASKS, 0
assert !bitmask.get(:phone)
bitmask.set(:phone, true)
assert bitmask.get(:phone)
assert !bitmask.get(:email)
bitmask.set(:email, true)
assert bitmask.get(:email)
end
def test_to_h
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
assert_equal({:phone => true, :name => true, :email => true, :gender => false, :birthday => false, :location => false}, bitmask.to_h)
end
def test_to_a
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
assert_equal([:phone, :name, :email], bitmask.to_a)
end
def test_each
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
results = {}
bitmask.each do |k, v|
results[k] = v
end
assert_equal({:phone => true, :name => true, :email => true, :gender => false, :birthday => false, :location => false}, results)
end
def test_defaults
bitmask = Bitmask.new(TEST_MASKS, nil || {:phone => true, :email => true})
assert bitmask.get(:phone)
assert !bitmask.get(:name)
assert bitmask.get(:email)
assert !bitmask.get(:gender)
assert !bitmask.get(:birthday)
assert !bitmask.get(:location)
end
def test_to_i_and_create_from_integer
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
bitmask_two = Bitmask.new(TEST_MASKS, bitmask.to_i)
assert_equal(bitmask_two.to_h, {:phone => true, :name => true, :email => true, :gender => false, :birthday => false, :location => false})
end
def test_equality
bitmask_one = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
bitmask_two = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => true
bitmask_three = Bitmask.new TEST_MASKS, :phone => true, :name => true, :email => false
assert bitmask_one == bitmask_two
assert bitmask_two != bitmask_three
end
def test_set_array
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true
bitmask.set_array [:phone, :email]
assert_equal(bitmask.to_h, {:phone => true, :name => false, :email => true, :gender => false, :birthday => false, :location => false})
end
def test_set_raises
bitmask = Bitmask.new TEST_MASKS, 0
assert_raises ArgumentError do
bitmask.set :foo, true
end
end
def test_set_array_doesnt_raise
bitmask = Bitmask.new TEST_MASKS, :phone => true, :name => true
assert_nothing_raised do
bitmask.set_array [:phone, :email, :foodebar]
end
assert_equal(bitmask.to_h, {:phone => true, :name => false, :email => true, :gender => false, :birthday => false, :location => false})
end
end
|
Test Context class
require_relative 'helper'
describe ApplicationInsightsInstaller::Context do
before do
@configs = {
"instrumentation_key" => "a_key",
"custom" => 4,
"properties" => "belong to the context",
"application" => {
"ver" => "0.0.1"
},
"device" => {
"id" => "asdfghjkl1",
"os" => "OSX"
}
}
end
describe 'configure' do
it 'returns a ApplicationInsights::Channel::TelemetryContext object' do
context = ApplicationInsightsInstaller::Context.configure
assert_equal ApplicationInsights::Channel::TelemetryContext, context.class
end
it 'accepts a hash to set Context values' do
context = ApplicationInsightsInstaller::Context.configure @configs
assert_equal 'a_key', context.instrumentation_key
assert_equal '0.0.1', context.application.ver
end
end
describe 'telemetry_client' do
before do
ApplicationInsightsInstaller::Context.configure @configs
@client = ApplicationInsightsInstaller::Context.telemetry_client
end
it 'returns an instance of ApplicationInsights::TelemetryClient' do
assert_equal ApplicationInsights::TelemetryClient, @client.class
end
it 'sets the context to the Telemetry Client' do
assert_equal 'a_key', @client.context.instrumentation_key
end
end
end
|
get '/admin/?' do
p session
erb :"admin/login", :layout => :"admin/layout", :locals => {:message => nil}
end
post '/admin/login' do
if admin?
session[:admin] = true
redirect '/admin/posts/'
else
erb :"admin/login", :layout => :"admin/layout", :locals => {:message => "Invalid credentials."}
end
end
get '/admin/logout/?' do
session[:admin] = false
redirect '/admin/'
end
get '/admin/posts/?' do
admin!
posts = Post.desc(:created_at).paginate(pagination(20))
erb :"admin/posts", :layout => :"admin/layout", :locals => {:posts => posts}
end
get '/admin/posts/new/?' do
admin!
erb :"admin/new", :layout => :"admin/layout"
end
post '/admin/posts/?' do
admin!
post = Post.new params[:post]
post.save! # should be no reason for failure
redirect "/admin/post/#{post.slug}"
end
get '/admin/post/:slug' do
admin!
post = Post.where(:slug => params[:slug]).first
raise Sinatra::NotFound unless post
erb :"admin/post", :layout => :"admin/layout", :locals => {:post => post}
end
put '/admin/post/:slug' do
admin!
post = Post.where(:slug => params[:slug]).first
raise Sinatra::NotFound unless post
params[:post]['tags'] = (params[:post]['tags'] || []).split /, ?/
params[:post]['display_title'] = (params[:post]['display_title'] == "on")
post.attributes = params[:post]
if params[:submit] == "Publish"
post.published_at = Time.now
post.draft = false
elsif params[:submit] == "Unpublish"
post.draft = true
elsif params[:submit] == "Make public"
post.private = false
elsif params[:submit] == "Make private"
post.private = true
end
if post.save
redirect "/admin/post/#{post.slug}"
else
erb :"admin/post", :locals => {:post => post}
end
end
get '/admin/comments/?' do
admin!
comments = Comment.desc(:created_at).where(:flagged => false).all.paginate(pagination(20))
erb :"admin/comments", :layout => :"admin/layout", :locals => {:comments => comments, :flagged => false}
end
get '/admin/comments/flagged/?' do
admin!
comments = Comment.desc(:created_at).where(:flagged => true).all.paginate(pagination(100))
erb :"admin/comments", :layout => :"admin/layout", :locals => {:comments => comments, :flagged => true}
end
get '/admin/comment/:id' do
admin!
comment = Comment.where(:_id => BSON::ObjectId(params[:id])).first
raise Sinatra::NotFound unless comment
erb :"admin/comment", :layout => :"admin/layout", :locals => {:comment => comment}
end
put '/admin/comment/:id' do
admin!
comment = Comment.where(:_id => BSON::ObjectId(params[:id])).first
raise Sinatra::NotFound unless comment
params[:comment]['mine'] = (params[:comment]['mine'] == "on")
comment.attributes = params[:comment]
comment.ip = params[:comment]['ip']
comment.mine = params[:comment]['mine']
if params[:submit] == "Hide"
comment.hidden = true
elsif params[:submit] == "Show"
comment.hidden = false
end
if comment.save
redirect "/admin/comment/#{comment._id}"
else
erb :"admin/comment", :layout => :"admin/layout", :locals => {:comment => comment}
end
end
def admin!
throw(:halt, [401, "Not authorized\n"]) unless session[:admin] == true
end
def admin?
(params[:username] == config[:admin][:username]) and (params[:password] == config[:admin][:password])
end
Don't overwrite published_at timestamp if it's set already
get '/admin/?' do
p session
erb :"admin/login", :layout => :"admin/layout", :locals => {:message => nil}
end
post '/admin/login' do
if admin?
session[:admin] = true
redirect '/admin/posts/'
else
erb :"admin/login", :layout => :"admin/layout", :locals => {:message => "Invalid credentials."}
end
end
get '/admin/logout/?' do
session[:admin] = false
redirect '/admin/'
end
get '/admin/posts/?' do
admin!
posts = Post.desc(:created_at).paginate(pagination(20))
erb :"admin/posts", :layout => :"admin/layout", :locals => {:posts => posts}
end
get '/admin/posts/new/?' do
admin!
erb :"admin/new", :layout => :"admin/layout"
end
post '/admin/posts/?' do
admin!
post = Post.new params[:post]
post.save! # should be no reason for failure
redirect "/admin/post/#{post.slug}"
end
get '/admin/post/:slug' do
admin!
post = Post.where(:slug => params[:slug]).first
raise Sinatra::NotFound unless post
erb :"admin/post", :layout => :"admin/layout", :locals => {:post => post}
end
put '/admin/post/:slug' do
admin!
post = Post.where(:slug => params[:slug]).first
raise Sinatra::NotFound unless post
params[:post]['tags'] = (params[:post]['tags'] || []).split /, ?/
params[:post]['display_title'] = (params[:post]['display_title'] == "on")
post.attributes = params[:post]
if params[:submit] == "Publish"
post.published_at ||= Time.now # don't overwrite this if it was published once already
post.draft = false
elsif params[:submit] == "Unpublish"
post.draft = true
elsif params[:submit] == "Make public"
post.private = false
elsif params[:submit] == "Make private"
post.private = true
end
if post.save
redirect "/admin/post/#{post.slug}"
else
erb :"admin/post", :locals => {:post => post}
end
end
get '/admin/comments/?' do
admin!
comments = Comment.desc(:created_at).where(:flagged => false).all.paginate(pagination(20))
erb :"admin/comments", :layout => :"admin/layout", :locals => {:comments => comments, :flagged => false}
end
get '/admin/comments/flagged/?' do
admin!
comments = Comment.desc(:created_at).where(:flagged => true).all.paginate(pagination(100))
erb :"admin/comments", :layout => :"admin/layout", :locals => {:comments => comments, :flagged => true}
end
get '/admin/comment/:id' do
admin!
comment = Comment.where(:_id => BSON::ObjectId(params[:id])).first
raise Sinatra::NotFound unless comment
erb :"admin/comment", :layout => :"admin/layout", :locals => {:comment => comment}
end
put '/admin/comment/:id' do
admin!
comment = Comment.where(:_id => BSON::ObjectId(params[:id])).first
raise Sinatra::NotFound unless comment
params[:comment]['mine'] = (params[:comment]['mine'] == "on")
comment.attributes = params[:comment]
comment.ip = params[:comment]['ip']
comment.mine = params[:comment]['mine']
if params[:submit] == "Hide"
comment.hidden = true
elsif params[:submit] == "Show"
comment.hidden = false
end
if comment.save
redirect "/admin/comment/#{comment._id}"
else
erb :"admin/comment", :layout => :"admin/layout", :locals => {:comment => comment}
end
end
def admin!
throw(:halt, [401, "Not authorized\n"]) unless session[:admin] == true
end
def admin?
(params[:username] == config[:admin][:username]) and (params[:password] == config[:admin][:password])
end |
class ActiveDocument::Base
def self.path(path = nil)
@path = path if path
@path ||= (self == ActiveDocument::Base ? nil : ActiveDocument::Base.path)
end
def self.db_config(config = {})
@db_config ||= {}
@db_config.merge!(config)
ActiveDocument.db_config.merge(@db_config)
end
def self.database_name(database_name = nil)
if database_name
raise 'cannot modify database_name after db has been initialized' if @database_name
@database_name = database_name
else
return if self == ActiveDocument::Base
@database_name ||= name.underscore.gsub('/', '-').pluralize
end
end
@@environment = {}
def self.environment
@@environment[path] ||= ActiveDocument::Environment.new(path)
end
def self.database
@database
end
def database
self.class.database
end
def self.transaction(&block)
database.transaction(&block)
end
def transaction(&block)
self.class.transaction(&block)
end
def self.checkpoint(opts = {})
environment.checkpoint(opts)
end
def self.create(*args)
model = new(*args)
model.save
model
end
def self.primary_key(field_or_fields, opts = {})
raise 'primary key already defined' if @database
if @partition_by = opts[:partition_by]
@database = ActiveDocument::PartitionedDatabase.new(
:model_class => self,
:environment => environment,
:partition_by => @partition_by
)
(class << self; self; end).instance_eval do
alias_method opts[:partition_by].to_s.pluralize, :partitions
alias_method "with_#{opts[:partition_by]}", :with_partition
alias_method "with_each_#{opts[:partition_by]}", :with_each_partition
end
else
@database = environment.new_database(:model_class => self)
end
field = define_field_accessor(field_or_fields)
define_find_methods(field, :field => :primary_key) # find_by_field1_and_field2
define_field_accessor(field_or_fields, :primary_key)
define_find_methods(:primary_key) # find_by_primary_key
# Define shortcuts for partial keys.
define_partial_shortcuts(field_or_fields, :primary_key)
end
def self.partitions
database.partitions
end
def self.with_partition(partition, &block)
database.with_partition(partition, &block)
end
def self.with_each_partition(&block)
database.partitions.each do |partition|
database.with_partition(partition, &block)
end
end
def self.partition_by
@partition_by
end
def partition_by
self.class.partition_by
end
def partition
send(partition_by) if partition_by
end
def self.index_by(field_or_fields, opts = {})
raise "cannot have a multi_key index on an aggregate key" if opts[:multi_key] and field_or_fields.kind_of?(Array)
field = define_field_accessor(field_or_fields)
database.index_by(field, opts)
field_name = opts[:multi_key] ? field.to_s.singularize : field
define_find_methods(field_name, :field => field) # find_by_field1_and_field2
# Define shortcuts for partial keys.
define_partial_shortcuts(field_or_fields, field)
end
def self.close_environment
# Will close all databases in the environment.
environment.close
end
def self.find_by(field, *keys)
opts = extract_opts(keys)
opts[:field] = field
keys << :all if keys.empty?
database.find(keys, opts)
end
def self.find(key, opts = {})
doc = database.find([key], opts).first
raise ActiveDocument::DocumentNotFound, "Couldn't find #{name} with id #{key.inspect}" unless doc
doc
end
def self.count(field, key)
database.count(field, key)
end
class << self
attr_reader :page_key, :page_offset
def set_page_marker(key = nil, offset = nil)
@page_key = key
@page_offset = offset
end
def page_marker
[page_key, page_offset]
end
end
def self.define_field_accessor(field_or_fields, field = nil)
if field_or_fields.kind_of?(Array)
field ||= field_or_fields.join('_and_').to_sym
define_method(field) do
field_or_fields.collect {|f| self.send(f)}.flatten
end
elsif field
define_method(field) do
self.send(field_or_fields)
end
else
field = field_or_fields.to_sym
end
field
end
def self.define_find_methods(name, config = {})
field = config[:field] || name
(class << self; self; end).instance_eval do
define_method("find_by_#{name}") do |*args|
modify_opts(args) do |opts|
opts[:limit] = 1
opts[:partial] ||= config[:partial]
end
find_by(field, *args).first
end
define_method("find_all_by_#{name}") do |*args|
modify_opts(args) do |opts|
opts[:partial] ||= config[:partial]
end
find_by(field, *args)
end
end
end
def self.define_partial_shortcuts(fields, primary_field)
return unless fields.kind_of?(Array)
(fields.size - 1).times do |i|
name = fields[0..i].join('_and_')
next if respond_to?("find_by_#{name}")
define_find_methods(name, :field => primary_field, :partial => true)
end
end
def self.timestamps
reader(:created_at, :updated_at, :deleted_at)
end
def self.defaults(defaults = {})
@defaults ||= {}
@defaults.merge!(defaults)
end
def self.default(attr, default)
defaults[attr] = default
end
def self.reader(*attrs)
attrs.each do |attr|
define_method(attr) do
read_attribute(attr)
end
end
end
def self.bool_reader(*attrs)
attrs.each do |attr|
define_method(attr) do
!!read_attribute(attr)
end
define_method("#{attr}?") do
!!read_attribute(attr)
end
end
end
def self.writer(*attrs)
attrs.each do |attr|
define_method("#{attr}=") do |value|
attributes[attr] = value
end
end
end
def self.accessor(*attrs)
reader(*attrs)
writer(*attrs)
end
def self.bool_accessor(*attrs)
bool_reader(*attrs)
writer(*attrs)
end
def self.save_method(method_name)
define_method("#{method_name}!") do |*args|
value = send(method_name, *args)
save
value
end
end
def initialize(attributes = {}, saved_attributes = nil)
@attributes = HashWithIndifferentAccess.new(attributes) if attributes
@saved_attributes = HashWithIndifferentAccess.new(saved_attributes) if saved_attributes
# Initialize defaults if this is a new record.
if @saved_attributes.nil?
self.class.defaults.each do |attr, default|
next if @attributes.has_key?(attr)
@attributes[attr] = default.is_a?(Proc) ? default.bind(self).call : default.dup
end
end
# Set the partition field in case we are in a with_partition block.
if partition_by and partition.nil?
set_method = "#{partition_by}="
self.send(set_method, database.partition) if respond_to?(set_method)
end
end
attr_reader :saved_attributes
attr_accessor :locator_key
def attributes
@attributes ||= Marshal.load(Marshal.dump(saved_attributes))
end
def read_attribute(attr)
if @attributes.nil?
saved_attributes[attr]
else
attributes[attr]
end
end
save_method :update_attributes
def update_attributes(attrs = {})
attrs.each do |field, value|
self.send("#{field}=", value)
end
end
def to_json(*args)
attributes.to_json(*args)
end
def ==(other)
return false unless other.class == self.class
attributes == other.attributes
end
def new_record?
@saved_attributes.nil?
end
def changed?(field = nil)
return false unless @attributes and @saved_attributes
if field
send(field) != saved.send(field)
else
attributes != saved_attributes
end
end
def saved
raise 'no saved attributes for new record' if new_record?
@saved ||= self.class.new(saved_attributes)
end
def save
time = Time.now
attributes[:updated_at] = time if respond_to?(:updated_at)
attributes[:created_at] = time if respond_to?(:created_at) and new_record?
opts = {}
if changed?(:primary_key) or (partition_by and changed?(partition_by))
opts[:create] = true
saved.destroy
else
opts[:create] = new_record?
end
@saved_attributes = attributes
@attributes = nil
@saved = nil
database.save(self, opts)
end
def destroy
database.delete(self)
end
save_method :delete
def delete
raise 'cannot delete a record without deleted_at attribute' unless respond_to?(:deleted_at)
saved_attributes[:deleted_at] = Time.now
end
save_method :undelete
def undelete
raise 'cannot undelete a record without deleted_at attribute' unless respond_to?(:deleted_at)
saved_attributes.delete(:deleted_at)
end
def deleted?
respond_to?(:deleted_at) and not deleted_at.nil?
end
def _dump(ignored)
attributes = @attributes.to_hash if @attributes
saved_attributes = @saved_attributes.to_hash if @saved_attributes
Marshal.dump([attributes, saved_attributes])
end
def self._load(data)
new(*Marshal.load(data))
end
private
def self.extract_opts(args)
args.last.kind_of?(Hash) ? args.pop : {}
end
def self.modify_opts(args)
opts = extract_opts(args)
yield(opts)
args << opts
end
end
add support for clone
class ActiveDocument::Base
def self.path(path = nil)
@path = path if path
@path ||= (self == ActiveDocument::Base ? nil : ActiveDocument::Base.path)
end
def self.db_config(config = {})
@db_config ||= {}
@db_config.merge!(config)
ActiveDocument.db_config.merge(@db_config)
end
def self.database_name(database_name = nil)
if database_name
raise 'cannot modify database_name after db has been initialized' if @database_name
@database_name = database_name
else
return if self == ActiveDocument::Base
@database_name ||= name.underscore.gsub('/', '-').pluralize
end
end
@@environment = {}
def self.environment
@@environment[path] ||= ActiveDocument::Environment.new(path)
end
def self.database
@database
end
def database
self.class.database
end
def self.transaction(&block)
database.transaction(&block)
end
def transaction(&block)
self.class.transaction(&block)
end
def self.checkpoint(opts = {})
environment.checkpoint(opts)
end
def self.create(*args)
model = new(*args)
model.save
model
end
def self.primary_key(field_or_fields, opts = {})
raise 'primary key already defined' if @database
if @partition_by = opts[:partition_by]
@database = ActiveDocument::PartitionedDatabase.new(
:model_class => self,
:environment => environment,
:partition_by => @partition_by
)
(class << self; self; end).instance_eval do
alias_method opts[:partition_by].to_s.pluralize, :partitions
alias_method "with_#{opts[:partition_by]}", :with_partition
alias_method "with_each_#{opts[:partition_by]}", :with_each_partition
end
else
@database = environment.new_database(:model_class => self)
end
field = define_field_accessor(field_or_fields)
define_find_methods(field, :field => :primary_key) # find_by_field1_and_field2
define_field_accessor(field_or_fields, :primary_key)
define_find_methods(:primary_key) # find_by_primary_key
# Define shortcuts for partial keys.
define_partial_shortcuts(field_or_fields, :primary_key)
end
def self.partitions
database.partitions
end
def self.with_partition(partition, &block)
database.with_partition(partition, &block)
end
def self.with_each_partition(&block)
database.partitions.each do |partition|
database.with_partition(partition, &block)
end
end
def self.partition_by
@partition_by
end
def partition_by
self.class.partition_by
end
def partition
send(partition_by) if partition_by
end
def self.index_by(field_or_fields, opts = {})
raise "cannot have a multi_key index on an aggregate key" if opts[:multi_key] and field_or_fields.kind_of?(Array)
field = define_field_accessor(field_or_fields)
database.index_by(field, opts)
field_name = opts[:multi_key] ? field.to_s.singularize : field
define_find_methods(field_name, :field => field) # find_by_field1_and_field2
# Define shortcuts for partial keys.
define_partial_shortcuts(field_or_fields, field)
end
def self.close_environment
# Will close all databases in the environment.
environment.close
end
def self.find_by(field, *keys)
opts = extract_opts(keys)
opts[:field] = field
keys << :all if keys.empty?
database.find(keys, opts)
end
def self.find(key, opts = {})
doc = database.find([key], opts).first
raise ActiveDocument::DocumentNotFound, "Couldn't find #{name} with id #{key.inspect}" unless doc
doc
end
def self.count(field, key)
database.count(field, key)
end
class << self
attr_reader :page_key, :page_offset
def set_page_marker(key = nil, offset = nil)
@page_key = key
@page_offset = offset
end
def page_marker
[page_key, page_offset]
end
end
def self.define_field_accessor(field_or_fields, field = nil)
if field_or_fields.kind_of?(Array)
field ||= field_or_fields.join('_and_').to_sym
define_method(field) do
field_or_fields.collect {|f| self.send(f)}.flatten
end
elsif field
define_method(field) do
self.send(field_or_fields)
end
else
field = field_or_fields.to_sym
end
field
end
def self.define_find_methods(name, config = {})
field = config[:field] || name
(class << self; self; end).instance_eval do
define_method("find_by_#{name}") do |*args|
modify_opts(args) do |opts|
opts[:limit] = 1
opts[:partial] ||= config[:partial]
end
find_by(field, *args).first
end
define_method("find_all_by_#{name}") do |*args|
modify_opts(args) do |opts|
opts[:partial] ||= config[:partial]
end
find_by(field, *args)
end
end
end
def self.define_partial_shortcuts(fields, primary_field)
return unless fields.kind_of?(Array)
(fields.size - 1).times do |i|
name = fields[0..i].join('_and_')
next if respond_to?("find_by_#{name}")
define_find_methods(name, :field => primary_field, :partial => true)
end
end
def self.timestamps
reader(:created_at, :updated_at, :deleted_at)
end
def self.defaults(defaults = {})
@defaults ||= {}
@defaults.merge!(defaults)
end
def self.default(attr, default)
defaults[attr] = default
end
def self.reader(*attrs)
attrs.each do |attr|
define_method(attr) do
read_attribute(attr)
end
end
end
def self.bool_reader(*attrs)
attrs.each do |attr|
define_method(attr) do
!!read_attribute(attr)
end
define_method("#{attr}?") do
!!read_attribute(attr)
end
end
end
def self.writer(*attrs)
attrs.each do |attr|
define_method("#{attr}=") do |value|
attributes[attr] = value
end
end
end
def self.accessor(*attrs)
reader(*attrs)
writer(*attrs)
end
def self.bool_accessor(*attrs)
bool_reader(*attrs)
writer(*attrs)
end
def self.save_method(method_name)
define_method("#{method_name}!") do |*args|
value = send(method_name, *args)
save
value
end
end
def initialize(attributes = {}, saved_attributes = nil)
@attributes = HashWithIndifferentAccess.new(attributes) if attributes
@saved_attributes = HashWithIndifferentAccess.new(saved_attributes) if saved_attributes
# Initialize defaults if this is a new record.
if @saved_attributes.nil?
self.class.defaults.each do |attr, default|
next if @attributes.has_key?(attr)
@attributes[attr] = default.is_a?(Proc) ? default.bind(self).call : default.dup
end
end
# Set the partition field in case we are in a with_partition block.
if partition_by and partition.nil?
set_method = "#{partition_by}="
self.send(set_method, database.partition) if respond_to?(set_method)
end
end
attr_reader :saved_attributes
attr_accessor :locator_key
def attributes
@attributes ||= Marshal.load(Marshal.dump(saved_attributes))
end
def read_attribute(attr)
if @attributes.nil?
saved_attributes[attr]
else
attributes[attr]
end
end
save_method :update_attributes
def update_attributes(attrs = {})
attrs.each do |field, value|
self.send("#{field}=", value)
end
end
def to_json(*args)
attributes.to_json(*args)
end
def ==(other)
return false unless other.class == self.class
attributes == other.attributes
end
def new_record?
@saved_attributes.nil?
end
def changed?(field = nil)
return false unless @attributes and @saved_attributes
if field
send(field) != saved.send(field)
else
attributes != saved_attributes
end
end
def saved
raise 'no saved attributes for new record' if new_record?
@saved ||= self.class.new(saved_attributes)
end
def clone
cloned_attributes = Marshal.load(Marshal.dump(attributes))
uncloned_fields.each do |attr|
cloned_attributes.delete(attr)
end
self.class.new(cloned_attributes)
end
def self.uncloned_fields(*attrs)
if attrs.empty?
@uncloned_fields ||= [:created_at, :updated_at, :deleted_at]
else
uncloned_fields.concat(attrs)
end
end
def save
time = Time.now
attributes[:updated_at] = time if respond_to?(:updated_at)
attributes[:created_at] = time if respond_to?(:created_at) and new_record?
opts = {}
if changed?(:primary_key) or (partition_by and changed?(partition_by))
opts[:create] = true
saved.destroy
else
opts[:create] = new_record?
end
@saved_attributes = attributes
@attributes = nil
@saved = nil
database.save(self, opts)
end
def destroy
database.delete(self)
end
save_method :delete
def delete
raise 'cannot delete a record without deleted_at attribute' unless respond_to?(:deleted_at)
saved_attributes[:deleted_at] = Time.now
end
save_method :undelete
def undelete
raise 'cannot undelete a record without deleted_at attribute' unless respond_to?(:deleted_at)
saved_attributes.delete(:deleted_at)
end
def deleted?
respond_to?(:deleted_at) and not deleted_at.nil?
end
def _dump(ignored)
attributes = @attributes.to_hash if @attributes
saved_attributes = @saved_attributes.to_hash if @saved_attributes
Marshal.dump([attributes, saved_attributes])
end
def self._load(data)
new(*Marshal.load(data))
end
private
def self.extract_opts(args)
args.last.kind_of?(Hash) ? args.pop : {}
end
def self.modify_opts(args)
opts = extract_opts(args)
yield(opts)
args << opts
end
end
|
require 'test_helper'
class InheritTest < MiniTest::Spec
module SongRepresenter # it's important to have a global module so we can test if stuff gets overridden in the original module.
include Representable::Hash
property :name, :as => :title do
property :string, :as => :str
end
property :track, :as => :no
end
let (:song) { Song.new(Struct.new(:string).new("Roxanne"), 1) }
describe ":inherit plain property" do
representer! do
include SongRepresenter
property :track, :inherit => true, :getter => lambda { |*| "n/a" }
end
it { SongRepresenter.prepare(song).to_hash.must_equal({"title"=>{"str"=>"Roxanne"}, "no"=>1}) }
it { representer.prepare(song).to_hash.must_equal({"title"=>{"str"=>"Roxanne"}, "no"=>"n/a"}) } # as: inherited.
end
describe ":inherit with empty inline representer" do
representer! do
include SongRepresenter
property :name, :inherit => true do # inherit as: title
# that doesn't make sense.
end
end
it { SongRepresenter.prepare(Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
it { representer.prepare( Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
end
describe ":inherit with overriding inline representer" do
representer! do
include SongRepresenter
property :name, :inherit => true do # inherit as: title
property :string, :as => :s
property :length
end
end
it { representer.prepare( Song.new(Struct.new(:string, :length).new("Believe It", 10), 1)).to_hash.must_equal({"title"=>{"s"=>"Believe It","length"=>10}, "no"=>1}) }
end
describe ":inherit with empty inline and options" do
representer! do
include SongRepresenter
property :name, :inherit => true, :as => :name do # inherit module, only.
# that doesn't make sense.
end
end
it { SongRepresenter.prepare(Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
it { representer.prepare( Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"name"=>{"str"=>"Believe It"}, "no"=>1}) }
end
describe ":inherit with inline without block but options" do
representer! do
include SongRepresenter
property :name, :inherit => true, :as => :name # FIXME: add :getter or something else dynamic since this is double-wrapped.
end
it { SongRepresenter.prepare(Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
it { representer.prepare( Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"name"=>{"str"=>"Believe It"}, "no"=>1}) }
end
# no :inherit
describe "overwriting without :inherit" do
representer! do
include SongRepresenter
property :track, :representable => true
end
it "replaces inherited property" do
representer.representable_attrs.size.must_equal 2
definition = representer.representable_attrs[:track] # TODO: find a better way to assert Definition identity.
definition.keys.size.must_equal 2
definition[:representable]. must_equal true
definition[:as].evaluate(nil).must_equal "track" # was "no".
end
end
end
add test where inherit: true doesn't work in a Decorator.
require 'test_helper'
class InheritTest < MiniTest::Spec
module SongRepresenter # it's important to have a global module so we can test if stuff gets overridden in the original module.
include Representable::Hash
property :name, :as => :title do
property :string, :as => :str
end
property :track, :as => :no
end
let (:song) { Song.new(Struct.new(:string).new("Roxanne"), 1) }
describe ":inherit plain property" do
representer! do
include SongRepresenter
property :track, :inherit => true, :getter => lambda { |*| "n/a" }
end
it { SongRepresenter.prepare(song).to_hash.must_equal({"title"=>{"str"=>"Roxanne"}, "no"=>1}) }
it { representer.prepare(song).to_hash.must_equal({"title"=>{"str"=>"Roxanne"}, "no"=>"n/a"}) } # as: inherited.
end
describe ":inherit with empty inline representer" do
representer! do
include SongRepresenter
property :name, :inherit => true do # inherit as: title
# that doesn't make sense.
end
end
it { SongRepresenter.prepare(Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
it { representer.prepare( Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
end
describe ":inherit with overriding inline representer" do
representer! do
include SongRepresenter
property :name, :inherit => true do # inherit as: title
property :string, :as => :s
property :length
end
end
it { representer.prepare( Song.new(Struct.new(:string, :length).new("Believe It", 10), 1)).to_hash.must_equal({"title"=>{"s"=>"Believe It","length"=>10}, "no"=>1}) }
end
describe ":inherit with empty inline and options" do
representer! do
include SongRepresenter
property :name, :inherit => true, :as => :name do # inherit module, only.
# that doesn't make sense.
end
end
it { SongRepresenter.prepare(Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
it { representer.prepare( Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"name"=>{"str"=>"Believe It"}, "no"=>1}) }
end
describe ":inherit with inline without block but options" do
representer! do
include SongRepresenter
property :name, :inherit => true, :as => :name # FIXME: add :getter or something else dynamic since this is double-wrapped.
end
it { SongRepresenter.prepare(Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"title"=>{"str"=>"Believe It"}, "no"=>1}) }
it { representer.prepare( Song.new(Struct.new(:string).new("Believe It"), 1)).to_hash.must_equal({"name"=>{"str"=>"Believe It"}, "no"=>1}) }
end
# no :inherit
describe "overwriting without :inherit" do
representer! do
include SongRepresenter
property :track, :representable => true
end
it "replaces inherited property" do
representer.representable_attrs.size.must_equal 2
definition = representer.representable_attrs[:track] # TODO: find a better way to assert Definition identity.
definition.keys.size.must_equal 2
definition[:representable]. must_equal true
definition[:as].evaluate(nil).must_equal "track" # was "no".
end
end
# decorator
describe ":inherit with decorator" do
representer!(:decorator => true) do
property :hit do
property :title
end
end
let (:inheriting) {
class InheritingDecorator < representer
property :hit, :inherit => true do
end
self
end
}
it { inheriting.new(OpenStruct.new(:hit => OpenStruct.new(:title => "Hole In Your Soul"))).to_hash.must_equal {} }
end
end |
require "rails/railtie"
module ActiveVault
class Railtie < Rails::Railtie # :nodoc:
config.action_file = ActiveSupport::OrderedOptions.new
config.eager_load_namespaces << ActiveVault
initializer "action_file.routes" do
require "active_vault/disk_controller"
config.after_initialize do |app|
app.routes.prepend do
get "/rails/blobs/:encoded_key" => "active_vault/disk#show", as: :rails_disk_blob
end
end
end
initializer "action_file.attached" do
require "active_vault/attached"
ActiveSupport.on_load(:active_record) do
extend ActiveVault::Attached::Macros
end
end
end
end
Fix configuration names
require "rails/railtie"
module ActiveVault
class Railtie < Rails::Railtie # :nodoc:
config.active_vault = ActiveSupport::OrderedOptions.new
config.eager_load_namespaces << ActiveVault
initializer "active_vault.routes" do
require "active_vault/disk_controller"
config.after_initialize do |app|
app.routes.prepend do
get "/rails/blobs/:encoded_key" => "active_vault/disk#show", as: :rails_disk_blob
end
end
end
initializer "active_vault.attached" do
require "active_vault/attached"
ActiveSupport.on_load(:active_record) do
extend ActiveVault::Attached::Macros
end
end
end
end
|
module ActiveSearch
VERSION = "0.0.9"
end
Bumped version to 0.0.10
module ActiveSearch
VERSION = "0.0.10"
end
|
class Bot::Adapter::Irc::Handler < EM::Connection
require_relative 'rfc2812'
include Bot::Adapter::Irc::RFC2812
def initialize(adapter, s=Hash.new(false))
@adapter = adapter
@s = s
@registered = false
@ping_state = :inactive
@buffer = BufferedTokenizer.new("\r\n")
end
def connection_completed
start_tls if @s[:ssl]
register(@s[:nick])
keep_alive
end
def send_data(data)
Bot.log.info "#{self.class.name} #{@s[:name]}\n\t#{'->'.green} #{data}"
super @adapter.format(data) + "\n"
rescue Exception => e
Bot.log.error "#{self.class.name} #{@s[:name]}\n#{e}\n#{e.backtrace.join("\n")}}"
end
alias_method :send, :send_data
def receive_data(data)
data = @buffer.extract(data)
data.each do |line|
Bot.log.info "#{self.class.name} #{@s[:name]}\n\t#{'<-'.cyan} #{line.chomp}"
handle_message(parse_data(line))
end
rescue Exception => e
Bot.log.error "#{self.class.name} #{@s[:name]}\n#{e}\n#{e.backtrace.join("\n")}}"
end
def parse_data(data)
sender, real_name, hostname, type, channel = nil
privm_regex = /^:(?<sender>.+)!(?<real_name>.+)@(?<hostname>.+)/
origin = self
raw = data
text = data.split(' :').last.chomp
data = data.split(' ')
internal_type = :server
if data[0] == 'PING'
type = :ping
sender = data[1]
elsif data[1] == 'PONG'
type = :pong
sender = data[0]
channel = data[2]
elsif data[1] == 'PRIVMSG'
type = :privmsg
matches = data[0].match(privm_regex)
sender = matches[:sender]
real_name = matches[:real_name]
hostname = matches[:hostname]
channel = data[2]
# Handle PMs - reply to user directly.
channel = ((data[2] == @s[:nick]) ? matches[:sender] : data[2])
internal_type = :client
elsif /^(JOIN|PART)$/ === data[1]
type = data[1].downcase.to_sym
matches = data[0].match(privm_regex)
sender = matches[:sender]
real_name = matches[:real_name]
hostname = matches[:hostname]
channel = data[2].gsub(/^:/, '')
elsif /^\d+$/ === data[1]
# If message type is numeric
type = data[1].to_sym
sender = data[0].delete(':')
channel = data[2]
end
Bot::Adapter::Irc::Message.new do |m|
m.type = type
m.sender = sender
m.real_name = real_name
m.hostname = hostname
m.channel = channel
m.text = text
m.raw = raw
m.origin = origin
m.internal_type = internal_type
end
end
def handle_message(m)
case m.type
when :ping
send "PONG #{m.sender} #{m.text}"
when :pong
@ping_state = :received
@adapter.latency = (Time.now.to_f - m.text.to_f) * 1000
when :"001"
@registered = true
@s[:default_channels].each { |c| join(c) }
when :"433"
nick = m.raw.split(' ')[3]
register(nick + '_')
EM.add_timer(900) { nick(@s[:nick]) } # Try to reclaim desired nick
when :privmsg
check_trigger(m)
end
@adapter.publish(m)
end
def check_trigger(m)
if /^#{Bot::SHORT_TRIGGER}([^ ]*)/i === m.text || # !command
/^#{@s[:nick]}: ([^ ]*)/i === m.text # BotNick: command
trigger = $1
@adapter.trigger_plugin(trigger, m)
end
end
def register(nick)
nick(nick)
user(nick, 0, ":Romani ite domum")
end
def keep_alive
period_timer = EventMachine::PeriodicTimer.new(300) do
send "PING #{Time.now.to_f}"
@ping_state = :waiting
EM.add_timer(30) do
if @ping_state == :waiting
period_timer.cancel
@adapter.reconnect
end
end
end
end
def unbind
Bot.log.warn "Connection closed: reconnecting"
@adapter.reconnect(@s[:name]) unless $restart || $shutdown
end
end
IRC: Add reconnect delay on socket close
class Bot::Adapter::Irc::Handler < EM::Connection
require_relative 'rfc2812'
include Bot::Adapter::Irc::RFC2812
def initialize(adapter, s=Hash.new(false))
@adapter = adapter
@s = s
@registered = false
@ping_state = :inactive
@buffer = BufferedTokenizer.new("\r\n")
end
def connection_completed
start_tls if @s[:ssl]
register(@s[:nick])
keep_alive
end
def send_data(data)
Bot.log.info "#{self.class.name} #{@s[:name]}\n\t#{'->'.green} #{data}"
super @adapter.format(data) + "\n"
rescue Exception => e
Bot.log.error "#{self.class.name} #{@s[:name]}\n#{e}\n#{e.backtrace.join("\n")}}"
end
alias_method :send, :send_data
def receive_data(data)
data = @buffer.extract(data)
data.each do |line|
Bot.log.info "#{self.class.name} #{@s[:name]}\n\t#{'<-'.cyan} #{line.chomp}"
handle_message(parse_data(line))
end
rescue Exception => e
Bot.log.error "#{self.class.name} #{@s[:name]}\n#{e}\n#{e.backtrace.join("\n")}}"
end
def parse_data(data)
sender, real_name, hostname, type, channel = nil
privm_regex = /^:(?<sender>.+)!(?<real_name>.+)@(?<hostname>.+)/
origin = self
raw = data
text = data.split(' :').last.chomp
data = data.split(' ')
internal_type = :server
if data[0] == 'PING'
type = :ping
sender = data[1]
elsif data[1] == 'PONG'
type = :pong
sender = data[0]
channel = data[2]
elsif data[1] == 'PRIVMSG'
type = :privmsg
matches = data[0].match(privm_regex)
sender = matches[:sender]
real_name = matches[:real_name]
hostname = matches[:hostname]
channel = data[2]
# Handle PMs - reply to user directly.
channel = ((data[2] == @s[:nick]) ? matches[:sender] : data[2])
internal_type = :client
elsif /^(JOIN|PART)$/ === data[1]
type = data[1].downcase.to_sym
matches = data[0].match(privm_regex)
sender = matches[:sender]
real_name = matches[:real_name]
hostname = matches[:hostname]
channel = data[2].gsub(/^:/, '')
elsif /^\d+$/ === data[1]
# If message type is numeric
type = data[1].to_sym
sender = data[0].delete(':')
channel = data[2]
end
Bot::Adapter::Irc::Message.new do |m|
m.type = type
m.sender = sender
m.real_name = real_name
m.hostname = hostname
m.channel = channel
m.text = text
m.raw = raw
m.origin = origin
m.internal_type = internal_type
end
end
def handle_message(m)
case m.type
when :ping
send "PONG #{m.sender} #{m.text}"
when :pong
@ping_state = :received
@adapter.latency = (Time.now.to_f - m.text.to_f) * 1000
when :"001"
@registered = true
@s[:default_channels].each { |c| join(c) }
when :"433"
nick = m.raw.split(' ')[3]
register(nick + '_')
EM.add_timer(900) { nick(@s[:nick]) } # Try to reclaim desired nick
when :privmsg
check_trigger(m)
end
@adapter.publish(m)
end
def check_trigger(m)
if /^#{Bot::SHORT_TRIGGER}([^ ]*)/i === m.text || # !command
/^#{@s[:nick]}: ([^ ]*)/i === m.text # BotNick: command
trigger = $1
@adapter.trigger_plugin(trigger, m)
end
end
def register(nick)
nick(nick)
user(nick, 0, ":Romani ite domum")
end
def keep_alive
period_timer = EventMachine::PeriodicTimer.new(300) do
send "PING #{Time.now.to_f}"
@ping_state = :waiting
EM.add_timer(30) do
if @ping_state == :waiting
period_timer.cancel
@adapter.reconnect
end
end
end
end
def unbind
Bot.log.warn "Connection closed: reconnecting in 30 seconds..."
EM.add_timer(30) do
@adapter.reconnect(@s[:name]) unless $restart || $shutdown
end
end
end |
require 'active_resource'
module AirbrakeSymbolicate
class DsymFinder
@@dsyms = nil
class << self
def dsym_for_error(error)
find_dsyms unless @@dsyms
@@dsyms[error.environment.git_commit] || @@dsyms[error.environment.application_version]
end
private
# use spotlight to find all the xcode archives
# then use the Info.plist inside those archives to try and look up a git commit hash
def find_dsyms
@@dsyms = {}
files = `mdfind 'kMDItemKind = "Xcode Archive"'`.split("\n")
files.each do |f|
# puts `ls '#{f.chomp}'`
info = `find '#{f}/Products' -name Info.plist`.chomp
if commit = plist_val(info, 'GCGitCommitHash')
if bin_file = Dir[File.join(f, '/dSYMs/*.dSYM/**/DWARF/*')].first
@@dsyms[commit] = bin_file
end
else
short_version = plist_val(info, 'CFBundleShortVersionString')
long_version = plist_val(info, 'CFBundleVersion')
# this is the format in HTApplicationVersion() in hoptoad-ios
@@dsyms["#{CFBundleShortVersionString} (#{CFBundleVersion})"] = bin_file
end
end
end
def plist_val(plist, key)
`/usr/libexec/PlistBuddy -c 'Print :#{key}' '#{plist}' 2>/dev/null`.chomp
end
end
end
class Symbolicator
class << self
def symbolicated_backtrace(error)
if dsym = DsymFinder.dsym_for_error(error)
error.backtrace.line.map {|l| Symbolicator.symbolicate_line(dsym, l)}
end
end
def symbolicate_line(dsym_file, line)
binname = File.basename(dsym_file)
if line[/#{binname}/] && loc = line[/0x\w+/]
`/usr/bin/atos -arch armv7 -o "#{dsym_file}" #{loc}`.sub(/^[-_]+/, '')
else
line
end.chomp
end
end
end
class Airbrake < ActiveResource::Base
cattr_accessor :auth_token
class << self
def account=(a)
self.site = "https://#{a}.airbrake.io/" if a
self.format = ActiveResource::Formats::XmlFormat
end
def find(*arguments)
arguments = append_auth_token_to_params(*arguments)
super(*arguments)
end
def append_auth_token_to_params(*arguments)
raise RuntimeError.new("Airbrake.auth_token must be set!") if !auth_token
opts = arguments.last.is_a?(Hash) ? arguments.pop : {}
opts = opts.has_key?(:params) ? opts : opts.merge(:params => {})
opts[:params] = opts[:params].merge(:auth_token => auth_token)
arguments << opts
arguments
end
end
end
class Error < Airbrake
end
end
Remove support for identifying bin files by git commit
The API results returned for my Airbrake account don't include the
git_commit value, which caused the a method not found exception
when processing results.
require 'active_resource'
module AirbrakeSymbolicate
class DsymFinder
@@dsyms = nil
class << self
def dsym_for_error(error)
find_dsyms unless @@dsyms
@@dsyms[error.environment.application_version]
end
private
# use spotlight to find all the xcode archives
# then use the Info.plist inside those archives to try and look up a git commit hash
def find_dsyms
@@dsyms = {}
files = `mdfind 'kMDItemKind = "Xcode Archive"'`.split("\n")
files.each do |f|
# puts `ls '#{f.chomp}'`
info = `find '#{f}/Products' -name Info.plist`.chomp
# this is the version reported as application-version by Airbrake
version = plist_val(info, 'CFBundleVersion')
if bin_file = Dir[File.join(f, '/dSYMs/*.dSYM/**/DWARF/*')].first
@@dsyms[version] = bin_file
end
# I don't see the git-commit value in the values Airbrake
# returns for my errors. Maybe these are only added with github
# integration?
#if commit = plist_val(info, 'GCGitCommitHash')
#@@dsyms[commit] = bin_file
#end
#else
# The responses I get from Airbrake just have the CFBundleVersion value,
# not sure if there are some conditions where both versions below are returned.
#short_version = plist_val(info, 'CFBundleShortVersionString')
#long_version = plist_val(info, 'CFBundleVersion')
#@@dsyms["#{CFBundleShortVersionString} (#{CFBundleVersion})"] = bin_file
#end
end
end
def plist_val(plist, key)
`/usr/libexec/PlistBuddy -c 'Print :#{key}' '#{plist}' 2>/dev/null`.chomp
end
end
end
class Symbolicator
class << self
def symbolicated_backtrace(error)
if dsym = DsymFinder.dsym_for_error(error)
error.backtrace.line.map {|l| Symbolicator.symbolicate_line(dsym, l)}
end
end
def symbolicate_line(dsym_file, line)
binname = File.basename(dsym_file)
if line[/#{binname}/] && loc = line[/0x\w+/]
`/usr/bin/atos -arch armv7 -o "#{dsym_file}" #{loc}`.sub(/^[-_]+/, '')
else
line
end.chomp
end
end
end
class Airbrake < ActiveResource::Base
cattr_accessor :auth_token
class << self
def account=(a)
self.site = "https://#{a}.airbrake.io/" if a
self.format = ActiveResource::Formats::XmlFormat
end
def find(*arguments)
arguments = append_auth_token_to_params(*arguments)
super(*arguments)
end
def append_auth_token_to_params(*arguments)
raise RuntimeError.new("Airbrake.auth_token must be set!") if !auth_token
opts = arguments.last.is_a?(Hash) ? arguments.pop : {}
opts = opts.has_key?(:params) ? opts : opts.merge(:params => {})
opts[:params] = opts[:params].merge(:auth_token => auth_token)
arguments << opts
arguments
end
end
end
class Error < Airbrake
end
end
|
module AMQ
module Protocol
VERSION = "0.7.0.beta1"
end # Protocol
end # AMQ
Now working on 0.7.0.beta2.pre
module AMQ
module Protocol
VERSION = "0.7.0.beta2.pre"
end # Protocol
end # AMQ
|
module Ans
module JpIndex
VERSION = "1.0.1"
end
end
up version
module Ans
module JpIndex
VERSION = "1.0.2"
end
end
|
module API
# Projects API
class ProjectSnippets < Grape::API
before { authenticate! }
resource :projects do
helpers do
def handle_project_member_errors(errors)
if errors[:project_access].any?
error!(errors[:project_access], 422)
end
not_found!
end
end
# Get a project snippets
#
# Parameters:
# id (required) - The ID of a project
# Example Request:
# GET /projects/:id/snippets
get ":id/snippets" do
present paginate(user_project.snippets), with: Entities::ProjectSnippet
end
# Get a project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# Example Request:
# GET /projects/:id/snippets/:snippet_id
get ":id/snippets/:snippet_id" do
@snippet = user_project.snippets.find(params[:snippet_id])
present @snippet, with: Entities::ProjectSnippet
end
# Create a new project snippet
#
# Parameters:
# id (required) - The ID of a project
# title (required) - The title of a snippet
# file_name (required) - The name of a snippet file
# lifetime (optional) - The expiration date of a snippet
# code (required) - The content of a snippet
# Example Request:
# POST /projects/:id/snippets
post ":id/snippets" do
authorize! :write_project_snippet, user_project
required_attributes! [:title, :file_name, :code]
attrs = attributes_for_keys [:title, :file_name]
attrs[:expires_at] = params[:lifetime] if params[:lifetime].present?
attrs[:content] = params[:code] if params[:code].present?
@snippet = user_project.snippets.new attrs
@snippet.author = current_user
if @snippet.save
present @snippet, with: Entities::ProjectSnippet
else
not_found!
end
end
# Update an existing project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# title (optional) - The title of a snippet
# file_name (optional) - The name of a snippet file
# lifetime (optional) - The expiration date of a snippet
# code (optional) - The content of a snippet
# Example Request:
# PUT /projects/:id/snippets/:snippet_id
put ":id/snippets/:snippet_id" do
@snippet = user_project.snippets.find(params[:snippet_id])
authorize! :modify_project_snippet, @snippet
attrs = attributes_for_keys [:title, :file_name]
attrs[:expires_at] = params[:lifetime] if params[:lifetime].present?
attrs[:content] = params[:code] if params[:code].present?
if @snippet.update_attributes attrs
present @snippet, with: Entities::ProjectSnippet
else
not_found!
end
end
# Delete a project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# Example Request:
# DELETE /projects/:id/snippets/:snippet_id
delete ":id/snippets/:snippet_id" do
begin
@snippet = user_project.snippets.find(params[:snippet_id])
authorize! :modify_project_snippet, @snippet
@snippet.destroy
rescue
end
end
# Get a raw project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# Example Request:
# GET /projects/:id/snippets/:snippet_id/raw
get ":id/snippets/:snippet_id/raw" do
@snippet = user_project.snippets.find(params[:snippet_id])
content_type 'text/plain'
present @snippet.content
end
end
end
end
Fix snippet raw content being escaped
module API
# Projects API
class ProjectSnippets < Grape::API
before { authenticate! }
resource :projects do
helpers do
def handle_project_member_errors(errors)
if errors[:project_access].any?
error!(errors[:project_access], 422)
end
not_found!
end
end
# Get a project snippets
#
# Parameters:
# id (required) - The ID of a project
# Example Request:
# GET /projects/:id/snippets
get ":id/snippets" do
present paginate(user_project.snippets), with: Entities::ProjectSnippet
end
# Get a project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# Example Request:
# GET /projects/:id/snippets/:snippet_id
get ":id/snippets/:snippet_id" do
@snippet = user_project.snippets.find(params[:snippet_id])
present @snippet, with: Entities::ProjectSnippet
end
# Create a new project snippet
#
# Parameters:
# id (required) - The ID of a project
# title (required) - The title of a snippet
# file_name (required) - The name of a snippet file
# lifetime (optional) - The expiration date of a snippet
# code (required) - The content of a snippet
# Example Request:
# POST /projects/:id/snippets
post ":id/snippets" do
authorize! :write_project_snippet, user_project
required_attributes! [:title, :file_name, :code]
attrs = attributes_for_keys [:title, :file_name]
attrs[:expires_at] = params[:lifetime] if params[:lifetime].present?
attrs[:content] = params[:code] if params[:code].present?
@snippet = user_project.snippets.new attrs
@snippet.author = current_user
if @snippet.save
present @snippet, with: Entities::ProjectSnippet
else
not_found!
end
end
# Update an existing project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# title (optional) - The title of a snippet
# file_name (optional) - The name of a snippet file
# lifetime (optional) - The expiration date of a snippet
# code (optional) - The content of a snippet
# Example Request:
# PUT /projects/:id/snippets/:snippet_id
put ":id/snippets/:snippet_id" do
@snippet = user_project.snippets.find(params[:snippet_id])
authorize! :modify_project_snippet, @snippet
attrs = attributes_for_keys [:title, :file_name]
attrs[:expires_at] = params[:lifetime] if params[:lifetime].present?
attrs[:content] = params[:code] if params[:code].present?
if @snippet.update_attributes attrs
present @snippet, with: Entities::ProjectSnippet
else
not_found!
end
end
# Delete a project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# Example Request:
# DELETE /projects/:id/snippets/:snippet_id
delete ":id/snippets/:snippet_id" do
begin
@snippet = user_project.snippets.find(params[:snippet_id])
authorize! :modify_project_snippet, @snippet
@snippet.destroy
rescue
end
end
# Get a raw project snippet
#
# Parameters:
# id (required) - The ID of a project
# snippet_id (required) - The ID of a project snippet
# Example Request:
# GET /projects/:id/snippets/:snippet_id/raw
get ":id/snippets/:snippet_id/raw" do
@snippet = user_project.snippets.find(params[:snippet_id])
env['api.format'] = :txt
content_type 'text/plain'
present @snippet.content
end
end
end
end
|
# OOOR: Open Object On Rails
# Copyright (C) 2009-2011 Akretion LTDA (<http://www.akretion.com>).
# Author: Raphaël Valyi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
module Ooor
class ActionWindow
class << self
attr_accessor :klass, :openerp_act_window, :views
def define_action_window(act_window_param)
act_win_class = Class.new(ActionWindow)
if act_window_param.ancestors.include?(OpenObjectResource)
act_win_class.openerp_act_window = IrActionsAct_window.find(:first, :domain=>[['res_model', '=', act_window_param.openerp_model]])
act_win_class.klass = act_window_param
act_win_class.views = {}
Object.const_set("SuperTest", act_win_class)
end #TODO else
act_win_class
end
def get_view_id(mode)
IrActionsAct_window.read(@openerp_act_window.id, ["view_ids"])["view_ids"]
IrActionsAct_windowView.read([9,10], ["view_mode"]).each do |view_hash|
return view_hash["id"] if view_hash["view_mode"] == mode.to_s
end
IrUiView.search([['model', '=', act_window_param.openerp_model], ['type', '=', mode.to_s]])
end
def get_fields(mode)
@views[mode] ||= @klass.fields_view_get(get_view_id(mode), mode)
@views[mode]['fields']
end
def column_names
reload_fields_definition
@column_names ||= ["id"] + get_fields('tree').keys()
end
def columns_hash
reload_fields_definition
unless @column_hash
@column_hash = {"id" => {"string"=>"Id", "type"=>"integer"}}.merge(get_fields('tree'))
def @column_hash.type
col_type = @column_hash['type'].to_sym #TODO mapping ?
col_type == :char && :string || col_type
end
end
@column_hash
end
def primary_key
"id"
end
def get_arch(mode)
#TODO
end
def open(mode='tree', ids=nil)#TODO: fix!
if view_mode.index(mode)
the_view_id = false
relations['views'].each do |tuple|
the_view_id = tuple[0] if tuple[1] == mode
end
self.class.ooor.build_object_view(self.class.ooor.const_get(res_model), the_view_id, mode, domain || [], ids, {})
end
end
def method_missing(method, *args, &block)
@klass.send(method, *args, &block)
end
end
end
end
format code
# OOOR: Open Object On Rails
# Copyright (C) 2009-2011 Akretion LTDA (<http://www.akretion.com>).
# Author: Raphaël Valyi
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
module Ooor
class ActionWindow
class << self
attr_accessor :klass, :openerp_act_window, :views
def define_action_window(act_window_param)
act_win_class = Class.new(ActionWindow)
if act_window_param.ancestors.include?(OpenObjectResource)
act_win_class.openerp_act_window = IrActionsAct_window.find(:first, :domain=>[['res_model', '=', act_window_param.openerp_model]])
act_win_class.klass = act_window_param
act_win_class.views = {}
Object.const_set("SuperTest", act_win_class)
end #TODO else
act_win_class
end
def get_view_id(mode)
IrActionsAct_window.read(@openerp_act_window.id, ["view_ids"])["view_ids"]
IrActionsAct_windowView.read([9,10], ["view_mode"]).each do |view_hash|
return view_hash["id"] if view_hash["view_mode"] == mode.to_s
end
IrUiView.search([['model', '=', act_window_param.openerp_model], ['type', '=', mode.to_s]])
end
def get_fields(mode)
@views[mode] ||= @klass.fields_view_get(get_view_id(mode), mode)
@views[mode]['fields']
end
def column_names
reload_fields_definition
@column_names ||= ["id"] + get_fields('tree').keys()
end
def columns_hash
reload_fields_definition
unless @column_hash
@column_hash = {"id" => {"string"=>"Id", "type"=>"integer"}}.merge(get_fields('tree'))
def @column_hash.type
col_type = @column_hash['type'].to_sym #TODO mapping ?
col_type == :char && :string || col_type
end
end
@column_hash
end
def primary_key
"id"
end
def get_arch(mode)
#TODO
end
def open(mode='tree', ids=nil)#TODO: fix!
if view_mode.index(mode)
the_view_id = false
relations['views'].each do |tuple|
the_view_id = tuple[0] if tuple[1] == mode
end
self.class.ooor.build_object_view(self.class.ooor.const_get(res_model), the_view_id, mode, domain || [], ids, {})
end
end
def method_missing(method, *args, &block)
@klass.send(method, *args, &block)
end
end
end
end |
require 'yaml'
module Aptly
module Watcher
module Config
class << self
def parse(config_file)
config = YAML.load_file(config_file)
valid_config!(config)
config = parse_tildes(config)
config
end
def valid_config!(config)
raise ArgumentError, "Config file missing :pidfile:" unless config[:pidfile]
raise ArgumentError, "Config file missing :conf:" unless config[:conf]
raise ArgumentError, "Config file missing :log:" unless config[:log]
raise ArgumentError, "Config file missing :repos:" unless config[:repos]
raise ArgumentError, "Config file missing :distrib:" unless config[:distrib]
raise ArgumentError, "Config file missing :incoming_dir:" unless config[:incoming_dir]
end
# Parse any tildes into the full home path
def parse_tildes(config)
[:pidfile, :conf, :incoming_dir, :log].each do |key|
config[key].sub! /~/, ENV['HOME']
end
config
end
end
end
end
end
added config file exists and not empty check
require 'yaml'
module Aptly
module Watcher
module Config
class << self
def parse(config_file)
raise ArgumentError, "Config file not found: #{config_file}" unless File.exist?(config_file)
config = YAML.load_file(config_file)
valid_config!(config)
config = parse_tildes(config)
config
end
def valid_config!(config)
raise ArgumentError, "Config file was empty" unless config
raise ArgumentError, "Config file missing :pidfile:" unless config[:pidfile]
raise ArgumentError, "Config file missing :conf:" unless config[:conf]
raise ArgumentError, "Config file missing :log:" unless config[:log]
raise ArgumentError, "Config file missing :repos:" unless config[:repos]
raise ArgumentError, "Config file missing :distrib:" unless config[:distrib]
raise ArgumentError, "Config file missing :incoming_dir:" unless config[:incoming_dir]
end
# Parse any tildes into the full home path
def parse_tildes(config)
[:pidfile, :conf, :incoming_dir, :log].each do |key|
config[key].sub! /~/, ENV['HOME']
end
config
end
end
end
end
end |
ArJdbc.load_java_part :Derby
require 'arjdbc/util/table_copier'
require 'arjdbc/derby/schema_creation' # AR 4.x
module ArJdbc
module Derby
include Util::TableCopier
def self.extended(adapter)
require 'arjdbc/derby/active_record_patch'
end
def self.included(base)
require 'arjdbc/derby/active_record_patch'
end
# @see ActiveRecord::ConnectionAdapters::JdbcAdapter#jdbc_connection_class
def self.jdbc_connection_class
::ActiveRecord::ConnectionAdapters::DerbyJdbcConnection
end
# @see ActiveRecord::ConnectionAdapters::JdbcColumn#column_types
def self.column_selector
[ /derby/i, lambda { |config, column| column.extend(Column) } ]
end
# @private
@@emulate_booleans = true
# Boolean emulation can be disabled using :
#
# ArJdbc::Derby.emulate_booleans = false
#
def self.emulate_booleans?; @@emulate_booleans; end
# @deprecated Use {#emulate_booleans?} instead.
def self.emulate_booleans; @@emulate_booleans; end
# @see #emulate_booleans?
def self.emulate_booleans=(emulate); @@emulate_booleans = emulate; end
# @note Part of this module is implemented in "native" Java.
# @see ActiveRecord::ConnectionAdapters::JdbcColumn
module Column
private
def extract_limit(sql_type)
case @sql_type = sql_type.downcase
when /^smallint/i then @sql_type = 'smallint'; limit = 2
when /^bigint/i then @sql_type = 'bigint'; limit = 8
when /^double/i then @sql_type = 'double'; limit = 8 # DOUBLE PRECISION
when /^real/i then @sql_type = 'real'; limit = 4
when /^integer/i then @sql_type = 'integer'; limit = 4
when /^datetime/i then @sql_type = 'datetime'; limit = nil
when /^timestamp/i then @sql_type = 'timestamp'; limit = nil
when /^time/i then @sql_type = 'time'; limit = nil
when /^date/i then @sql_type = 'date'; limit = nil
when /^xml/i then @sql_type = 'xml'; limit = nil
else
limit = super
# handle maximum length for a VARCHAR string :
limit = 32672 if ! limit && @sql_type.index('varchar') == 0
end
limit
end
def simplified_type(field_type)
case field_type
when /^smallint/i then Derby.emulate_booleans? ? :boolean : :integer
when /^bigint|int/i then :integer
when /^real|double/i then :float
when /^dec/i then # DEC is a DECIMAL alias
extract_scale(field_type) == 0 ? :integer : :decimal
when /^timestamp/i then :datetime
when /^xml/i then :xml
when 'long varchar' then :text
when /for bit data/i then :binary
# :name=>"long varchar for bit data", :limit=>32700
# :name=>"varchar() for bit data", :limit=>32672
# :name=>"char() for bit data", :limit=>254}
else
super
end
end
# Post process default value from JDBC into a Rails-friendly format (columns{-internal})
def default_value(value)
# JDBC returns column default strings with actual single quotes around the value.
return $1 if value =~ /^'(.*)'$/
return nil if value == "GENERATED_BY_DEFAULT"
value
end
end
# @see ActiveRecord::ConnectionAdapters::Jdbc::ArelSupport
def self.arel_visitor_type(config = nil)
require 'arel/visitors/derby'; ::Arel::Visitors::Derby
end
ADAPTER_NAME = 'Derby'.freeze
def adapter_name
ADAPTER_NAME
end
# @private
def init_connection(jdbc_connection)
md = jdbc_connection.meta_data
major_version = md.database_major_version; minor_version = md.database_minor_version
if major_version < 10 || (major_version == 10 && minor_version < 5)
raise ::ActiveRecord::ConnectionNotEstablished, "Derby adapter requires Derby >= 10.5"
end
if major_version == 10 && minor_version < 8 # 10.8 ~ supports JDBC 4.1
config[:connection_alive_sql] ||=
'SELECT 1 FROM SYS.SYSSCHEMAS FETCH FIRST 1 ROWS ONLY' # FROM clause mandatory
else
# NOTE: since the loaded Java driver class can't change :
Derby.send(:remove_method, :init_connection) rescue nil
end
end
def configure_connection
# must be done or SELECT...FOR UPDATE won't work how we expect :
tx_isolation = config[:transaction_isolation] # set false to leave as is
tx_isolation = :serializable if tx_isolation.nil?
@connection.transaction_isolation = tx_isolation if tx_isolation
# if a user name was specified upon connection, the user's name is the
# default schema for the connection, if a schema with that name exists
set_schema(config[:schema]) if config.key?(:schema)
end
def index_name_length
128
end
NATIVE_DATABASE_TYPES = {
:primary_key => "int GENERATED BY DEFAULT AS identity NOT NULL PRIMARY KEY",
:string => { :name => "varchar", :limit => 255 }, # 32672
:text => { :name => "clob" }, # 2,147,483,647
:char => { :name => "char", :limit => 254 }, # JDBC limit: 254
:binary => { :name => "blob" }, # 2,147,483,647
:float => { :name => "float", :limit => 8 }, # DOUBLE PRECISION
:real => { :name => "real", :limit => 4 }, # JDBC limit: 23
:double => { :name => "double", :limit => 8 }, # JDBC limit: 52
:decimal => { :name => "decimal", :precision => 5, :scale => 0 }, # JDBC limit: 31
:numeric => { :name => "decimal", :precision => 5, :scale => 0 }, # JDBC limit: 31
:integer => { :name => "integer", :limit => 4 }, # JDBC limit: 10
:smallint => { :name => "smallint", :limit => 2 }, # JDBC limit: 5
:bigint => { :name => "bigint", :limit => 8 }, # JDBC limit: 19
:date => { :name => "date" },
:time => { :name => "time" },
:datetime => { :name => "timestamp" },
:timestamp => { :name => "timestamp" },
:xml => { :name => "xml" },
:boolean => { :name => "smallint", :limit => 1 }, # TODO boolean (since 10.7)
:object => { :name => "object" },
}
# @override
def native_database_types
NATIVE_DATABASE_TYPES
end
# Ensure the savepoint name is unused before creating it.
# @override
def create_savepoint(name = current_savepoint_name(true))
release_savepoint(name) if @connection.marked_savepoint_names.include?(name)
super(name)
end
# @override
def quote(value, column = nil)
return value.quoted_id if value.respond_to?(:quoted_id)
return value if sql_literal?(value)
return 'NULL' if value.nil?
column_type = column && column.type
if column_type == :string || column_type == :text
# Derby is not permissive
# e.g. sending an Integer to a VARCHAR column will fail
case value
when BigDecimal then value = value.to_s('F')
when Numeric then value = value.to_s
when true, false then value = value.to_s
when Date, Time then value = quoted_date(value)
else # on 2.3 attribute serialization needs to_yaml here
value = value.to_s if ActiveRecord::VERSION::MAJOR >= 3
end
end
case value
when String, ActiveSupport::Multibyte::Chars
if column_type == :text
"CAST('#{quote_string(value)}' AS CLOB)"
elsif column_type == :binary
"CAST(X'#{quote_binary(value)}' AS BLOB)"
elsif column_type == :xml
"XMLPARSE(DOCUMENT '#{quote_string(value)}' PRESERVE WHITESPACE)"
elsif column_type == :integer
value.to_i
elsif column_type == :float
value.to_f
else
"'#{quote_string(value)}'"
end
else
super
end
end
# @override
def quoted_date(value)
if value.acts_like?(:time) && value.respond_to?(:usec)
usec = sprintf("%06d", value.usec)
value = ::ActiveRecord::Base.default_timezone == :utc ? value.getutc : value.getlocal
"#{value.strftime("%Y-%m-%d %H:%M:%S")}.#{usec}"
else
super
end
end if ::ActiveRecord::VERSION::MAJOR >= 3
# @private In Derby, these cannot specify a limit.
NO_LIMIT_TYPES = [ :integer, :boolean, :timestamp, :datetime, :date, :time ]
# Convert the specified column type to a SQL string.
# @override
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
return super unless NO_LIMIT_TYPES.include?(t = type.to_s.downcase.to_sym)
native_type = NATIVE_DATABASE_TYPES[t]
native_type.is_a?(Hash) ? native_type[:name] : native_type
end
# @private
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
def xml(*args)
options = args.extract_options!
column(args[0], 'xml', options)
end
end
def table_definition(*args)
new_table_definition(TableDefinition, *args)
end
# @override
def empty_insert_statement_value
::Arel::Visitors::Derby::VALUES_DEFAULT # Derby needs to know the columns
end
# Set the sequence to the max value of the table's column.
# @override
def reset_sequence!(table, column, sequence = nil)
mpk = select_value("SELECT MAX(#{quote_column_name(column)}) FROM #{quote_table_name(table)}")
execute("ALTER TABLE #{quote_table_name(table)} ALTER COLUMN #{quote_column_name(column)} RESTART WITH #{mpk.to_i + 1}")
end
def reset_pk_sequence!(table, pk = nil, sequence = nil)
klasses = classes_for_table_name(table)
klass = klasses.nil? ? nil : klasses.first
pk = klass.primary_key unless klass.nil?
if pk && klass.columns_hash[pk].type == :integer
reset_sequence!(klass.table_name, pk)
end
end
def classes_for_table_name(table)
ActiveRecord::Base.send(:subclasses).select { |klass| klass.table_name == table }
end
private :classes_for_table_name
# @override
def remove_index(table_name, options)
execute "DROP INDEX #{index_name(table_name, options)}"
end
# @override
def rename_table(name, new_name)
execute "RENAME TABLE #{quote_table_name(name)} TO #{quote_table_name(new_name)}"
end
def add_column(table_name, column_name, type, options = {})
add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
add_column_options!(add_column_sql, options)
execute(add_column_sql)
end unless const_defined? :SchemaCreation
# @override fix case where AR passes `:default => nil, :null => true`
def add_column_options!(sql, options)
options.delete(:default) if options.has_key?(:default) && options[:default].nil?
sql << " DEFAULT #{quote(options.delete(:default))}" if options.has_key?(:default)
super
end unless const_defined? :SchemaCreation
if ActiveRecord::VERSION::MAJOR >= 4
# @override
def remove_column(table_name, column_name, type = nil, options = {})
do_remove_column(table_name, column_name)
end
else
# @override
def remove_column(table_name, *column_names)
for column_name in column_names.flatten
do_remove_column(table_name, column_name)
end
end
alias remove_columns remove_column
end
def do_remove_column(table_name, column_name)
execute "ALTER TABLE #{quote_table_name(table_name)} DROP COLUMN #{quote_column_name(column_name)} RESTRICT"
end
private :do_remove_column
# @override
def change_column(table_name, column_name, type, options = {})
# TODO this needs a review since now we're likely to be on >= 10.8
# Notes about changing in Derby:
# http://db.apache.org/derby/docs/10.2/ref/rrefsqlj81859.html#rrefsqlj81859__rrefsqlj37860)
#
# We support changing columns using the strategy outlined in:
# https://issues.apache.org/jira/browse/DERBY-1515
#
# This feature has not made it into a formal release and is not in Java 6.
# We will need to conditionally support this (supposed to arrive for 10.3.0.0).
# null/not nulling is easy, handle that separately
if options.include?(:null)
# This seems to only work with 10.2 of Derby
if options.delete(:null) == false
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} NOT NULL"
else
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} NULL"
end
end
# anything left to do?
unless options.empty?
begin
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN " <<
" #{quote_column_name(column_name)} SET DATA TYPE #{type_to_sql(type, options[:limit])}"
rescue
transaction do
temp_new_column_name = "#{column_name}_newtype"
# 1) ALTER TABLE t ADD COLUMN c1_newtype NEWTYPE;
add_column table_name, temp_new_column_name, type, options
# 2) UPDATE t SET c1_newtype = c1;
execute "UPDATE #{quote_table_name(table_name)} SET " <<
" #{quote_column_name(temp_new_column_name)} = " <<
" CAST(#{quote_column_name(column_name)} AS #{type_to_sql(type, options[:limit])})"
# 3) ALTER TABLE t DROP COLUMN c1;
remove_column table_name, column_name
# 4) ALTER TABLE t RENAME COLUMN c1_newtype to c1;
rename_column table_name, temp_new_column_name, column_name
end
end
end
end
# @override
def rename_column(table_name, column_name, new_column_name)
execute "RENAME COLUMN #{quote_table_name(table_name)}.#{quote_column_name(column_name)} " <<
" TO #{quote_column_name(new_column_name)}"
end
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
#
# Derby requires the ORDER BY columns in the select list for distinct queries, and
# requires that the ORDER BY include the distinct column.
# ```
# distinct("posts.id", "posts.created_at desc")
# ```
# @note This is based on distinct method for the PostgreSQL Adapter.
# @override
def distinct(columns, order_by)
"DISTINCT #{columns_for_distinct(columns, order_by)}"
end
# @override Since AR 4.0 (on 4.1 {#distinct} is gone and won't be called).
def columns_for_distinct(columns, orders)
return columns if orders.blank?
# construct a clean list of column names from the ORDER BY clause,
# removing any ASC/DESC modifiers
order_columns = [ orders ]; order_columns.flatten! # AR 3.x vs 4.x
order_columns.map! do |column|
column = column.to_sql unless column.is_a?(String) # handle AREL node
column.split(',').collect! { |s| s.split.first }
end.flatten!
order_columns.reject!(&:blank?)
order_columns = order_columns.zip (0...order_columns.size).to_a
order_columns = order_columns.map { |s, i| "#{s} AS alias_#{i}" }
columns = [ columns ]; columns.flatten!
columns.push( *order_columns ).join(', ')
# return a DISTINCT clause that's distinct on the columns we want but
# includes all the required columns for the ORDER BY to work properly
end
# @override
def primary_keys(table_name)
@connection.primary_keys table_name.to_s.upcase
end
# @override
def tables(name = nil)
@connection.tables(nil, current_schema)
end
def truncate(table_name, name = nil)
execute "TRUNCATE TABLE #{quote_table_name(table_name)}", name
end
# @return [String] the current schema name
def current_schema
@current_schema ||=
select_value "SELECT CURRENT SCHEMA FROM SYS.SYSSCHEMAS FETCH FIRST 1 ROWS ONLY", 'SCHEMA'
end
# Change the current (implicit) Derby schema to be used for this connection.
def set_schema(schema)
@current_schema = nil
execute "SET SCHEMA #{schema}", 'SCHEMA'
end
alias_method :current_schema=, :set_schema
# Creates a new Derby schema.
# @see #set_schema
def create_schema(schema)
execute "CREATE SCHEMA #{schema}", 'Create Schema'
end
# Drops an existing schema, needs to be empty (no DB objects).
def drop_schema(schema)
execute "DROP SCHEMA #{schema} RESTRICT", 'Drop Schema'
end
# @private
def recreate_database(name = nil, options = {})
drop_database(name)
create_database(name, options)
end
# @private
def create_database(name = nil, options = {}); end
# @private
def drop_database(name = nil)
tables.each { |table| drop_table(table) }
end
# @override
def quote_column_name(name)
%Q{"#{name.to_s.upcase.gsub('"', '""')}"}
end
# @override
def quote_table_name_for_assignment(table, attr)
quote_column_name(attr)
end if ::ActiveRecord::VERSION::MAJOR > 3
# @note Only used with (non-AREL) ActiveRecord **2.3**.
# @see Arel::Visitors::Derby
def add_limit_offset!(sql, options)
sql << " OFFSET #{options[:offset]} ROWS" if options[:offset]
# ROWS/ROW and FIRST/NEXT mean the same
sql << " FETCH FIRST #{options[:limit]} ROWS ONLY" if options[:limit]
end if ::ActiveRecord::VERSION::MAJOR < 3
# @override
def execute(sql, name = nil, binds = [])
sql = to_sql(sql, binds)
insert = self.class.insert?(sql)
update = ! insert && ! self.class.select?(sql)
sql = correct_is_null(sql, insert || update)
super(sql, name, binds)
end
# Returns the value of an identity column of the last *INSERT* statement
# made over this connection.
# @note Check the *IDENTITY_VAL_LOCAL* function for documentation.
# @return [Fixnum]
def last_insert_id
@connection.identity_val_local
end
private
def correct_is_null(sql, insert_or_update = false)
if insert_or_update
if ( i = sql =~ /\sWHERE\s/im )
where_part = sql[i..-1]; sql = sql.dup
where_part.gsub!(/!=\s*NULL/i, 'IS NOT NULL')
where_part.gsub!(/=\sNULL/i, 'IS NULL')
sql[i..-1] = where_part
end
sql
else
sql.gsub(/=\sNULL/i, 'IS NULL')
end
end
# NOTE: only setup query analysis on AR <= 3.0 since on 3.1 {#exec_query},
# {#exec_insert} will be used for AR generated queries/inserts etc.
# Also there's prepared statement support and {#execute} is meant to stay
# as a way of running non-prepared SQL statements (returning raw results).
if ActiveRecord::VERSION::MAJOR < 3 ||
( ActiveRecord::VERSION::MAJOR == 3 && ActiveRecord::VERSION::MINOR < 1 )
def _execute(sql, name = nil)
if self.class.insert?(sql)
@connection.execute_insert(sql)
elsif self.class.select?(sql)
@connection.execute_query_raw(sql)
else
@connection.execute_update(sql)
end
end
end
end
end
Let ActiveRecord do the work for serialized columns
ArJdbc.load_java_part :Derby
require 'arjdbc/util/table_copier'
require 'arjdbc/derby/schema_creation' # AR 4.x
module ArJdbc
module Derby
include Util::TableCopier
def self.extended(adapter)
require 'arjdbc/derby/active_record_patch'
end
def self.included(base)
require 'arjdbc/derby/active_record_patch'
end
# @see ActiveRecord::ConnectionAdapters::JdbcAdapter#jdbc_connection_class
def self.jdbc_connection_class
::ActiveRecord::ConnectionAdapters::DerbyJdbcConnection
end
# @see ActiveRecord::ConnectionAdapters::JdbcColumn#column_types
def self.column_selector
[ /derby/i, lambda { |config, column| column.extend(Column) } ]
end
# @private
@@emulate_booleans = true
# Boolean emulation can be disabled using :
#
# ArJdbc::Derby.emulate_booleans = false
#
def self.emulate_booleans?; @@emulate_booleans; end
# @deprecated Use {#emulate_booleans?} instead.
def self.emulate_booleans; @@emulate_booleans; end
# @see #emulate_booleans?
def self.emulate_booleans=(emulate); @@emulate_booleans = emulate; end
# @note Part of this module is implemented in "native" Java.
# @see ActiveRecord::ConnectionAdapters::JdbcColumn
module Column
private
def extract_limit(sql_type)
case @sql_type = sql_type.downcase
when /^smallint/i then @sql_type = 'smallint'; limit = 2
when /^bigint/i then @sql_type = 'bigint'; limit = 8
when /^double/i then @sql_type = 'double'; limit = 8 # DOUBLE PRECISION
when /^real/i then @sql_type = 'real'; limit = 4
when /^integer/i then @sql_type = 'integer'; limit = 4
when /^datetime/i then @sql_type = 'datetime'; limit = nil
when /^timestamp/i then @sql_type = 'timestamp'; limit = nil
when /^time/i then @sql_type = 'time'; limit = nil
when /^date/i then @sql_type = 'date'; limit = nil
when /^xml/i then @sql_type = 'xml'; limit = nil
else
limit = super
# handle maximum length for a VARCHAR string :
limit = 32672 if ! limit && @sql_type.index('varchar') == 0
end
limit
end
def simplified_type(field_type)
case field_type
when /^smallint/i then Derby.emulate_booleans? ? :boolean : :integer
when /^bigint|int/i then :integer
when /^real|double/i then :float
when /^dec/i then # DEC is a DECIMAL alias
extract_scale(field_type) == 0 ? :integer : :decimal
when /^timestamp/i then :datetime
when /^xml/i then :xml
when 'long varchar' then :text
when /for bit data/i then :binary
# :name=>"long varchar for bit data", :limit=>32700
# :name=>"varchar() for bit data", :limit=>32672
# :name=>"char() for bit data", :limit=>254}
else
super
end
end
# Post process default value from JDBC into a Rails-friendly format (columns{-internal})
def default_value(value)
# JDBC returns column default strings with actual single quotes around the value.
return $1 if value =~ /^'(.*)'$/
return nil if value == "GENERATED_BY_DEFAULT"
value
end
end
# @see ActiveRecord::ConnectionAdapters::Jdbc::ArelSupport
def self.arel_visitor_type(config = nil)
require 'arel/visitors/derby'; ::Arel::Visitors::Derby
end
ADAPTER_NAME = 'Derby'.freeze
def adapter_name
ADAPTER_NAME
end
# @private
def init_connection(jdbc_connection)
md = jdbc_connection.meta_data
major_version = md.database_major_version; minor_version = md.database_minor_version
if major_version < 10 || (major_version == 10 && minor_version < 5)
raise ::ActiveRecord::ConnectionNotEstablished, "Derby adapter requires Derby >= 10.5"
end
if major_version == 10 && minor_version < 8 # 10.8 ~ supports JDBC 4.1
config[:connection_alive_sql] ||=
'SELECT 1 FROM SYS.SYSSCHEMAS FETCH FIRST 1 ROWS ONLY' # FROM clause mandatory
else
# NOTE: since the loaded Java driver class can't change :
Derby.send(:remove_method, :init_connection) rescue nil
end
end
def configure_connection
# must be done or SELECT...FOR UPDATE won't work how we expect :
tx_isolation = config[:transaction_isolation] # set false to leave as is
tx_isolation = :serializable if tx_isolation.nil?
@connection.transaction_isolation = tx_isolation if tx_isolation
# if a user name was specified upon connection, the user's name is the
# default schema for the connection, if a schema with that name exists
set_schema(config[:schema]) if config.key?(:schema)
end
def index_name_length
128
end
NATIVE_DATABASE_TYPES = {
:primary_key => "int GENERATED BY DEFAULT AS identity NOT NULL PRIMARY KEY",
:string => { :name => "varchar", :limit => 255 }, # 32672
:text => { :name => "clob" }, # 2,147,483,647
:char => { :name => "char", :limit => 254 }, # JDBC limit: 254
:binary => { :name => "blob" }, # 2,147,483,647
:float => { :name => "float", :limit => 8 }, # DOUBLE PRECISION
:real => { :name => "real", :limit => 4 }, # JDBC limit: 23
:double => { :name => "double", :limit => 8 }, # JDBC limit: 52
:decimal => { :name => "decimal", :precision => 5, :scale => 0 }, # JDBC limit: 31
:numeric => { :name => "decimal", :precision => 5, :scale => 0 }, # JDBC limit: 31
:integer => { :name => "integer", :limit => 4 }, # JDBC limit: 10
:smallint => { :name => "smallint", :limit => 2 }, # JDBC limit: 5
:bigint => { :name => "bigint", :limit => 8 }, # JDBC limit: 19
:date => { :name => "date" },
:time => { :name => "time" },
:datetime => { :name => "timestamp" },
:timestamp => { :name => "timestamp" },
:xml => { :name => "xml" },
:boolean => { :name => "smallint", :limit => 1 }, # TODO boolean (since 10.7)
:object => { :name => "object" },
}
# @override
def native_database_types
NATIVE_DATABASE_TYPES
end
# Ensure the savepoint name is unused before creating it.
# @override
def create_savepoint(name = current_savepoint_name(true))
release_savepoint(name) if @connection.marked_savepoint_names.include?(name)
super(name)
end
# @override
def quote(value, column = nil)
return super if column && ArJdbc::AR42 && column.cast_type.is_a?(ActiveRecord::Type::Serialized)
return value.quoted_id if value.respond_to?(:quoted_id)
return value if sql_literal?(value)
return 'NULL' if value.nil?
column_type = column && column.type
if column_type == :string || column_type == :text
# Derby is not permissive
# e.g. sending an Integer to a VARCHAR column will fail
case value
when BigDecimal then value = value.to_s('F')
when Numeric then value = value.to_s
when true, false then value = value.to_s
when Date, Time then value = quoted_date(value)
else # on 2.3 attribute serialization needs to_yaml here
value = value.to_s if ActiveRecord::VERSION::MAJOR >= 3
end
end
case value
when String, ActiveSupport::Multibyte::Chars
if column_type == :text
"CAST('#{quote_string(value)}' AS CLOB)"
elsif column_type == :binary
"CAST(X'#{quote_binary(value)}' AS BLOB)"
elsif column_type == :xml
"XMLPARSE(DOCUMENT '#{quote_string(value)}' PRESERVE WHITESPACE)"
elsif column_type == :integer
value.to_i
elsif column_type == :float
value.to_f
else
"'#{quote_string(value)}'"
end
else
super
end
end
# @override
def quoted_date(value)
if value.acts_like?(:time) && value.respond_to?(:usec)
usec = sprintf("%06d", value.usec)
value = ::ActiveRecord::Base.default_timezone == :utc ? value.getutc : value.getlocal
"#{value.strftime("%Y-%m-%d %H:%M:%S")}.#{usec}"
else
super
end
end if ::ActiveRecord::VERSION::MAJOR >= 3
# @private In Derby, these cannot specify a limit.
NO_LIMIT_TYPES = [ :integer, :boolean, :timestamp, :datetime, :date, :time ]
# Convert the specified column type to a SQL string.
# @override
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
return super unless NO_LIMIT_TYPES.include?(t = type.to_s.downcase.to_sym)
native_type = NATIVE_DATABASE_TYPES[t]
native_type.is_a?(Hash) ? native_type[:name] : native_type
end
# @private
class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition
def xml(*args)
options = args.extract_options!
column(args[0], 'xml', options)
end
end
def table_definition(*args)
new_table_definition(TableDefinition, *args)
end
# @override
def empty_insert_statement_value
::Arel::Visitors::Derby::VALUES_DEFAULT # Derby needs to know the columns
end
# Set the sequence to the max value of the table's column.
# @override
def reset_sequence!(table, column, sequence = nil)
mpk = select_value("SELECT MAX(#{quote_column_name(column)}) FROM #{quote_table_name(table)}")
execute("ALTER TABLE #{quote_table_name(table)} ALTER COLUMN #{quote_column_name(column)} RESTART WITH #{mpk.to_i + 1}")
end
def reset_pk_sequence!(table, pk = nil, sequence = nil)
klasses = classes_for_table_name(table)
klass = klasses.nil? ? nil : klasses.first
pk = klass.primary_key unless klass.nil?
if pk && klass.columns_hash[pk].type == :integer
reset_sequence!(klass.table_name, pk)
end
end
def classes_for_table_name(table)
ActiveRecord::Base.send(:subclasses).select { |klass| klass.table_name == table }
end
private :classes_for_table_name
# @override
def remove_index(table_name, options)
execute "DROP INDEX #{index_name(table_name, options)}"
end
# @override
def rename_table(name, new_name)
execute "RENAME TABLE #{quote_table_name(name)} TO #{quote_table_name(new_name)}"
end
def add_column(table_name, column_name, type, options = {})
add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
add_column_options!(add_column_sql, options)
execute(add_column_sql)
end unless const_defined? :SchemaCreation
# @override fix case where AR passes `:default => nil, :null => true`
def add_column_options!(sql, options)
options.delete(:default) if options.has_key?(:default) && options[:default].nil?
sql << " DEFAULT #{quote(options.delete(:default))}" if options.has_key?(:default)
super
end unless const_defined? :SchemaCreation
if ActiveRecord::VERSION::MAJOR >= 4
# @override
def remove_column(table_name, column_name, type = nil, options = {})
do_remove_column(table_name, column_name)
end
else
# @override
def remove_column(table_name, *column_names)
for column_name in column_names.flatten
do_remove_column(table_name, column_name)
end
end
alias remove_columns remove_column
end
def do_remove_column(table_name, column_name)
execute "ALTER TABLE #{quote_table_name(table_name)} DROP COLUMN #{quote_column_name(column_name)} RESTRICT"
end
private :do_remove_column
# @override
def change_column(table_name, column_name, type, options = {})
# TODO this needs a review since now we're likely to be on >= 10.8
# Notes about changing in Derby:
# http://db.apache.org/derby/docs/10.2/ref/rrefsqlj81859.html#rrefsqlj81859__rrefsqlj37860)
#
# We support changing columns using the strategy outlined in:
# https://issues.apache.org/jira/browse/DERBY-1515
#
# This feature has not made it into a formal release and is not in Java 6.
# We will need to conditionally support this (supposed to arrive for 10.3.0.0).
# null/not nulling is easy, handle that separately
if options.include?(:null)
# This seems to only work with 10.2 of Derby
if options.delete(:null) == false
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} NOT NULL"
else
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} NULL"
end
end
# anything left to do?
unless options.empty?
begin
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN " <<
" #{quote_column_name(column_name)} SET DATA TYPE #{type_to_sql(type, options[:limit])}"
rescue
transaction do
temp_new_column_name = "#{column_name}_newtype"
# 1) ALTER TABLE t ADD COLUMN c1_newtype NEWTYPE;
add_column table_name, temp_new_column_name, type, options
# 2) UPDATE t SET c1_newtype = c1;
execute "UPDATE #{quote_table_name(table_name)} SET " <<
" #{quote_column_name(temp_new_column_name)} = " <<
" CAST(#{quote_column_name(column_name)} AS #{type_to_sql(type, options[:limit])})"
# 3) ALTER TABLE t DROP COLUMN c1;
remove_column table_name, column_name
# 4) ALTER TABLE t RENAME COLUMN c1_newtype to c1;
rename_column table_name, temp_new_column_name, column_name
end
end
end
end
# @override
def rename_column(table_name, column_name, new_column_name)
execute "RENAME COLUMN #{quote_table_name(table_name)}.#{quote_column_name(column_name)} " <<
" TO #{quote_column_name(new_column_name)}"
end
# SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
#
# Derby requires the ORDER BY columns in the select list for distinct queries, and
# requires that the ORDER BY include the distinct column.
# ```
# distinct("posts.id", "posts.created_at desc")
# ```
# @note This is based on distinct method for the PostgreSQL Adapter.
# @override
def distinct(columns, order_by)
"DISTINCT #{columns_for_distinct(columns, order_by)}"
end
# @override Since AR 4.0 (on 4.1 {#distinct} is gone and won't be called).
def columns_for_distinct(columns, orders)
return columns if orders.blank?
# construct a clean list of column names from the ORDER BY clause,
# removing any ASC/DESC modifiers
order_columns = [ orders ]; order_columns.flatten! # AR 3.x vs 4.x
order_columns.map! do |column|
column = column.to_sql unless column.is_a?(String) # handle AREL node
column.split(',').collect! { |s| s.split.first }
end.flatten!
order_columns.reject!(&:blank?)
order_columns = order_columns.zip (0...order_columns.size).to_a
order_columns = order_columns.map { |s, i| "#{s} AS alias_#{i}" }
columns = [ columns ]; columns.flatten!
columns.push( *order_columns ).join(', ')
# return a DISTINCT clause that's distinct on the columns we want but
# includes all the required columns for the ORDER BY to work properly
end
# @override
def primary_keys(table_name)
@connection.primary_keys table_name.to_s.upcase
end
# @override
def tables(name = nil)
@connection.tables(nil, current_schema)
end
def truncate(table_name, name = nil)
execute "TRUNCATE TABLE #{quote_table_name(table_name)}", name
end
# @return [String] the current schema name
def current_schema
@current_schema ||=
select_value "SELECT CURRENT SCHEMA FROM SYS.SYSSCHEMAS FETCH FIRST 1 ROWS ONLY", 'SCHEMA'
end
# Change the current (implicit) Derby schema to be used for this connection.
def set_schema(schema)
@current_schema = nil
execute "SET SCHEMA #{schema}", 'SCHEMA'
end
alias_method :current_schema=, :set_schema
# Creates a new Derby schema.
# @see #set_schema
def create_schema(schema)
execute "CREATE SCHEMA #{schema}", 'Create Schema'
end
# Drops an existing schema, needs to be empty (no DB objects).
def drop_schema(schema)
execute "DROP SCHEMA #{schema} RESTRICT", 'Drop Schema'
end
# @private
def recreate_database(name = nil, options = {})
drop_database(name)
create_database(name, options)
end
# @private
def create_database(name = nil, options = {}); end
# @private
def drop_database(name = nil)
tables.each { |table| drop_table(table) }
end
# @override
def quote_column_name(name)
%Q{"#{name.to_s.upcase.gsub('"', '""')}"}
end
# @override
def quote_table_name_for_assignment(table, attr)
quote_column_name(attr)
end if ::ActiveRecord::VERSION::MAJOR > 3
# @note Only used with (non-AREL) ActiveRecord **2.3**.
# @see Arel::Visitors::Derby
def add_limit_offset!(sql, options)
sql << " OFFSET #{options[:offset]} ROWS" if options[:offset]
# ROWS/ROW and FIRST/NEXT mean the same
sql << " FETCH FIRST #{options[:limit]} ROWS ONLY" if options[:limit]
end if ::ActiveRecord::VERSION::MAJOR < 3
# @override
def execute(sql, name = nil, binds = [])
sql = to_sql(sql, binds)
insert = self.class.insert?(sql)
update = ! insert && ! self.class.select?(sql)
sql = correct_is_null(sql, insert || update)
super(sql, name, binds)
end
# Returns the value of an identity column of the last *INSERT* statement
# made over this connection.
# @note Check the *IDENTITY_VAL_LOCAL* function for documentation.
# @return [Fixnum]
def last_insert_id
@connection.identity_val_local
end
private
def correct_is_null(sql, insert_or_update = false)
if insert_or_update
if ( i = sql =~ /\sWHERE\s/im )
where_part = sql[i..-1]; sql = sql.dup
where_part.gsub!(/!=\s*NULL/i, 'IS NOT NULL')
where_part.gsub!(/=\sNULL/i, 'IS NULL')
sql[i..-1] = where_part
end
sql
else
sql.gsub(/=\sNULL/i, 'IS NULL')
end
end
# NOTE: only setup query analysis on AR <= 3.0 since on 3.1 {#exec_query},
# {#exec_insert} will be used for AR generated queries/inserts etc.
# Also there's prepared statement support and {#execute} is meant to stay
# as a way of running non-prepared SQL statements (returning raw results).
if ActiveRecord::VERSION::MAJOR < 3 ||
( ActiveRecord::VERSION::MAJOR == 3 && ActiveRecord::VERSION::MINOR < 1 )
def _execute(sql, name = nil)
if self.class.insert?(sql)
@connection.execute_insert(sql)
elsif self.class.select?(sql)
@connection.execute_query_raw(sql)
else
@connection.execute_update(sql)
end
end
end
end
end
|
module ArticleJSON
class Article
attr_reader :article_elements, :additional_elements
# @param [Array[ArticleJSON::Elements::Base]] elements
def initialize(elements)
@article_elements = elements
@additional_elements = []
end
# All elements of this article with optional additional elements placed in
# between
# @return [Array[ArticleJSON::Elements::Base]]
def elements
@elements ||= begin
if @additional_elements.any?
ArticleJSON::Utils::AdditionalElementPlacer
.new(@article_elements, @additional_elements)
.merge_elements
else
@article_elements
end
end
end
# Hash representation of the article
# @return [Hash]
def to_h
{
article_json_version: VERSION,
content: elements.map(&:to_h),
}
end
# JSON representation of the article
# @return [String]
def to_json
to_h.to_json
end
# Exporter instance for HTML
# @return [ArticleJSON::Export::HTML::Exporter]
def html_exporter
ArticleJSON::Export::HTML::Exporter.new(elements)
end
# HTML export of the article
# @return [String]
def to_html
html_exporter.html
end
# Exporter instance for AMP
# @return [ArticleJSON::Export::AMP::Exporter]
def amp_exporter
ArticleJSON::Export::AMP::Exporter.new(elements)
end
# AMP export of the article
# @return [String]
def to_amp
amp_exporter.html
end
# Exporter instance for FacebookInstantArticle
# @return [ArticleJSON::Export::FacebookInstantArticle::Exporter]
def facebook_instant_article_exporter
ArticleJSON::Export::FacebookInstantArticle::Exporter.new(elements)
end
# FacebookInstantArticle export of the article
# @return [String]
def to_facebook_instant_article
facebook_instant_article_exporter.html
end
# Exporter instance for plain text
# @return [ArticleJSON::Export::PlainText::Exporter]
def plain_text_exporter
ArticleJSON::Export::PlainText::Exporter.new(elements)
end
# Plain text export of the article
# @return [String]
def to_plain_text
plain_text_exporter.text
end
# Distribute passed elements evenly throughout the article. All passed
# elements need to have an exporter to be represented in the rendered
# article. If the method is called multiple times, the order of additional
# elements is maintained.
# @param [Object] additional_elements
def place_additional_elements(additional_elements)
# Reset the `#elements` method memoization
@elements = nil
@additional_elements.concat(additional_elements)
end
class << self
# Build a new article from hash (like the one generated by #to_h)
# @return [ArticleJSON::Article]
def from_hash(hash)
hash = { content: hash } if hash.is_a?(Array)
new(ArticleJSON::Elements::Base.parse_hash_list(hash[:content]))
end
# Build a new article from JSON (like the one generated by #to_json)
# @return [ArticleJSON::Article]
def from_json(json)
from_hash(JSON.parse(json, symbolize_names: true))
end
# Build a new article from a Google Doc HTML export
# @return [ArticleJSON::Article]
def from_google_doc_html(html)
parser = ArticleJSON::Import::GoogleDoc::HTML::Parser.new(html)
new(parser.parsed_content)
end
end
end
end
BAN-1718 New param with to allow custom placer
With this optional param we can pass a
different placer that has a different algorithm
to distribute the elements in the article.
When not passing anything it will use the default
one: ArticleJSON::Utils::AdditionalElementPlacer
so this change won't break anything.
module ArticleJSON
class Article
attr_reader :article_elements, :additional_elements
# @param [Array[ArticleJSON::Elements::Base]] elements
def initialize(elements)
@article_elements = elements
@additional_elements = []
end
# All elements of this article with optional additional elements placed in
# between
# @return [Array[ArticleJSON::Elements::Base]]
def elements
@elements ||= begin
if @additional_elements.any?
@additional_element_placer_class
.new(@article_elements, @additional_elements)
.merge_elements
else
@article_elements
end
end
end
# Hash representation of the article
# @return [Hash]
def to_h
{
article_json_version: VERSION,
content: elements.map(&:to_h),
}
end
# JSON representation of the article
# @return [String]
def to_json
to_h.to_json
end
# Exporter instance for HTML
# @return [ArticleJSON::Export::HTML::Exporter]
def html_exporter
ArticleJSON::Export::HTML::Exporter.new(elements)
end
# HTML export of the article
# @return [String]
def to_html
html_exporter.html
end
# Exporter instance for AMP
# @return [ArticleJSON::Export::AMP::Exporter]
def amp_exporter
ArticleJSON::Export::AMP::Exporter.new(elements)
end
# AMP export of the article
# @return [String]
def to_amp
amp_exporter.html
end
# Exporter instance for FacebookInstantArticle
# @return [ArticleJSON::Export::FacebookInstantArticle::Exporter]
def facebook_instant_article_exporter
ArticleJSON::Export::FacebookInstantArticle::Exporter.new(elements)
end
# FacebookInstantArticle export of the article
# @return [String]
def to_facebook_instant_article
facebook_instant_article_exporter.html
end
# Exporter instance for plain text
# @return [ArticleJSON::Export::PlainText::Exporter]
def plain_text_exporter
ArticleJSON::Export::PlainText::Exporter.new(elements)
end
# Plain text export of the article
# @return [String]
def to_plain_text
plain_text_exporter.text
end
# Distribute passed elements evenly throughout the article. All passed
# elements need to have an exporter to be represented in the rendered
# article. If the method is called multiple times, the order of additional
# elements is maintained.
# @param [Object] additional_elements
# @param [Class<#merge_elements>] with - The passes class's `#initialize` method needs
# to accept two lists of elements. See
# `ArticleJSON::Utils::AdditionalElementPlacer`
# for reference.
def place_additional_elements(
additional_elements,
with: ArticleJSON::Utils::AdditionalElementPlacer
)
# Reset the `#elements` method memoization
@elements = nil
@additional_elements.concat(additional_elements)
@additional_element_placer_class = with
end
class << self
# Build a new article from hash (like the one generated by #to_h)
# @return [ArticleJSON::Article]
def from_hash(hash)
hash = { content: hash } if hash.is_a?(Array)
new(ArticleJSON::Elements::Base.parse_hash_list(hash[:content]))
end
# Build a new article from JSON (like the one generated by #to_json)
# @return [ArticleJSON::Article]
def from_json(json)
from_hash(JSON.parse(json, symbolize_names: true))
end
# Build a new article from a Google Doc HTML export
# @return [ArticleJSON::Article]
def from_google_doc_html(html)
parser = ArticleJSON::Import::GoogleDoc::HTML::Parser.new(html)
new(parser.parsed_content)
end
end
end
end
|
module Avalon
module Rails
VERSION = "0.0.2"
end
end
*feture): upgrade to v0.0.3
module Avalon
module Rails
VERSION = "0.0.3"
end
end
|
module AxlsxStyler
VERSION = '0.1.2'
end
Update version
Allow seting custom border color and width.
module AxlsxStyler
VERSION = '0.1.3'
end
|
module Babelish
class CSV2Android < Csv2Base
require 'xmlsimple'
attr_accessor :file_path
def initialize(filename, langs, args = {})
super(filename, langs, args)
@file_path = args[:output_dir].to_s
end
def language_filepaths(language)
require 'pathname'
filepath = Pathname.new(@file_path) + "values-#{language.code}" + "strings.xml"
return filepath ? [filepath] : []
end
def get_row_format(row_key, row_value, comment = nil, indentation = 0)
return "\t<string name=\"#{row_key}\">#{row_value}</string>\n"
end
def hash_to_output(content = {})
output = ''
if content && content.size > 0
output += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
output += "<resources>\n"
content.each do |key, value|
output += get_row_format(key, value)
end
output += "</resources>"
end
return output
end
def extension
"xml"
end
end
end
Removed the xmlsimple include in the csv2android.rb file.
module Babelish
class CSV2Android < Csv2Base
attr_accessor :file_path
def initialize(filename, langs, args = {})
super(filename, langs, args)
@file_path = args[:output_dir].to_s
end
def language_filepaths(language)
require 'pathname'
filepath = Pathname.new(@file_path) + "values-#{language.code}" + "strings.xml"
return filepath ? [filepath] : []
end
def get_row_format(row_key, row_value, comment = nil, indentation = 0)
return "\t<string name=\"#{row_key}\">#{row_value}</string>\n"
end
def hash_to_output(content = {})
output = ''
if content && content.size > 0
output += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
output += "<resources>\n"
content.each do |key, value|
output += get_row_format(key, value)
end
output += "</resources>"
end
return output
end
def extension
"xml"
end
end
end
|
module Besepa
module Utils
VERSION = '0.8.4'.freeze
end
end
Version 0.8.5
module Besepa
module Utils
VERSION = '0.8.5'.freeze
end
end
|
class Bibliog
attr_reader :autores, :titulo, :serie, :editorial, :edicion, :mes, :anno, :isbn
def initialize(a, t, e, ed, mes, anno, isbn, s="none")
@autores = a
@titulo = t
@serie = s
@editorial = e
@edicion = ed
@mes = mes
@anno = anno
@isbn = isbn
end
def get_autores
size = @autores.length
i = 0
while i < (size-1)
cadena = "#{cadena}"+"#{@autores[i]}, "
i = i+1
end
cadena = "#{cadena}"+"#{@autores[i]}"
end
def get_titulo
"#{@titulo}"
end
def get_serie
"#{@serie}"
end
def get_editorial
"#{@editorial}"
end
def get_edicion
"#{@edicion}"
end
def get_fecha
"#{@mes}, #{@anno}"
end
def get_isbn
size = @isbn.length
a = @isbn[0].length
cadena = "ISBN-#{a}: "
if a > 10
cadena = "#{cadena}"+"#{@isbn[0][-a..-11]}"+"-"+"#{@isbn[0][-10..-1]}"
else
cadena = "#{cadena}"+"#{@isbn[0]}"
end
i = 1
while i < size
a = @isbn[i].length
cadena = "#{cadena}"+"\nISBN-#{a}: "
if a > 10
cadena = "#{cadena}"+"#{@isbn[i][-a..-11]}"+"-"+"#{@isbn[i][-10..-1]}"
else
cadena = "#{cadena}"+"#{@isbn[i]}"
end
i = i+1
end
cadena
end
def to_s
cadena = "#{get_autores}.\n"
cadena = "#{cadena}"+"#{get_titulo}\n"
cadena = "#{cadena}"+"(#{get_serie})\n"
cadena = "#{cadena}"+"#{get_editorial}; #{get_edicion} edition (#{get_fecha})\n"
cadena = "#{cadena}"+"#{get_isbn}"
end
end
class Libro < Bibliog
end
Creada la clase vacia Libro (Modificacion)
class Bibliog
attr_reader :autores, :titulo, :serie, :editorial, :edicion, :mes, :anno, :isbn
def initialize(a, t, e, ed, mes, anno, isbn, s="none")
@autores = a
@titulo = t
@serie = s
@editorial = e
@edicion = ed
@mes = mes
@anno = anno
@isbn = isbn
end
def get_autores
size = @autores.length
i = 0
while i < (size-1)
cadena = "#{cadena}"+"#{@autores[i]}, "
i = i+1
end
cadena = "#{cadena}"+"#{@autores[i]}"
end
def get_titulo
"#{@titulo}"
end
def get_serie
"#{@serie}"
end
def get_editorial
"#{@editorial}"
end
def get_edicion
"#{@edicion}"
end
def get_fecha
"#{@mes}, #{@anno}"
end
def get_isbn
size = @isbn.length
a = @isbn[0].length
cadena = "ISBN-#{a}: "
if a > 10
cadena = "#{cadena}"+"#{@isbn[0][-a..-11]}"+"-"+"#{@isbn[0][-10..-1]}"
else
cadena = "#{cadena}"+"#{@isbn[0]}"
end
i = 1
while i < size
a = @isbn[i].length
cadena = "#{cadena}"+"\nISBN-#{a}: "
if a > 10
cadena = "#{cadena}"+"#{@isbn[i][-a..-11]}"+"-"+"#{@isbn[i][-10..-1]}"
else
cadena = "#{cadena}"+"#{@isbn[i]}"
end
i = i+1
end
cadena
end
def to_s
cadena = "#{get_autores}.\n"
cadena = "#{cadena}"+"#{get_titulo}\n"
cadena = "#{cadena}"+"(#{get_serie})\n"
cadena = "#{cadena}"+"#{get_editorial}; #{get_edicion} edition (#{get_fecha})\n"
cadena = "#{cadena}"+"#{get_isbn}"
end
end
class Libro
end |
module BillForward
# in an rspec run, the gemspec and bill_forward.rb loader will both visit this
VERSION = "1.2016.26" unless const_defined?(:VERSION)
end
bump version
module BillForward
# in an rspec run, the gemspec and bill_forward.rb loader will both visit this
VERSION = "1.2016.101" unless const_defined?(:VERSION)
end
|
# -*- encoding: utf-8; mode: ruby; tab-width: 2; indent-tabs-mode: nil -*-
# -*- mode: ruby; tab-width: 2; indent-tabs-mode: nil; -*-
require "uri"
require "json"
module Bishop
# see http://help.github.com/post-receive-hooks/
class SimpleCIHook < Bishop::Base
post "/#{ENV["BISHOP_API_KEY"]}" do
if ENV["BISHOP_SIMPLECI_HOOK_CHANNELS"]
payload = JSON.parse(URI.unescape(params["payload"]))
channels = ENV["BISHOP_SIMPLECI_HOOK_CHANNELS"].split(",")
# FIXME: This hack is nessecary for a heroku hosted app to work
# as .channels.each will throw a DRb::DRbConnError / Connection refused
# The .join(",").split(",") give us a simple array to work with
Bishop::Bot.instance.channels.join(",").split(",").each do |channel|
if (channels.index(channel))
#response = Net::HTTP.post_form(URI.parse("http://git.io/"), "url" => commit["url"])
#commit["url"] = Net::HTTPSuccess === response ? response["Location"] : commit["url"]
Bishop::Bot.instance.Channel(channel).safe_notice("[#{payload["project"]}] Build #{payload["commit_version"][0..9]} committet by #{payload["commit_author"]} #{payload["status"] ? "passed" : "failed"} at #{payload["built_at"]} - #{payload["url"]}")
end
end
end
"OK"
end
end
end
indicate simpleci status with colors
# -*- encoding: utf-8; mode: ruby; tab-width: 2; indent-tabs-mode: nil -*-
# -*- mode: ruby; tab-width: 2; indent-tabs-mode: nil; -*-
require "uri"
require "json"
module Bishop
# see http://help.github.com/post-receive-hooks/
class SimpleCIHook < Bishop::Base
post "/#{ENV["BISHOP_API_KEY"]}" do
if ENV["BISHOP_SIMPLECI_HOOK_CHANNELS"]
payload = JSON.parse(URI.unescape(params["payload"]))
channels = ENV["BISHOP_SIMPLECI_HOOK_CHANNELS"].split(",")
# FIXME: This hack is nessecary for a heroku hosted app to work
# as .channels.each will throw a DRb::DRbConnError / Connection refused
# The .join(",").split(",") give us a simple array to work with
Bishop::Bot.instance.channels.join(",").split(",").each do |channel|
if (channels.index(channel))
#response = Net::HTTP.post_form(URI.parse("http://git.io/"), "url" => commit["url"])
#commit["url"] = Net::HTTPSuccess === response ? response["Location"] : commit["url"]
Bishop::Bot.instance.Channel(channel).notice("[#{payload["project"]}] Build #{payload["commit_version"][0..9]} committet by #{payload["commit_author"]} #{payload["status"] ? "\x0309passed\x0F" : "\x0304failed\x0F"} at #{payload["built_at"]} - #{payload["url"]}")
end
end
end
"OK"
end
end
end
|
require "json"
module Brewdler
class BrewDumper
attr_reader :formulae
def initialize
if Brewdler.brew_installed?
formulae_info = JSON.load(`brew info --json=v1 --installed`) || [] rescue []
@formulae = formulae_info.map { |info| formula_inspector info }
else
raise "Unable to list installed formulae. Homebrew is not currently installed on your system."
end
end
def to_s
@formulae.map do |f|
if f[:args].empty?
"brew '#{f[:name]}'"
else
args = f[:args].map { |arg| "'#{arg}'" }.join(", ")
"brew '#{f[:name]}', args: [#{args}]"
end
end.join("\n")
end
private
def formula_inspector f
installed = f["installed"]
if f["linked_keg"].nil?
keg = installed[-1]
else
keg = installed.detect { |k| f["linked_keg"] == k["version"] }
end
args = keg["used_options"].map { |option| option.gsub /^--/, "" }
args << "HEAD" if keg["version"] == "HEAD"
args << "devel" if keg["version"].gsub(/_\d+$/, "") == f["versions"]["devel"]
args.uniq!
{name: f["name"], args: args, version: keg["version"]}
end
end
end
Fix syntax warning
./lib/brewdler/brew_dumper.rb:36: warning: ambiguous first argument; put parentheses or a space even after `/' operator
require "json"
module Brewdler
class BrewDumper
attr_reader :formulae
def initialize
if Brewdler.brew_installed?
formulae_info = JSON.load(`brew info --json=v1 --installed`) || [] rescue []
@formulae = formulae_info.map { |info| formula_inspector info }
else
raise "Unable to list installed formulae. Homebrew is not currently installed on your system."
end
end
def to_s
@formulae.map do |f|
if f[:args].empty?
"brew '#{f[:name]}'"
else
args = f[:args].map { |arg| "'#{arg}'" }.join(", ")
"brew '#{f[:name]}', args: [#{args}]"
end
end.join("\n")
end
private
def formula_inspector f
installed = f["installed"]
if f["linked_keg"].nil?
keg = installed[-1]
else
keg = installed.detect { |k| f["linked_keg"] == k["version"] }
end
args = keg["used_options"].map { |option| option.gsub(/^--/, "") }
args << "HEAD" if keg["version"] == "HEAD"
args << "devel" if keg["version"].gsub(/_\d+$/, "") == f["versions"]["devel"]
args.uniq!
{name: f["name"], args: args, version: keg["version"]}
end
end
end
|
module Burst
module Blocks
class Doctest < Basic
end
end
end
Add implementation for doctest block
module Burst
module Blocks
class Doctest < Basic
attr_accessor :content
def initialize(text)
@content = text
end
def to_html(r)
"<pre class=\"doctest\">\n#{@content}\n</pre>"
end
def inspect
"d(#{@content.inspect})"
end
end
end
end |
module CamaleonCms
VERSION = '2.4.5.6'
end
Release 2.4.5.7
module CamaleonCms
VERSION = '2.4.5.7'
end |
require "capistrano-chef-solo/version"
require "capistrano-rbenv"
require "capistrano/configuration"
require "capistrano/recipes/deploy/scm"
require "json"
require "uri"
module Capistrano
module ChefSolo
def self.extended(configuration)
configuration.load {
namespace(:"chef-solo") {
desc("Setup chef-solo. (an alias of chef_solo:setup)")
task(:setup, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:setup")
}
desc("Run chef-solo. (an alias of chef_solo)")
task(:default, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:default")
}
desc("Show chef-solo version. (an alias of chef_solo:version)")
task(:version, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:version")
}
desc("Show chef-solo attributes. (an alias of chef_solo:attributes)")
task(:attributes, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:attributes")
}
}
namespace(:chef_solo) {
_cset(:chef_solo_version, "11.4.0")
_cset(:chef_solo_path) { capture("echo $HOME/chef").strip }
_cset(:chef_solo_path_children, %w(bundle cache config cookbooks))
_cset(:chef_solo_config_file) { File.join(chef_solo_path, "config", "solo.rb") }
_cset(:chef_solo_attributes_file) { File.join(chef_solo_path, "config", "solo.json") }
_cset(:chef_solo_bootstrap_user) {
if variables.key?(:chef_solo_user)
logger.info(":chef_solo_user has been deprecated. use :chef_solo_bootstrap_user instead.")
fetch(:chef_solo_user, user)
else
user
end
}
_cset(:chef_solo_bootstrap_password) { password }
_cset(:chef_solo_bootstrap_ssh_options) {
if variables.key?(:chef_solo_ssh_options)
logger.info(":chef_solo_ssh_options has been deprecated. use :chef_solo_bootstrap_ssh_options instead.")
fetch(:chef_solo_ssh_options, ssh_options)
else
ssh_options
end
}
_cset(:chef_solo_use_password) {
auth_methods = ssh_options.fetch(:auth_methods, []).map { |m| m.to_sym }
auth_methods.include?(:password) or auth_methods.empty?
}
_cset(:_chef_solo_bootstrapped, false)
def _activate_settings(servers=[])
if _chef_solo_bootstrapped
false
else
# preserve original :user and :ssh_options
set(:_chef_solo_bootstrap_user, fetch(:user))
set(:_chef_solo_bootstrap_password, fetch(:password)) if chef_solo_use_password
set(:_chef_solo_bootstrap_ssh_options, fetch(:ssh_options))
# we have to establish connections before teardown.
# https://github.com/capistrano/capistrano/pull/416
establish_connections_to(servers)
logger.info("entering chef-solo bootstrap mode. reconnect to servers as `#{chef_solo_bootstrap_user}'.")
# drop connection which is connected as standard :user.
teardown_connections_to(servers)
set(:user, chef_solo_bootstrap_user)
set(:password, chef_solo_bootstrap_password) if chef_solo_use_password
set(:ssh_options, chef_solo_bootstrap_ssh_options)
set(:_chef_solo_bootstrapped, true)
true
end
end
def _deactivate_settings(servers=[])
if _chef_solo_bootstrapped
set(:user, _chef_solo_bootstrap_user)
set(:password, _chef_solo_bootstrap_password) if chef_solo_use_password
set(:ssh_options, _chef_solo_bootstrap_ssh_options)
set(:_chef_solo_bootstrapped, false)
# we have to establish connections before teardown.
# https://github.com/capistrano/capistrano/pull/416
establish_connections_to(servers)
logger.info("leaving chef-solo bootstrap mode. reconnect to servers as `#{user}'.")
# drop connection which is connected as bootstrap :user.
teardown_connections_to(servers)
true
else
false
end
end
_cset(:chef_solo_bootstrap, false)
def connect_with_settings(&block)
if chef_solo_bootstrap
servers = find_servers
if block_given?
begin
activated = _activate_settings(servers)
yield
rescue => error
logger.info("could not connect with bootstrap settings: #{error}")
raise
ensure
_deactivate_settings(servers) if activated
end
else
_activate_settings(servers)
end
else
yield if block_given?
end
end
# FIXME:
# Some variables (such like :default_environment set by capistrano-rbenv) may be
# initialized without bootstrap settings during `on :load`.
# Is there any way to avoid this without setting `:rbenv_setup_default_environment`
# as false?
set(:rbenv_setup_default_environment, false)
desc("Setup chef-solo.")
task(:setup, :except => { :no_release => true }) {
connect_with_settings do
transaction do
install
end
end
}
desc("Run chef-solo.")
task(:default, :except => { :no_release => true }) {
connect_with_settings do
setup
transaction do
update
invoke
end
end
}
# Acts like `default`, but will apply specified recipes only.
def run_list(*recipes)
connect_with_settings do
setup
transaction do
update(:run_list => recipes)
invoke
end
end
end
_cset(:chef_solo_cmd, "chef-solo")
desc("Show chef-solo version.")
task(:version, :except => { :no_release => true }) {
connect_with_settings do
run("cd #{chef_solo_path.dump} && #{bundle_cmd} exec #{chef_solo_cmd} --version")
end
}
desc("Show chef-solo attributes.")
task(:attributes, :except => { :no_release => true }) {
hosts = ENV.fetch("HOST", "").split(/\s*,\s*/)
roles = ENV.fetch("ROLE", "").split(/\s*,\s*/).map { |role| role.to_sym }
roles += hosts.map { |host| role_names_for_host(ServerDefinition.new(host)) }
attributes = _generate_attributes(:hosts => hosts, :roles => roles)
STDOUT.puts(_json_attributes(attributes))
}
task(:install, :except => { :no_release => true }) {
install_ruby
install_chef
}
task(:install_ruby, :except => { :no_release => true }) {
set(:rbenv_install_bundler, true)
find_and_execute_task("rbenv:setup")
}
_cset(:chef_solo_gemfile) {
(<<-EOS).gsub(/^\s*/, "")
source "https://rubygems.org"
gem "chef", #{chef_solo_version.to_s.dump}
EOS
}
task(:install_chef, :except => { :no_release => true }) {
begin
version = capture("cd #{chef_solo_path.dump} && #{bundle_cmd} exec #{chef_solo_cmd} --version")
installed = Regexp.new(Regexp.escape(chef_solo_version)) =~ version
rescue
installed = false
end
unless installed
dirs = chef_solo_path_children.map { |dir| File.join(chef_solo_path, dir) }
run("mkdir -p #{dirs.map { |x| x.dump }.join(" ")}")
top.put(chef_solo_gemfile, File.join(chef_solo_path, "Gemfile"))
args = fetch(:chef_solo_bundle_options, [])
args << "--path=#{File.join(chef_solo_path, "bundle").dump}"
args << "--quiet"
run("cd #{chef_solo_path.dump} && #{bundle_cmd} install #{args.join(" ")}")
end
}
def update(options={})
update_cookbooks(options)
update_config(options)
update_attributes(options)
end
def update_cookbooks(options={})
_normalize_cookbooks(chef_solo_cookbooks).each do |name, variables|
begin
tmpdir = capture("mktemp -d /tmp/cookbooks.XXXXXXXXXX", options).strip
run("rm -rf #{tmpdir.dump} && mkdir -p #{tmpdir.dump}", options)
deploy_cookbooks(name, tmpdir, variables, options)
install_cookbooks(name, tmpdir, File.join(chef_solo_path, "cookbooks"), options)
ensure
run("rm -rf #{tmpdir.dump}", options)
end
end
end
#
# The definition of cookbooks.
# By default, load cookbooks from local path of "config/cookbooks".
#
_cset(:chef_solo_cookbooks_exclude, %w(.hg .git .svn))
_cset(:chef_solo_cookbooks_default_variables) {{
:scm => :none,
:deploy_via => :copy_subdir,
:deploy_subdir => nil,
:repository => ".",
:cookbooks_exclude => chef_solo_cookbooks_exclude,
:copy_cache => nil,
}}
_cset(:chef_solo_cookbooks) {
variables = chef_solo_cookbooks_default_variables.dup
variables[:scm] = fetch(:chef_solo_cookbooks_scm) if exists?(:chef_solo_cookbooks_scm)
variables[:deploy_subdir] = fetch(:chef_solo_cookbooks_subdir, "config/cookbooks")
variables[:repository] = fetch(:chef_solo_cookbooks_repository) if exists?("chef_solo_cookbooks_repository")
variables[:revision] = fetch(:chef_solo_cookbooks_revision) if exists?(:chef_solo_cookbooks_revision)
if exists?(:chef_solo_cookbook_name)
# deploy as single cookbook
name = fetch(:chef_solo_cookbook_name)
{ name => variables.merge(:cookbook_name => name) }
else
# deploy as multiple cookbooks
name = fetch(:chef_solo_cookbooks_name, application)
{ name => variables }
end
}
_cset(:chef_solo_repository_cache) { File.expand_path("tmp/cookbooks-cache") }
def _normalize_cookbooks(cookbooks)
xs = cookbooks.map { |name, variables|
variables = chef_solo_cookbooks_default_variables.merge(variables)
variables[:application] ||= name
# use :cookbooks as :deploy_subdir for backward compatibility with prior than 0.1.2
variables[:deploy_subdir] ||= variables[:cookbooks]
if variables[:scm] != :none
variables[:copy_cache] ||= File.expand_path(name, chef_solo_repository_cache)
end
[name, variables]
}
Hash[xs]
end
def deploy_cookbooks(name, destination, variables={}, options={})
logger.debug("retrieving cookbooks `#{name}' from #{variables[:repository]} via #{variables[:deploy_via]}.")
begin
releases_path = capture("mktemp -d /tmp/releases.XXXXXXXXXX", options).strip
release_path = File.join(releases_path, release_name)
run("rm -rf #{releases_path.dump} && mkdir -p #{releases_path.dump}", options)
c = _middle_copy(top) # create new configuration with separated @variables
c.instance_eval do
set(:deploy_to, File.dirname(releases_path))
set(:releases_path, releases_path)
set(:release_path, release_path)
set(:revision) { source.head }
set(:source) { ::Capistrano::Deploy::SCM.new(scm, self) }
set(:real_revision) { source.local.query_revision(revision) { |cmd| with_env("LC_ALL", "C") { run_locally(cmd) } } }
set(:strategy) { ::Capistrano::Deploy::Strategy.new(deploy_via, self) }
variables.each do |key, val|
set(key, val)
end
strategy.deploy!
end
if variables.key?(:cookbook_name)
# deploy as single cookbook
final_destination = File.join(destination, variables[:cookbook_name])
else
# deploy as multiple cookbooks
final_destination = destination
end
run("rsync -lrpt #{(release_path + "/").dump} #{final_destination.dump}", options)
ensure
run("rm -rf #{releases_path.dump}", options)
end
end
def _middle_copy(object)
o = object.clone
object.instance_variables.each do |k|
v = object.instance_variable_get(k)
o.instance_variable_set(k, v ? v.clone : v)
end
o
end
def install_cookbooks(name, source, destination, options={})
logger.debug("installing cookbooks `#{name}' to #{destination}.")
run("mkdir -p #{source.dump} #{destination.dump}", options)
run("rsync -lrpt #{(source + "/").dump} #{destination.dump}", options)
end
_cset(:chef_solo_config) {
(<<-EOS).gsub(/^\s*/, "")
file_cache_path #{File.join(chef_solo_path, "cache").dump}
cookbook_path #{File.join(chef_solo_path, "cookbooks").dump}
EOS
}
def update_config(options={})
top.put(chef_solo_config, chef_solo_config_file)
end
# merge nested hashes
def _merge_attributes!(a, b)
f = lambda { |key, val1, val2|
case val1
when Array
val1 + val2
when Hash
val1.merge(val2, &f)
else
val2
end
}
a.merge!(b, &f)
end
def _json_attributes(x)
JSON.send(fetch(:chef_solo_pretty_json, true) ? :pretty_generate : :generate, x)
end
_cset(:chef_solo_capistrano_attributes) {
#
# The rule of generating chef attributes from Capistrano variables
#
# 1. Reject variables if it is in exclude list.
# 2. Reject variables if it is lazy and not in include list.
# (lazy variables might have any side-effects)
#
attributes = variables.reject { |key, value|
excluded = chef_solo_capistrano_attributes_exclude.include?(key)
included = chef_solo_capistrano_attributes_include.include?(key)
excluded or (not included and value.respond_to?(:call))
}
Hash[attributes.map { |key, value| [key, fetch(key, nil)] }]
}
_cset(:chef_solo_capistrano_attributes_include, [
:application, :deploy_to, :rails_env, :latest_release,
:releases_path, :shared_path, :current_path, :release_path,
])
_cset(:chef_solo_capistrano_attributes_exclude, [:logger, :password])
_cset(:chef_solo_attributes, {})
_cset(:chef_solo_host_attributes, {})
_cset(:chef_solo_role_attributes, {})
_cset(:chef_solo_run_list, [])
_cset(:chef_solo_host_run_list, {})
_cset(:chef_solo_role_run_list, {})
def _generate_attributes(options={})
hosts = [ options.delete(:hosts) ].flatten.compact.uniq
roles = [ options.delete(:roles) ].flatten.compact.uniq
run_list = [ options.delete(:run_list) ].flatten.compact.uniq
#
# By default, the Chef attributes will be generated by following order.
#
# 1. Use _non-lazy_ variables of Capistrano.
# 2. Use attributes defined in `:chef_solo_attributes`.
# 3. Use attributes defined in `:chef_solo_role_attributes` for target role.
# 4. Use attributes defined in `:chef_solo_host_attributes` for target host.
#
attributes = chef_solo_capistrano_attributes.dup
_merge_attributes!(attributes, chef_solo_attributes)
roles.each do |role|
_merge_attributes!(attributes, chef_solo_role_attributes.fetch(role, {}))
end
hosts.each do |host|
_merge_attributes!(attributes, chef_solo_host_attributes.fetch(host, {}))
end
#
# The Chef `run_list` will be generated by following rules.
#
# * If `:run_list` was given as argument, just use it.
# * Otherwise, generate it from `:chef_solo_role_run_list`, `:chef_solo_role_run_list`
# and `:chef_solo_host_run_list`.
#
if run_list.empty?
_merge_attributes!(attributes, {"run_list" => chef_solo_run_list})
roles.each do |role|
_merge_attributes!(attributes, {"run_list" => chef_solo_role_run_list.fetch(role, [])})
end
hosts.each do |host|
_merge_attributes!(attributes, {"run_list" => chef_solo_host_run_list.fetch(host, [])})
end
else
attributes["run_list"] = [] # ignore run_list not from argument
_merge_attributes!(attributes, {"run_list" => run_list})
end
attributes
end
def update_attributes(options={})
run_list = options.delete(:run_list)
servers = find_servers_for_task(current_task)
servers.each do |server|
logger.debug("updating chef-solo attributes for #{server.host}.")
attributes = _generate_attributes(:hosts => server.host, :roles => role_names_for_host(server), :run_list => run_list)
top.put(_json_attributes(attributes), chef_solo_attributes_file, options.merge(:hosts => server.host))
end
end
def invoke(options={})
logger.debug("invoking chef-solo.")
args = fetch(:chef_solo_options, [])
args << "-c #{chef_solo_config_file.dump}"
args << "-j #{chef_solo_attributes_file.dump}"
run("cd #{chef_solo_path.dump} && #{sudo} #{bundle_cmd} exec #{chef_solo_cmd} #{args.join(" ")}", options)
end
}
}
end
end
end
if Capistrano::Configuration.instance
Capistrano::Configuration.instance.extend(Capistrano::ChefSolo)
end
# vim:set ft=ruby ts=2 sw=2 :
add :chef_solo_cache_path, :chef_solo_config_path and :chef_solo_cookbooks_path
require "capistrano-chef-solo/version"
require "capistrano-rbenv"
require "capistrano/configuration"
require "capistrano/recipes/deploy/scm"
require "json"
require "uri"
module Capistrano
module ChefSolo
def self.extended(configuration)
configuration.load {
namespace(:"chef-solo") {
desc("Setup chef-solo. (an alias of chef_solo:setup)")
task(:setup, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:setup")
}
desc("Run chef-solo. (an alias of chef_solo)")
task(:default, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:default")
}
desc("Show chef-solo version. (an alias of chef_solo:version)")
task(:version, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:version")
}
desc("Show chef-solo attributes. (an alias of chef_solo:attributes)")
task(:attributes, :except => { :no_release => true }) {
find_and_execute_task("chef_solo:attributes")
}
}
namespace(:chef_solo) {
_cset(:chef_solo_version, "11.4.0")
_cset(:chef_solo_path) { capture("echo $HOME/chef").strip }
_cset(:chef_solo_cache_path) { File.join(chef_solo_path, "cache") }
_cset(:chef_solo_config_path) { File.join(chef_solo_path, "config") }
_cset(:chef_solo_cookbooks_path) { File.join(chef_solo_path, "cookbooks") }
_cset(:chef_solo_config_file) { File.join(chef_solo_config_path, "solo.rb") }
_cset(:chef_solo_attributes_file) { File.join(chef_solo_config_path, "solo.json") }
_cset(:chef_solo_bootstrap_user) {
if variables.key?(:chef_solo_user)
logger.info(":chef_solo_user has been deprecated. use :chef_solo_bootstrap_user instead.")
fetch(:chef_solo_user, user)
else
user
end
}
_cset(:chef_solo_bootstrap_password) { password }
_cset(:chef_solo_bootstrap_ssh_options) {
if variables.key?(:chef_solo_ssh_options)
logger.info(":chef_solo_ssh_options has been deprecated. use :chef_solo_bootstrap_ssh_options instead.")
fetch(:chef_solo_ssh_options, ssh_options)
else
ssh_options
end
}
_cset(:chef_solo_use_password) {
auth_methods = ssh_options.fetch(:auth_methods, []).map { |m| m.to_sym }
auth_methods.include?(:password) or auth_methods.empty?
}
_cset(:_chef_solo_bootstrapped, false)
def _activate_settings(servers=[])
if _chef_solo_bootstrapped
false
else
# preserve original :user and :ssh_options
set(:_chef_solo_bootstrap_user, fetch(:user))
set(:_chef_solo_bootstrap_password, fetch(:password)) if chef_solo_use_password
set(:_chef_solo_bootstrap_ssh_options, fetch(:ssh_options))
# we have to establish connections before teardown.
# https://github.com/capistrano/capistrano/pull/416
establish_connections_to(servers)
logger.info("entering chef-solo bootstrap mode. reconnect to servers as `#{chef_solo_bootstrap_user}'.")
# drop connection which is connected as standard :user.
teardown_connections_to(servers)
set(:user, chef_solo_bootstrap_user)
set(:password, chef_solo_bootstrap_password) if chef_solo_use_password
set(:ssh_options, chef_solo_bootstrap_ssh_options)
set(:_chef_solo_bootstrapped, true)
true
end
end
def _deactivate_settings(servers=[])
if _chef_solo_bootstrapped
set(:user, _chef_solo_bootstrap_user)
set(:password, _chef_solo_bootstrap_password) if chef_solo_use_password
set(:ssh_options, _chef_solo_bootstrap_ssh_options)
set(:_chef_solo_bootstrapped, false)
# we have to establish connections before teardown.
# https://github.com/capistrano/capistrano/pull/416
establish_connections_to(servers)
logger.info("leaving chef-solo bootstrap mode. reconnect to servers as `#{user}'.")
# drop connection which is connected as bootstrap :user.
teardown_connections_to(servers)
true
else
false
end
end
_cset(:chef_solo_bootstrap, false)
def connect_with_settings(&block)
if chef_solo_bootstrap
servers = find_servers
if block_given?
begin
activated = _activate_settings(servers)
yield
rescue => error
logger.info("could not connect with bootstrap settings: #{error}")
raise
ensure
_deactivate_settings(servers) if activated
end
else
_activate_settings(servers)
end
else
yield if block_given?
end
end
# FIXME:
# Some variables (such like :default_environment set by capistrano-rbenv) may be
# initialized without bootstrap settings during `on :load`.
# Is there any way to avoid this without setting `:rbenv_setup_default_environment`
# as false?
set(:rbenv_setup_default_environment, false)
desc("Setup chef-solo.")
task(:setup, :except => { :no_release => true }) {
connect_with_settings do
transaction do
install
end
end
}
desc("Run chef-solo.")
task(:default, :except => { :no_release => true }) {
connect_with_settings do
setup
transaction do
update
invoke
end
end
}
# Acts like `default`, but will apply specified recipes only.
def run_list(*recipes)
connect_with_settings do
setup
transaction do
update(:run_list => recipes)
invoke
end
end
end
_cset(:chef_solo_cmd, "chef-solo")
desc("Show chef-solo version.")
task(:version, :except => { :no_release => true }) {
connect_with_settings do
run("cd #{chef_solo_path.dump} && #{bundle_cmd} exec #{chef_solo_cmd} --version")
end
}
desc("Show chef-solo attributes.")
task(:attributes, :except => { :no_release => true }) {
hosts = ENV.fetch("HOST", "").split(/\s*,\s*/)
roles = ENV.fetch("ROLE", "").split(/\s*,\s*/).map { |role| role.to_sym }
roles += hosts.map { |host| role_names_for_host(ServerDefinition.new(host)) }
attributes = _generate_attributes(:hosts => hosts, :roles => roles)
STDOUT.puts(_json_attributes(attributes))
}
task(:install, :except => { :no_release => true }) {
install_ruby
install_chef
}
task(:install_ruby, :except => { :no_release => true }) {
set(:rbenv_install_bundler, true)
find_and_execute_task("rbenv:setup")
}
_cset(:chef_solo_gemfile) {
(<<-EOS).gsub(/^\s*/, "")
source "https://rubygems.org"
gem "chef", #{chef_solo_version.to_s.dump}
EOS
}
task(:install_chef, :except => { :no_release => true }) {
begin
version = capture("cd #{chef_solo_path.dump} && #{bundle_cmd} exec #{chef_solo_cmd} --version")
installed = Regexp.new(Regexp.escape(chef_solo_version)) =~ version
rescue
installed = false
end
unless installed
dirs = [ chef_solo_path, chef_solo_cache_path, chef_solo_config_path, chef_solo_cookbooks_path ].uniq
run("mkdir -p #{dirs.map { |x| x.dump }.join(" ")}")
top.put(chef_solo_gemfile, File.join(chef_solo_path, "Gemfile"))
args = fetch(:chef_solo_bundle_options, [])
args << "--path=#{File.join(chef_solo_path, "bundle").dump}"
args << "--quiet"
run("cd #{chef_solo_path.dump} && #{bundle_cmd} install #{args.join(" ")}")
end
}
def update(options={})
update_cookbooks(options)
update_attributes(options)
update_config(options)
end
def update_cookbooks(options={})
_normalize_cookbooks(chef_solo_cookbooks).each do |name, variables|
begin
tmpdir = capture("mktemp -d /tmp/cookbooks.XXXXXXXXXX", options).strip
run("rm -rf #{tmpdir.dump} && mkdir -p #{tmpdir.dump}", options)
deploy_cookbooks(name, tmpdir, variables, options)
install_cookbooks(name, tmpdir, chef_solo_cookbooks_path, options)
ensure
run("rm -rf #{tmpdir.dump}", options)
end
end
end
#
# The definition of cookbooks.
# By default, load cookbooks from local path of "config/cookbooks".
#
_cset(:chef_solo_cookbooks_exclude, %w(.hg .git .svn))
_cset(:chef_solo_cookbooks_default_variables) {{
:scm => :none,
:deploy_via => :copy_subdir,
:deploy_subdir => nil,
:repository => ".",
:cookbooks_exclude => chef_solo_cookbooks_exclude,
:copy_cache => nil,
}}
_cset(:chef_solo_cookbooks) {
variables = chef_solo_cookbooks_default_variables.dup
variables[:scm] = fetch(:chef_solo_cookbooks_scm) if exists?(:chef_solo_cookbooks_scm)
variables[:deploy_subdir] = fetch(:chef_solo_cookbooks_subdir, "config/cookbooks")
variables[:repository] = fetch(:chef_solo_cookbooks_repository) if exists?("chef_solo_cookbooks_repository")
variables[:revision] = fetch(:chef_solo_cookbooks_revision) if exists?(:chef_solo_cookbooks_revision)
if exists?(:chef_solo_cookbook_name)
# deploy as single cookbook
name = fetch(:chef_solo_cookbook_name)
{ name => variables.merge(:cookbook_name => name) }
else
# deploy as multiple cookbooks
name = fetch(:chef_solo_cookbooks_name, application)
{ name => variables }
end
}
_cset(:chef_solo_repository_cache) { File.expand_path("tmp/cookbooks-cache") }
def _normalize_cookbooks(cookbooks)
xs = cookbooks.map { |name, variables|
variables = chef_solo_cookbooks_default_variables.merge(variables)
variables[:application] ||= name
# use :cookbooks as :deploy_subdir for backward compatibility with prior than 0.1.2
variables[:deploy_subdir] ||= variables[:cookbooks]
if variables[:scm] != :none
variables[:copy_cache] ||= File.expand_path(name, chef_solo_repository_cache)
end
[name, variables]
}
Hash[xs]
end
def deploy_cookbooks(name, destination, variables={}, options={})
logger.debug("retrieving cookbooks `#{name}' from #{variables[:repository]} via #{variables[:deploy_via]}.")
begin
releases_path = capture("mktemp -d /tmp/releases.XXXXXXXXXX", options).strip
release_path = File.join(releases_path, release_name)
run("rm -rf #{releases_path.dump} && mkdir -p #{releases_path.dump}", options)
c = _middle_copy(top) # create new configuration with separated @variables
c.instance_eval do
set(:deploy_to, File.dirname(releases_path))
set(:releases_path, releases_path)
set(:release_path, release_path)
set(:revision) { source.head }
set(:source) { ::Capistrano::Deploy::SCM.new(scm, self) }
set(:real_revision) { source.local.query_revision(revision) { |cmd| with_env("LC_ALL", "C") { run_locally(cmd) } } }
set(:strategy) { ::Capistrano::Deploy::Strategy.new(deploy_via, self) }
variables.each do |key, val|
set(key, val)
end
strategy.deploy!
end
if variables.key?(:cookbook_name)
# deploy as single cookbook
final_destination = File.join(destination, variables[:cookbook_name])
else
# deploy as multiple cookbooks
final_destination = destination
end
run("rsync -lrpt #{(release_path + "/").dump} #{final_destination.dump}", options)
ensure
run("rm -rf #{releases_path.dump}", options)
end
end
def _middle_copy(object)
o = object.clone
object.instance_variables.each do |k|
v = object.instance_variable_get(k)
o.instance_variable_set(k, v ? v.clone : v)
end
o
end
def install_cookbooks(name, source, destination, options={})
logger.debug("installing cookbooks `#{name}' to #{destination}.")
run("mkdir -p #{source.dump} #{destination.dump}", options)
run("rsync -lrpt #{(source + "/").dump} #{destination.dump}", options)
end
_cset(:chef_solo_config) {
(<<-EOS).gsub(/^\s*/, "")
file_cache_path #{chef_solo_cache_path.dump}
cookbook_path #{chef_solo_cookbooks_path.dump}
EOS
}
def update_config(options={})
top.put(chef_solo_config, chef_solo_config_file, options)
end
# merge nested hashes
def _merge_attributes!(a, b)
f = lambda { |key, val1, val2|
case val1
when Array
val1 + val2
when Hash
val1.merge(val2, &f)
else
val2
end
}
a.merge!(b, &f)
end
def _json_attributes(x)
JSON.send(fetch(:chef_solo_pretty_json, true) ? :pretty_generate : :generate, x)
end
_cset(:chef_solo_capistrano_attributes) {
#
# The rule of generating chef attributes from Capistrano variables
#
# 1. Reject variables if it is in exclude list.
# 2. Reject variables if it is lazy and not in include list.
# (lazy variables might have any side-effects)
#
attributes = variables.reject { |key, value|
excluded = chef_solo_capistrano_attributes_exclude.include?(key)
included = chef_solo_capistrano_attributes_include.include?(key)
excluded or (not included and value.respond_to?(:call))
}
Hash[attributes.map { |key, value| [key, fetch(key, nil)] }]
}
_cset(:chef_solo_capistrano_attributes_include, [
:application, :deploy_to, :rails_env, :latest_release,
:releases_path, :shared_path, :current_path, :release_path,
])
_cset(:chef_solo_capistrano_attributes_exclude, [:logger, :password])
_cset(:chef_solo_attributes, {})
_cset(:chef_solo_host_attributes, {})
_cset(:chef_solo_role_attributes, {})
_cset(:chef_solo_run_list, [])
_cset(:chef_solo_host_run_list, {})
_cset(:chef_solo_role_run_list, {})
def _generate_attributes(options={})
hosts = [ options.delete(:hosts) ].flatten.compact.uniq
roles = [ options.delete(:roles) ].flatten.compact.uniq
run_list = [ options.delete(:run_list) ].flatten.compact.uniq
#
# By default, the Chef attributes will be generated by following order.
#
# 1. Use _non-lazy_ variables of Capistrano.
# 2. Use attributes defined in `:chef_solo_attributes`.
# 3. Use attributes defined in `:chef_solo_role_attributes` for target role.
# 4. Use attributes defined in `:chef_solo_host_attributes` for target host.
#
attributes = chef_solo_capistrano_attributes.dup
_merge_attributes!(attributes, chef_solo_attributes)
roles.each do |role|
_merge_attributes!(attributes, chef_solo_role_attributes.fetch(role, {}))
end
hosts.each do |host|
_merge_attributes!(attributes, chef_solo_host_attributes.fetch(host, {}))
end
#
# The Chef `run_list` will be generated by following rules.
#
# * If `:run_list` was given as argument, just use it.
# * Otherwise, generate it from `:chef_solo_role_run_list`, `:chef_solo_role_run_list`
# and `:chef_solo_host_run_list`.
#
if run_list.empty?
_merge_attributes!(attributes, {"run_list" => chef_solo_run_list})
roles.each do |role|
_merge_attributes!(attributes, {"run_list" => chef_solo_role_run_list.fetch(role, [])})
end
hosts.each do |host|
_merge_attributes!(attributes, {"run_list" => chef_solo_host_run_list.fetch(host, [])})
end
else
attributes["run_list"] = [] # ignore run_list not from argument
_merge_attributes!(attributes, {"run_list" => run_list})
end
attributes
end
def update_attributes(options={})
run_list = options.delete(:run_list)
servers = find_servers_for_task(current_task)
servers.each do |server|
logger.debug("updating chef-solo attributes for #{server.host}.")
attributes = _generate_attributes(:hosts => server.host, :roles => role_names_for_host(server), :run_list => run_list)
top.put(_json_attributes(attributes), chef_solo_attributes_file, options.merge(:hosts => server.host))
end
end
def invoke(options={})
logger.debug("invoking chef-solo.")
args = fetch(:chef_solo_options, [])
args << "-c #{chef_solo_config_file.dump}"
args << "-j #{chef_solo_attributes_file.dump}"
run("cd #{chef_solo_path.dump} && #{sudo} #{bundle_cmd} exec #{chef_solo_cmd} #{args.join(" ")}", options)
end
}
}
end
end
end
if Capistrano::Configuration.instance
Capistrano::Configuration.instance.extend(Capistrano::ChefSolo)
end
# vim:set ft=ruby ts=2 sw=2 :
|
require 'jinx/helpers/validation'
require 'catissue/helpers/person'
module CaTissue
# The User domain class.
#
# @quirk caTissue caTissue 1.2 User has an adminuser Java property, but caTissue throws an
# UnsupportedOperationException if it's accessor method is called.
#
# @quirk caTissue clinical study is unsupported by 1.1.x caTissue, removed in 1.2.
class User
include Person
# @quirk caTissue work-around for caTissue Bug #66 - Client missing CSException class et al.
# caTissue User class initializes roleId to "", which triggers a client exception on subsequent
# getRoleId call. Use a private variable instead and bypass getRoleId.
#
# @quirk caTissue 1.2 Call to getRoleId results in the following error:
# NoClassDefFoundError: gov/nih/nci/security/dao/SearchCriteria
# This bug is probably a result of caTissue "fixing" Bug #66.
# The work-around to the caTissue bug fix bug is to return nil unless the role id has been set
# by a call to the {#role_id=} setter method.
def role_id
@role_id
end
# Sets the role id to the given value, which can be either a String or an Integer.
# An empty or zero value is converted to nil.
#
# @quirk caTissue caTissue API roleId is a String although the intended value domain is the
# integer csm_role.identifier.
def role_id=(value)
# value as an integer (nil is zero)
value_i = value.to_i
# set the Bug #66 work-around i.v.
@role_id = value_i.zero? ? nil : value_i
# value as a String (if non-nil)
value_s = @role_id.to_s if @role_id
# call Java with a String
setRoleId(value_s)
end
if property_defined?(:adminuser) then remove_attribute(:adminuser) end
# Make the convenience {CaRuby::Person::Name} name a first-class attribute.
add_attribute(:name, CaRuby::Person::Name)
if property_defined?(:clinical_studies) then remove_attribute(:clinical_studies) end
# Clarify that collection_protocols is a coordinator -> protocol association.
# Make assigned protocol and site attribute names consistent.
add_attribute_aliases(:coordinated_protocols => :collection_protocols, :protocols => :assigned_protocols, :assigned_sites => :sites)
# login_name is a database unique key.
set_secondary_key_attributes(:login_name)
# email_address is expected to be unique, and is enforced by the caTissue business logic.
set_alternate_key_attributes(:email_address)
# Set defaults as follows:
# * page_of is the value set when creating a User in the GUI
# * role id is 7 = Scientist (public)
# * initial password is 'changeMe1'
add_attribute_defaults(:activity_status => 'Active', :page_of => 'pageOfUserAdmin', :role_id => 7, :new_password => 'changeMe1')
# @quirk caTissue obscure GUI artifact User page_of attribute pollutes the data layer as a
# required attribute. Work-around is to simulate the GUI with a default value.
add_mandatory_attributes(:activity_status, :address, :cancer_research_group, :department,
:email_address, :first_name, :institution, :last_name, :page_of, :role_id)
# @quirk caTissue 1.2 User address can be updated in 1.1.2, but not 1.2. This difference is handled
# by the caRuby {CaTissue::Database} update case logic.
#
# @quirk caTissue 1.2 User address is fetched on create in 1.1.2, but not 1.2. This difference is
# handled by the caRuby {CaTissue::Database} create case logic.
add_dependent_attribute(:address)
# Password is removed as a visible caRuby attribute, since it is immutable in 1.2 and there
# is no use case for its access.
remove_attribute(:passwords)
set_attribute_inverse(:protocols, :assigned_protocol_users)
set_attribute_inverse(:sites, :assigned_site_users)
qualify_attribute(:cancer_research_group, :fetched)
qualify_attribute(:department, :fetched)
qualify_attribute(:institution, :fetched)
qualify_attribute(:protocols, :saved, :fetched)
qualify_attribute(:sites, :saved)
qualify_attribute(:page_of, :unfetched)
qualify_attribute(:new_password, :unfetched)
qualify_attribute(:role_id, :unfetched)
private
# By default, the email address is the same as the login name.
def add_defaults_local
super
self.login_name ||= email_address
self.email_address ||= login_name
end
end
end
coordinated_protocols are saved.
require 'jinx/helpers/validation'
require 'catissue/helpers/person'
module CaTissue
# The User domain class.
#
# @quirk caTissue caTissue 1.2 User has an adminuser Java property, but caTissue throws an
# UnsupportedOperationException if it's accessor method is called.
#
# @quirk caTissue clinical study is unsupported by 1.1.x caTissue, removed in 1.2.
class User
include Person
# @quirk caTissue work-around for caTissue Bug #66 - Client missing CSException class et al.
# caTissue User class initializes roleId to "", which triggers a client exception on subsequent
# getRoleId call. Use a private variable instead and bypass getRoleId.
#
# @quirk caTissue 1.2 Call to getRoleId results in the following error:
# NoClassDefFoundError: gov/nih/nci/security/dao/SearchCriteria
# This bug is probably a result of caTissue "fixing" Bug #66.
# The work-around to the caTissue bug fix bug is to return nil unless the role id has been set
# by a call to the {#role_id=} setter method.
def role_id
@role_id
end
# Sets the role id to the given value, which can be either a String or an Integer.
# An empty or zero value is converted to nil.
#
# @quirk caTissue caTissue API roleId is a String although the intended value domain is the
# integer csm_role.identifier.
def role_id=(value)
# value as an integer (nil is zero)
value_i = value.to_i
# set the Bug #66 work-around i.v.
@role_id = value_i.zero? ? nil : value_i
# value as a String (if non-nil)
value_s = @role_id.to_s if @role_id
# call Java with a String
setRoleId(value_s)
end
if property_defined?(:adminuser) then remove_attribute(:adminuser) end
# Make the convenience {CaRuby::Person::Name} name a first-class attribute.
add_attribute(:name, CaRuby::Person::Name)
if property_defined?(:clinical_studies) then remove_attribute(:clinical_studies) end
# Clarify that collection_protocols is a coordinator -> protocol association.
# Make assigned protocol and site attribute names consistent.
add_attribute_aliases(:coordinated_protocols => :collection_protocols, :protocols => :assigned_protocols, :assigned_sites => :sites)
# login_name is a database unique key.
set_secondary_key_attributes(:login_name)
# email_address is expected to be unique, and is enforced by the caTissue business logic.
set_alternate_key_attributes(:email_address)
# Set defaults as follows:
# * page_of is the value set when creating a User in the GUI
# * role id is 7 = Scientist (public)
# * initial password is 'changeMe1'
add_attribute_defaults(:activity_status => 'Active', :page_of => 'pageOfUserAdmin', :role_id => 7, :new_password => 'changeMe1')
# @quirk caTissue obscure GUI artifact User page_of attribute pollutes the data layer as a
# required attribute. Work-around is to simulate the GUI with a default value.
add_mandatory_attributes(:activity_status, :address, :cancer_research_group, :department,
:email_address, :first_name, :institution, :last_name, :page_of, :role_id)
# @quirk caTissue 1.2 User address can be updated in 1.1.2, but not 1.2. This difference is handled
# by the caRuby {CaTissue::Database} update case logic.
#
# @quirk caTissue 1.2 User address is fetched on create in 1.1.2, but not 1.2. This difference is
# handled by the caRuby {CaTissue::Database} create case logic.
add_dependent_attribute(:address)
# Password is removed as a visible caRuby attribute, since it is immutable in 1.2 and there
# is no use case for its access.
remove_attribute(:passwords)
set_attribute_inverse(:coordinated_protocols, :coordinators)
qualify_attribute(:coordinated_protocols, :saved)
set_attribute_inverse(:assigned_protocols, :assigned_protocol_users)
qualify_attribute(:assigned_protocols, :saved, :fetched)
set_attribute_inverse(:sites, :assigned_site_users)
qualify_attribute(:cancer_research_group, :fetched)
qualify_attribute(:department, :fetched)
qualify_attribute(:institution, :fetched)
qualify_attribute(:sites, :saved)
qualify_attribute(:page_of, :unfetched)
qualify_attribute(:new_password, :unfetched)
qualify_attribute(:role_id, :unfetched)
private
# By default, the email address is the same as the login name.
def add_defaults_local
super
self.login_name ||= email_address
self.email_address ||= login_name
end
end
end |
require 'byebug'
require 'pathname'
require 'git'
require 'json'
require 'fileutils'
require 'active_support'
module CenitCmd
class Collection < Thor::Group
include Thor::Actions
desc "builds a cenit_hub shared collection"
argument :file_name, type: :string, desc: 'collection path', default: '.'
argument :collection_name, type: :string, desc: 'collection name', default: '.'
source_root File.expand_path('../templates/collection', __FILE__)
class_option :user_name
class_option :user_email
class_option :github_username
class_option :summary
class_option :description
class_option :homepage
class_option :source
@generated = false
def generate
@collection_name = @file_name
use_prefix 'cenit-collection-'
@user_name = options[:user_name] || git_config['user.name']
@user_email = options[:user_email] || git_config['user.email']
@github_username = options[:github_username] || git_config['github.user']
@summary = options[:summary] || "Shared Collection #{@file_name} to be use in Cenit"
@description = options[:description] || @summary
@homepage = options[:homepage] || "https://github.com/#{@github_username}/#{@file_name}"
@source = options[:source]
return unless validate_argument
empty_directory file_name
directory 'lib', "#{file_name}/lib"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/connections"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/webhooks"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/connection_roles"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/events"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/flows"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/translators"
empty_directory "#{file_name}/spec/support"
empty_directory "#{file_name}/spec/support/sample"
template 'Gemfile', "#{file_name}/Gemfile"
template 'gitignore', "#{file_name}/.gitignore"
template 'LICENSE', "#{file_name}/LICENSE"
template 'Rakefile', "#{file_name}/Rakefile"
template 'README.md', "#{file_name}/README.md"
template 'rspec', "#{file_name}/.rspec"
template 'spec/spec_helper.rb.tt', "#{file_name}/spec/spec_helper.rb"
@load_data = false
import_from_file
puts "cd ./#{file_name}"
`cd ./#{file_name}`
puts "rake create_repo"
`rake create_repo`
puts "rake version:write"
`rake version:write`
puts "rake git:release"
`rake git:release`
@generated = true
end
def final_banner
return unless @generated
say %Q{
#{'*' * 80}
Consider the next steps:
Move to the new collection folder.
$ cd #{file_name}
Create a new git and related GitHub's repository
$ rake create_repo
Commit and push until you are happy with your changes
...
Generate a version
$ rake version:write
Tag and push release to git
$ rake git:release
Shared your collection in https://rubygems.org
$ rake release
Visit README.md for more details.
#{'*' * 80}
}
end
no_tasks do
def class_name
Thor::Util.camel_case @collection_name
end
def use_prefix(prefix)
unless file_name =~ /^#{prefix}/
@file_name = prefix + Thor::Util.snake_case(file_name)
end
end
# Expose git config here, so we can stub it out for test environments
def git_config
@git_config ||= Pathname.new("~/.gitconfig").expand_path.exist? ? Git.global_config : {}
end
def validate_argument
if @user_name.nil?
$stderr.puts %Q{No user.name found in ~/.gitconfig. Please tell git about yourself (see http://help.github.com/git-email-settings/ for details). For example: git config --global user.name "mad voo"}
return false
elsif @user_email.nil?
$stderr.puts %Q{No user.email found in ~/.gitconfig. Please tell git about yourself (see http://help.github.com/git-email-settings/ for details). For example: git config --global user.email mad.vooo@gmail.com}
return false
elsif @github_username.nil?
$stderr.puts %Q{Please specify --github-username or set github.user in ~/.gitconfig (see http://github.com/blog/180-local-github-config for details). For example: git config --global github.user defunkt}
return false
end
true
end
def import_from_file
unless @source.nil?
import_data(open_source)
@load_data = true
end
end
def import_data(data)
shared_data = JSON.parse(data)
hash_data = shared_data['data']
hash_model = []
models = ["flows","connection_roles","translators","events","connections","webhooks"]
models.collect do |model|
if hash_model = hash_data[model].to_a
hash_model.collect do |hash|
if file = filename_scape(hash['name'])
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/' + model + '/' + file + '.json', mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(hash))
end
end
end
end
end
libraries = hash_data['libraries']
library_index = []
libraries.collect do |library|
if library_name = library['name']
library_file = filename_scape (library_name)
FileUtils.mkpath(@file_name + '/lib/cenit/collection/' + @collection_name + '/libraries/' + library_file) unless File.directory?(@file_name + '/lib/cenit/collection/' + @collection_name + '/libraries/' + library_file)
library['schemas'].collect do |schema|
if schema_file = schema['uri']
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/' + '/libraries/' + library_file + '/' + schema_file, mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(JSON.parse(schema['schema'])))
end
end
end
library_index << {'name' => library_name, 'file' => library_file}
end
end
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/libraries/index.json', mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(library_index))
end
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/index.json', mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(shared_data.except('data')))
end
end
def open_source
File.open(@source, mode: "r:utf-8").read
rescue {}
end
def filename_scape(name)
name.gsub(/[^\w\s_-]+/, '')
.gsub(/(^|\b\s)\s+($|\s?\b)/, '\\1\\2')
.gsub(/\s+/, '_')
.downcase
end
end
end
end
added bundle exec
require 'byebug'
require 'pathname'
require 'git'
require 'json'
require 'fileutils'
require 'active_support'
module CenitCmd
class Collection < Thor::Group
include Thor::Actions
desc "builds a cenit_hub shared collection"
argument :file_name, type: :string, desc: 'collection path', default: '.'
argument :collection_name, type: :string, desc: 'collection name', default: '.'
source_root File.expand_path('../templates/collection', __FILE__)
class_option :user_name
class_option :user_email
class_option :github_username
class_option :summary
class_option :description
class_option :homepage
class_option :source
@generated = false
def generate
@collection_name = @file_name
use_prefix 'cenit-collection-'
@user_name = options[:user_name] || git_config['user.name']
@user_email = options[:user_email] || git_config['user.email']
@github_username = options[:github_username] || git_config['github.user']
@summary = options[:summary] || "Shared Collection #{@file_name} to be use in Cenit"
@description = options[:description] || @summary
@homepage = options[:homepage] || "https://github.com/#{@github_username}/#{@file_name}"
@source = options[:source]
return unless validate_argument
empty_directory file_name
directory 'lib', "#{file_name}/lib"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/connections"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/webhooks"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/connection_roles"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/events"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/flows"
empty_directory "#{file_name}/lib/cenit/collection/#{collection_name}/translators"
empty_directory "#{file_name}/spec/support"
empty_directory "#{file_name}/spec/support/sample"
template 'Gemfile', "#{file_name}/Gemfile"
template 'gitignore', "#{file_name}/.gitignore"
template 'LICENSE', "#{file_name}/LICENSE"
template 'Rakefile', "#{file_name}/Rakefile"
template 'README.md', "#{file_name}/README.md"
template 'rspec', "#{file_name}/.rspec"
template 'spec/spec_helper.rb.tt', "#{file_name}/spec/spec_helper.rb"
@load_data = false
import_from_file
puts "cd ./#{file_name}"
`cd ./#{file_name}`
puts "bundle exec rake create_repo"
`rake bundle exec create_repo`
puts "bundle exec rake version:write"
`bundle exec rake version:write`
puts "bundle exec rake git:release"
`bundle exec rake git:release`
@generated = true
end
def final_banner
return unless @generated
say %Q{
#{'*' * 80}
Consider the next steps:
Move to the new collection folder.
$ cd #{file_name}
Create a new git and related GitHub's repository
$ rake create_repo
Commit and push until you are happy with your changes
...
Generate a version
$ rake version:write
Tag and push release to git
$ rake git:release
Shared your collection in https://rubygems.org
$ rake release
Visit README.md for more details.
#{'*' * 80}
}
end
no_tasks do
def class_name
Thor::Util.camel_case @collection_name
end
def use_prefix(prefix)
unless file_name =~ /^#{prefix}/
@file_name = prefix + Thor::Util.snake_case(file_name)
end
end
# Expose git config here, so we can stub it out for test environments
def git_config
@git_config ||= Pathname.new("~/.gitconfig").expand_path.exist? ? Git.global_config : {}
end
def validate_argument
if @user_name.nil?
$stderr.puts %Q{No user.name found in ~/.gitconfig. Please tell git about yourself (see http://help.github.com/git-email-settings/ for details). For example: git config --global user.name "mad voo"}
return false
elsif @user_email.nil?
$stderr.puts %Q{No user.email found in ~/.gitconfig. Please tell git about yourself (see http://help.github.com/git-email-settings/ for details). For example: git config --global user.email mad.vooo@gmail.com}
return false
elsif @github_username.nil?
$stderr.puts %Q{Please specify --github-username or set github.user in ~/.gitconfig (see http://github.com/blog/180-local-github-config for details). For example: git config --global github.user defunkt}
return false
end
true
end
def import_from_file
unless @source.nil?
import_data(open_source)
@load_data = true
end
end
def import_data(data)
shared_data = JSON.parse(data)
hash_data = shared_data['data']
hash_model = []
models = ["flows","connection_roles","translators","events","connections","webhooks"]
models.collect do |model|
if hash_model = hash_data[model].to_a
hash_model.collect do |hash|
if file = filename_scape(hash['name'])
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/' + model + '/' + file + '.json', mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(hash))
end
end
end
end
end
libraries = hash_data['libraries']
library_index = []
libraries.collect do |library|
if library_name = library['name']
library_file = filename_scape (library_name)
FileUtils.mkpath(@file_name + '/lib/cenit/collection/' + @collection_name + '/libraries/' + library_file) unless File.directory?(@file_name + '/lib/cenit/collection/' + @collection_name + '/libraries/' + library_file)
library['schemas'].collect do |schema|
if schema_file = schema['uri']
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/' + '/libraries/' + library_file + '/' + schema_file, mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(JSON.parse(schema['schema'])))
end
end
end
library_index << {'name' => library_name, 'file' => library_file}
end
end
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/libraries/index.json', mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(library_index))
end
File.open(@file_name + '/lib/cenit/collection/' + @collection_name + '/index.json', mode: "w:utf-8") do |f|
f.write(JSON.pretty_generate(shared_data.except('data')))
end
end
def open_source
File.open(@source, mode: "r:utf-8").read
rescue {}
end
def filename_scape(name)
name.gsub(/[^\w\s_-]+/, '')
.gsub(/(^|\b\s)\s+($|\s?\b)/, '\\1\\2')
.gsub(/\s+/, '_')
.downcase
end
end
end
end
|
automatically parse program help
require 'pp'
class ProgramParser
def initialize(path='', name='')
# raise 'ERROR: cannot parse program: no file at that path!' unless File.exists? path
@path = path
@name = name
end
def parse
# parse program's help message, generate the arguments hash, and store the definition
raise 'ERROR: could not retrieve help message: please define the program manually' unless self.gethelp
raise 'ERROR: could not parse retrieved help message: please define manually' unless self.parse_help
@program = {
:name => @name,
:path => @path,
:arguments => @args
}
end
# we hope the program will respond with the help message
# to one of these arguments
HelpFlags = ['', ' -h', ' -help', ' --help']
def gethelp
# attempt to retrieve the help message
HelpFlags.each do |helpflag|
`#{@path + helpflag} &> capturehelpmsg.tmp`
helpmsg = File.open('capturehelpmsg.tmp').read
File.delete('capturehelpmsg.tmp')
# note: do we need to check exit status?
# bowtie, tophat and cufflinks exit 0, 1, 2 repsectively
# when run with no args - not consistent
unless helpmsg.split(/\n/).length > 1
next
end
@helpmsg = helpmsg
return true
end
false
end
def parse_help
# parse out arguments from help message
lines = @helpmsg.split(/\n/)
args = {}
lines.each do |line|
line = line.strip
next if line =~
d = nil
if line =~ /\t/
segments = line.split(/\t/)
d = self.parse_segments segments
else
segments = line.split(/\s{2,}/)
d = self.parse_segments segments
end
unless d.nil?
d[:default] = self.guess_default(d)
args[d[:arg][0]] = d
end
end
@args = args
return true
# rescue Exception => e
# puts "error trying to parse help: #{e}"
# nil
end
def parse_segments(segments)
# extract argument data from parts of a help line
if segments.length > 1
arg = {}
remaining = [] # to collect any unused segments for description
gotflags = false
segments.each do |segment|
if segment =~ /:$/
# ignore headings like "Heading:"
next
elsif segment =~ /^-+/
# capture the flags!
parts = segment.split(' ')
parts.each do |part|
if part =~ /-{1,2}[a-zA-Z0-9]+/ && !gotflags
# flags/arguments
a = part.split(/[\/\s]/)
a = a.each{ |f| f.scan(/(-{1,2}[a-zA-Z0-9]+)/) }
arg[:arg] = a
gotflags = true
elsif part =~ /<.*>/
# type
type = self.extract_type(part)
arg[:type] = type if type
else
# save it for description
remaining << part
end
end
arg[:type] ||= 'flag'
else
if segment =~ /<.*>/
# type
type = self.extract_type(segment)
arg[:type] = type if type
end
# save it for description
remaining << segment
end
end
arg[:desc] = remaining.join(', ').strip if (gotflags && remaining.length > 0)
return arg.length > 0 ? arg : nil
end
nil
end
# we use these lists of keywords to detect argument types
StringTypes = %w(string str file fname filename path text)
IntTypes = %w(int integer long longint number value)
FloatTypes = %w(float decimal fraction prop proportion prob probability)
def extract_type(part)
# try to return the type for an argument
typeword = /<([^>]+)>/.match(part)[1]
unless typeword.nil?
return :string if StringTypes.include? typeword
return :integer if IntTypes.include? typeword
return :float if FloatTypes.include? typeword
end
nil
end
# we use these defaults if we can't guess values from the help line
# having something as a placeholder allows the user to easily replace
# the default value without having to create the data structure
Defaults = {
'string' => 'change me',
'integer' => 10000,
'float' => 0.0001,
'flag' => false
}
# we use these regexes to detect different ways of extracting the default
DefaultRegexes = [
/[\(\[](?:def|default)?(?:\:|=)?\s*(\w+)[\)\]]/
]
# we use this to scan for flag defaults
FlagWords = {
:true => ['true', 'yes', 'on'],
:false => ['false', 'no', 'off']
}
# attempt to guess the default value for an argument
def guess_default(args)
# we use the description to guess
return Defaults[args[:type]] if args[:desc].nil?
type = args[:type] == 'flag' ? 'flag' : Kernel.const_get(args[:type].capitalize)
test = args[:desc].strip
guesses = []
DefaultRegexes.each do |regex|
guesses += test.scan(regex) if test =~ regex
end
if guesses.length > 0
# we have guesses - try to understand them
# note: at the moment we only parse the first guess
# if we add more to DefaultRegexes we might need to
# iterate over the guesses to see if any matches the type
guess = guesses.first.first
if type != 'flag'
# easy to check if we can convert to type
can_convert = self.convert_to(guess, type)
if !can_convert.nil?
# guess is the same as type, hooray!
return can_convert
end
else
# type is flag - check the guess is a flag
if FlagWords[:true].include? guess
return true
elsif FlagWords[:false].include? guess
return false
else
# it's not really a flag
is_int = self.convert_to(guess, Integer)
if !is_int.nil?
# type is really int
args[:type] = 'integer'
return is_int
end
is_float = self.convert_to(guess, Float)
if !is_float.nil?
# type is really float
args[:type] = 'integer'
return is_float
end
# eliminated all other options - it's a string
args[:type] = 'string'
return guess
end
end
else
return Defaults[args[:type]]
end
guesses
end
# attempt to convert string guess to object of type
# return nil on failure
def convert_to(string, type)
if type == Integer
return Integer(string)
elsif type == Float
return Float(string)
else
return string
end
rescue ArgumentError
return nil
end
end |
require 'pp'
module Channel9
# Exits with a status code of 0 regardless of what's passed to it.
module CleanExitChannel
def self.channel_send(env, val, ret)
exit(0)
end
end
# Exits with the status code passed to it.
module ExitChannel
def self.channel_send(env, val, ret)
exit(val.to_i)
end
end
# Used as a guard when a sender does not expect to be returned to.
# Just blows things up.
module InvalidReturnChannel
def self.channel_send(env, val, ret)
raise "Invalid Return, exiting"
end
end
# Used to output information to stdout. Prints whatever's
# passed to it.
module StdoutChannel
def self.channel_send(env, val, ret)
$stdout.puts(val)
ret.channel_send(env, val, InvalidReturnChannel)
end
end
class Environment
attr :context
attr :special_channel
attr :debug, true
attr :running
def initialize(debug = false)
@context = nil
@running = false
@debug = debug
@special_channel = {
:clean_exit => CleanExitChannel,
:exit => ExitChannel,
:invalid_return => InvalidReturnChannel,
:stdout => StdoutChannel
}
end
# stores the context for the duration of a block and then
# restores it when done. Used for instructions that need
# to call back into the environment. (eg. string_new).
# in most cases, you will probably need to indicate when to
# exit the sub-state by throwing :end_save.
def save_context
catch (:end_save) do
begin
prev_context = @context
prev_running = @running
@context = nil
@running = false
yield
ensure
@running = true
@context = prev_context
end
end
end
def run(context)
@context = context
if (!@running)
@running = true
begin
while (instruction = @context.next)
current_context = @context
sp = @context.stack.length
pp(:instruction => {:ip => @context.pos - 1, :instruction => instruction.debug_info}) if @debug
pp(:before => @context.debug_info) if @debug
instruction.run(self)
pp(:orig_after_jump => current_context.debug_info) if @debug && current_context != @context
pp(:after => @context.debug_info) if @debug
puts("--------------") if @debug
stack_should = (sp - instruction.stack_input + instruction.stack_output)
if (current_context.stack.length != stack_should)
raise "Stack error: Expected stack depth to be #{stack_should}, was actually #{current_context.stack.length}"
end
end
if (@debug)
require 'pp'
pp(
:final_state => @context.debug_info
)
end
ensure
@running = false
end
end
end
end
end
Made the special builtin channels truthy.
require 'pp'
module Channel9
# Exits with a status code of 0 regardless of what's passed to it.
module CleanExitChannel
def self.channel_send(env, val, ret)
exit(0)
end
def self.truthy?; true; end
end
# Exits with the status code passed to it.
module ExitChannel
def self.channel_send(env, val, ret)
exit(val.to_i)
end
def self.truthy?; true; end
end
# Used as a guard when a sender does not expect to be returned to.
# Just blows things up.
module InvalidReturnChannel
def self.channel_send(env, val, ret)
raise "Invalid Return, exiting"
end
def self.truthy?; true; end
end
# Used to output information to stdout. Prints whatever's
# passed to it.
module StdoutChannel
def self.channel_send(env, val, ret)
$stdout.puts(val)
ret.channel_send(env, val, InvalidReturnChannel)
end
def self.truthy?; true; end
end
class Environment
attr :context
attr :special_channel
attr :debug, true
attr :running
def initialize(debug = false)
@context = nil
@running = false
@debug = debug
@special_channel = {
:clean_exit => CleanExitChannel,
:exit => ExitChannel,
:invalid_return => InvalidReturnChannel,
:stdout => StdoutChannel
}
end
# stores the context for the duration of a block and then
# restores it when done. Used for instructions that need
# to call back into the environment. (eg. string_new).
# in most cases, you will probably need to indicate when to
# exit the sub-state by throwing :end_save.
def save_context
catch (:end_save) do
begin
prev_context = @context
prev_running = @running
@context = nil
@running = false
yield
ensure
@running = true
@context = prev_context
end
end
end
def run(context)
@context = context
if (!@running)
@running = true
begin
while (instruction = @context.next)
current_context = @context
sp = @context.stack.length
pp(:instruction => {:ip => @context.pos - 1, :instruction => instruction.debug_info}) if @debug
pp(:before => @context.debug_info) if @debug
instruction.run(self)
pp(:orig_after_jump => current_context.debug_info) if @debug && current_context != @context
pp(:after => @context.debug_info) if @debug
puts("--------------") if @debug
stack_should = (sp - instruction.stack_input + instruction.stack_output)
if (current_context.stack.length != stack_should)
raise "Stack error: Expected stack depth to be #{stack_should}, was actually #{current_context.stack.length}"
end
end
if (@debug)
require 'pp'
pp(
:final_state => @context.debug_info
)
end
ensure
@running = false
end
end
end
end
end |
require "tempfile"
module Cheatly
module Adapter
class File
def find(name)
path = "sheets/#{name}.md"
::File.read(path)
end
def all
Dir["sheets/*.md"].map { |f| f.scan(/sheets\/(.*).md/)[0][0] }
end
def create(name, body)
body = {name => body}.to_yaml
f = ::File.new("sheets/#{name}.md", "w")
f.write(body)
f.close
end
def update(name, body)
::File.delete("sheets/#{name}.md")
create(name, body)
end
end
end
end
No need to call to_yaml anymore
require "tempfile"
module Cheatly
module Adapter
class File
def find(name)
path = "sheets/#{name}.md"
::File.read(path)
end
def all
Dir["sheets/*.md"].map { |f| f.scan(/sheets\/(.*).md/)[0][0] }
end
def create(name, body)
f = ::File.new("sheets/#{name}.md", "w")
f.write(body)
f.close
end
def update(name, body)
::File.delete("sheets/#{name}.md")
create(name, body)
end
end
end
end
|
module ChefRunDeck
VERSION = '0.1.0'.freeze
end
Bump version
module ChefRunDeck
VERSION = '0.1.1'.freeze
end
|
require 'rubygems'
require 'chef'
require 'chef/handler'
require 'dogapi'
class Chef
class Handler
class Datadog < Chef::Handler
# For the tags to work, the client must have created an Application Key on the
# "Account Settings" page here: https://app.datadoghq.com/account/settings
# It should be passed along from the node/role/environemnt attributes, as the default is nil.
def initialize(opts = nil)
opts = opts || {}
@api_key = opts[:api_key]
@application_key = opts[:application_key]
# If we're on ec2, use the instance by default, unless instructed otherwise
@use_ec2_instance_id = !opts.has_key?(:use_ec2_instance_id) || opts.has_key?(:use_ec2_instance_id) && opts[:use_ec2_instance_id]
@dog = Dogapi::Client.new(@api_key, application_key = @application_key)
end
def report
hostname = run_status.node.name
if @use_ec2_instance_id && run_status.node.attribute?("ec2") && run_status.node.ec2.attribute?("instance_id")
hostname = run_status.node.ec2.instance_id
end
# Send the metrics
begin
@dog.emit_point("chef.resources.total", run_status.all_resources.length, :host => hostname)
@dog.emit_point("chef.resources.updated", run_status.updated_resources.length, :host => hostname)
@dog.emit_point("chef.resources.elapsed_time", run_status.elapsed_time, :host => hostname)
Chef::Log.debug("Submitted chef metrics back to Datadog")
rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT => e
Chef::Log.error("Could not send metrics to Datadog. Connection error:\n" + e)
end
event_title = ""
run_time = pluralize(run_status.elapsed_time, "second")
if run_status.success?
alert_type = "success"
event_priority = "low"
event_title << "Chef completed in #{run_time} on #{hostname} "
else
event_title << "Chef failed in #{run_time} on #{hostname} "
end
event_data = "Chef updated #{run_status.updated_resources.length} resources out of #{run_status.all_resources.length} resources total."
if run_status.updated_resources.length.to_i > 0
event_data << "\n@@@\n"
run_status.updated_resources.each do |r|
event_data << "- #{r.to_s} (#{defined_at(r)})\n"
end
event_data << "\n@@@\n"
end
if run_status.failed?
alert_type = "error"
event_priority = "normal"
event_data << "\n@@@\n#{run_status.formatted_exception}\n@@@\n"
event_data << "\n@@@\n#{run_status.backtrace.join("\n")}\n@@@\n"
end
# Submit the details back to Datadog
begin
# Send the Event data
evt = @dog.emit_event(Dogapi::Event.new(event_data,
:msg_title => event_title,
:event_type => 'config_management.run',
:event_object => hostname,
:alert_type => alert_type,
:priority => event_priority,
:source_type_name => 'chef'
), :host => hostname)
begin
# FIXME nice-to-have: abstract format of return value away a bit
# in dogapi directly. See https://github.com/DataDog/dogapi-rb/issues/18
if evt.length < 2
Chef::Log.warn("Unexpected response from Datadog Event API: #{evt}")
else
# [http_response_code, {"event" => {"url" => "...", ...}}]
# 2xx means ok
if evt[0].to_i / 100 != 2
Chef::Log.warn("Could not submit event to Datadog (HTTP call failed): #{evt[0]}")
else
Chef::Log.debug("Successfully submitted Chef event to Datadog for #{hostname} at #{evt[1]['event']['url']}")
end
end
rescue
Chef::Log.warn("Could not determine whether chef run was successfully submitted to Datadog: #{evt}")
end
# Get the current list of tags, remove any "role:" entries
host_tags = @dog.host_tags(hostname)[1]["tags"] || []
host_tags.delete_if {|tag| tag.start_with?('role:') }
# Get list of chef roles, rename them to tag format
chef_roles = node.run_list.roles
chef_roles.collect! {|role| "role:" + role }
# Get the chef environment (as long as it's not '_default')
if node.respond_to?('chef_environment') && node.chef_environment != '_default'
host_tags.delete_if {|tag| tag.start_with?('env:') }
host_tags << "env:" + node.chef_environment
end
# Combine (union) both arrays. Removes dupes, preserves non-chef tags.
new_host_tags = host_tags | chef_roles
if @application_key.nil?
Chef::Log.warn("You need an application key to let Chef tag your nodes in Datadog. Visit https://app.datadoghq.com/account/settings#api to create one and update your datadog attributes in the datadog cookbook.")
else
# Replace all tags with the new tags
rc = @dog.update_tags(hostname, new_host_tags)
begin
# See FIXME above about why I feel dirty repeating this code here
if evt.length < 2
Chef::Log.warn("Unexpected response from Datadog Event API: #{evt}")
else
if rc[0].to_i / 100 != 2
Chef::Log.warn("Could not submit #{chef_roles} tags for #{hostname} to Datadog")
else
Chef::Log.debug("Successfully updated #{hostname}'s tags to #{new_host_tags.join(', ')}")
end
end
rescue
Chef::Log.warn("Could not determine whether #{hostname}'s tags were successfully submitted to Datadog: #{rc}")
end
end
rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT => e
Chef::Log.error("Could not connect to Datadog. Connection error:\n" + e)
Chef::Log.error("Data to be submitted was:")
Chef::Log.error(event_title)
Chef::Log.error(event_data)
Chef::Log.error("Tags to be set for this run:")
Chef::Log.error(new_host_tags)
end
end
private
def pluralize(number, noun)
begin
case number
when 0..1
"less than 1 #{noun}"
else
"#{number.round} #{noun}s"
end
rescue
Chef::Log.warn("Cannot make #{number} more legible")
"#{number} #{noun}s"
end
end
## This function is to mimic behavior built into a later version of chef than 0.9.x
## Source is here: https://github.com/opscode/chef/blob/master/chef/lib/chef/resource.rb#L415-424
## Including this based on help from schisamo
def defined_at(resource)
cookbook_name = resource.cookbook_name
recipe_name = resource.recipe_name
source_line = resource.source_line
if cookbook_name && recipe_name && source_line
"#{cookbook_name}::#{recipe_name} line #{source_line.split(':')[1]}"
elsif source_line
file, line_no = source_line.split(':')
"#{file} line #{line_no}"
else
"dynamically defined"
end
end
end #end class Datadog
end #end class Handler
end #end class Chef
caught a typo thanks to @miketheman
require 'rubygems'
require 'chef'
require 'chef/handler'
require 'dogapi'
class Chef
class Handler
class Datadog < Chef::Handler
# For the tags to work, the client must have created an Application Key on the
# "Account Settings" page here: https://app.datadoghq.com/account/settings
# It should be passed along from the node/role/environemnt attributes, as the default is nil.
def initialize(opts = nil)
opts = opts || {}
@api_key = opts[:api_key]
@application_key = opts[:application_key]
# If we're on ec2, use the instance by default, unless instructed otherwise
@use_ec2_instance_id = !opts.has_key?(:use_ec2_instance_id) || opts.has_key?(:use_ec2_instance_id) && opts[:use_ec2_instance_id]
@dog = Dogapi::Client.new(@api_key, application_key = @application_key)
end
def report
hostname = run_status.node.name
if @use_ec2_instance_id && run_status.node.attribute?("ec2") && run_status.node.ec2.attribute?("instance_id")
hostname = run_status.node.ec2.instance_id
end
# Send the metrics
begin
@dog.emit_point("chef.resources.total", run_status.all_resources.length, :host => hostname)
@dog.emit_point("chef.resources.updated", run_status.updated_resources.length, :host => hostname)
@dog.emit_point("chef.resources.elapsed_time", run_status.elapsed_time, :host => hostname)
Chef::Log.debug("Submitted chef metrics back to Datadog")
rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT => e
Chef::Log.error("Could not send metrics to Datadog. Connection error:\n" + e)
end
event_title = ""
run_time = pluralize(run_status.elapsed_time, "second")
if run_status.success?
alert_type = "success"
event_priority = "low"
event_title << "Chef completed in #{run_time} on #{hostname} "
else
event_title << "Chef failed in #{run_time} on #{hostname} "
end
event_data = "Chef updated #{run_status.updated_resources.length} resources out of #{run_status.all_resources.length} resources total."
if run_status.updated_resources.length.to_i > 0
event_data << "\n@@@\n"
run_status.updated_resources.each do |r|
event_data << "- #{r.to_s} (#{defined_at(r)})\n"
end
event_data << "\n@@@\n"
end
if run_status.failed?
alert_type = "error"
event_priority = "normal"
event_data << "\n@@@\n#{run_status.formatted_exception}\n@@@\n"
event_data << "\n@@@\n#{run_status.backtrace.join("\n")}\n@@@\n"
end
# Submit the details back to Datadog
begin
# Send the Event data
evt = @dog.emit_event(Dogapi::Event.new(event_data,
:msg_title => event_title,
:event_type => 'config_management.run',
:event_object => hostname,
:alert_type => alert_type,
:priority => event_priority,
:source_type_name => 'chef'
), :host => hostname)
begin
# FIXME nice-to-have: abstract format of return value away a bit
# in dogapi directly. See https://github.com/DataDog/dogapi-rb/issues/18
if evt.length < 2
Chef::Log.warn("Unexpected response from Datadog Event API: #{evt}")
else
# [http_response_code, {"event" => {"url" => "...", ...}}]
# 2xx means ok
if evt[0].to_i / 100 != 2
Chef::Log.warn("Could not submit event to Datadog (HTTP call failed): #{evt[0]}")
else
Chef::Log.debug("Successfully submitted Chef event to Datadog for #{hostname} at #{evt[1]['event']['url']}")
end
end
rescue
Chef::Log.warn("Could not determine whether chef run was successfully submitted to Datadog: #{evt}")
end
# Get the current list of tags, remove any "role:" entries
host_tags = @dog.host_tags(hostname)[1]["tags"] || []
host_tags.delete_if {|tag| tag.start_with?('role:') }
# Get list of chef roles, rename them to tag format
chef_roles = node.run_list.roles
chef_roles.collect! {|role| "role:" + role }
# Get the chef environment (as long as it's not '_default')
if node.respond_to?('chef_environment') && node.chef_environment != '_default'
host_tags.delete_if {|tag| tag.start_with?('env:') }
host_tags << "env:" + node.chef_environment
end
# Combine (union) both arrays. Removes dupes, preserves non-chef tags.
new_host_tags = host_tags | chef_roles
if @application_key.nil?
Chef::Log.warn("You need an application key to let Chef tag your nodes in Datadog. Visit https://app.datadoghq.com/account/settings#api to create one and update your datadog attributes in the datadog cookbook.")
else
# Replace all tags with the new tags
rc = @dog.update_tags(hostname, new_host_tags)
begin
# See FIXME above about why I feel dirty repeating this code here
if rc.length < 2
Chef::Log.warn("Unexpected response from Datadog Event API: #{evt}")
else
if rc[0].to_i / 100 != 2
Chef::Log.warn("Could not submit #{chef_roles} tags for #{hostname} to Datadog")
else
Chef::Log.debug("Successfully updated #{hostname}'s tags to #{new_host_tags.join(', ')}")
end
end
rescue
Chef::Log.warn("Could not determine whether #{hostname}'s tags were successfully submitted to Datadog: #{rc}")
end
end
rescue Errno::ECONNREFUSED, Errno::ETIMEDOUT => e
Chef::Log.error("Could not connect to Datadog. Connection error:\n" + e)
Chef::Log.error("Data to be submitted was:")
Chef::Log.error(event_title)
Chef::Log.error(event_data)
Chef::Log.error("Tags to be set for this run:")
Chef::Log.error(new_host_tags)
end
end
private
def pluralize(number, noun)
begin
case number
when 0..1
"less than 1 #{noun}"
else
"#{number.round} #{noun}s"
end
rescue
Chef::Log.warn("Cannot make #{number} more legible")
"#{number} #{noun}s"
end
end
## This function is to mimic behavior built into a later version of chef than 0.9.x
## Source is here: https://github.com/opscode/chef/blob/master/chef/lib/chef/resource.rb#L415-424
## Including this based on help from schisamo
def defined_at(resource)
cookbook_name = resource.cookbook_name
recipe_name = resource.recipe_name
source_line = resource.source_line
if cookbook_name && recipe_name && source_line
"#{cookbook_name}::#{recipe_name} line #{source_line.split(':')[1]}"
elsif source_line
file, line_no = source_line.split(':')
"#{file} line #{line_no}"
else
"dynamically defined"
end
end
end #end class Datadog
end #end class Handler
end #end class Chef
|
#
# Author:: Adam Jacob (<adam@opscode.com>)
# Copyright:: Copyright (c) 2010 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/knife'
require 'erubis'
class Chef
class Knife
class Bootstrap < Knife
deps do
require 'chef/knife/core/bootstrap_context'
require 'chef/json_compat'
require 'tempfile'
require 'highline'
require 'net/ssh'
require 'net/ssh/multi'
require 'chef/knife/ssh'
Chef::Knife::Ssh.load_deps
end
banner "knife bootstrap FQDN (options)"
option :ssh_user,
:short => "-x USERNAME",
:long => "--ssh-user USERNAME",
:description => "The ssh username",
:default => "root"
option :ssh_password,
:short => "-P PASSWORD",
:long => "--ssh-password PASSWORD",
:description => "The ssh password"
option :ssh_port,
:short => "-p PORT",
:long => "--ssh-port PORT",
:description => "The ssh port",
:proc => Proc.new { |key| Chef::Config[:knife][:ssh_port] = key }
option :ssh_gateway,
:short => "-G GATEWAY",
:long => "--ssh-gateway GATEWAY",
:description => "The ssh gateway",
:proc => Proc.new { |key| Chef::Config[:knife][:ssh_gateway] = key }
option :identity_file,
:short => "-i IDENTITY_FILE",
:long => "--identity-file IDENTITY_FILE",
:description => "The SSH identity file used for authentication"
option :chef_node_name,
:short => "-N NAME",
:long => "--node-name NAME",
:description => "The Chef node name for your new node"
option :prerelease,
:long => "--prerelease",
:description => "Install the pre-release chef gems"
option :bootstrap_version,
:long => "--bootstrap-version VERSION",
:description => "The version of Chef to install",
:proc => lambda { |v| Chef::Config[:knife][:bootstrap_version] = v }
option :bootstrap_proxy,
:long => "--bootstrap-proxy PROXY_URL",
:description => "The proxy server for the node being bootstrapped",
:proc => Proc.new { |p| Chef::Config[:knife][:bootstrap_proxy] = p }
option :distro,
:short => "-d DISTRO",
:long => "--distro DISTRO",
:description => "Bootstrap a distro using a template",
:default => "chef-full"
option :use_sudo,
:long => "--sudo",
:description => "Execute the bootstrap via sudo",
:boolean => true
option :template_file,
:long => "--template-file TEMPLATE",
:description => "Full path to location of template to use",
:default => false
option :run_list,
:short => "-r RUN_LIST",
:long => "--run-list RUN_LIST",
:description => "Comma separated list of roles/recipes to apply",
:proc => lambda { |o| o.split(/[\s,]+/) },
:default => []
option :first_boot_attributes,
:short => "-j JSON_ATTRIBS",
:long => "--json-attributes",
:description => "A JSON string to be added to the first run of chef-client",
:proc => lambda { |o| JSON.parse(o) },
:default => {}
option :host_key_verify,
:long => "--[no-]host-key-verify",
:description => "Verify host key, enabled by default.",
:boolean => true,
:default => true
option :hint,
:long => "--hint HINT_NAME[=HINT_FILE]",
:description => "Specify Ohai Hint to be set on the bootstrap target. Use multiple --hint options to specify multiple hints.",
:proc => Proc.new { |h|
Chef::Config[:knife][:hints] ||= Hash.new
name, path = h.split("=")
Chef::Config[:knife][:hints][name] = path ? JSON.parse(::File.read(path)) : Hash.new }
def find_template(template=nil)
# Are we bootstrapping using an already shipped template?
if config[:template_file]
bootstrap_files = config[:template_file]
else
bootstrap_files = []
bootstrap_files << File.join(File.dirname(__FILE__), 'bootstrap', "#{config[:distro]}.erb")
bootstrap_files << File.join(Knife.chef_config_dir, "bootstrap", "#{config[:distro]}.erb") if Knife.chef_config_dir
bootstrap_files << File.join(ENV['HOME'], '.chef', 'bootstrap', "#{config[:distro]}.erb") if ENV['HOME']
bootstrap_files << Gem.find_files(File.join("chef","knife","bootstrap","#{config[:distro]}.erb"))
bootstrap_files.flatten!
end
template = Array(bootstrap_files).find do |bootstrap_template|
Chef::Log.debug("Looking for bootstrap template in #{File.dirname(bootstrap_template)}")
File.exists?(bootstrap_template)
end
unless template
ui.info("Can not find bootstrap definition for #{config[:distro]}")
raise Errno::ENOENT
end
Chef::Log.debug("Found bootstrap template in #{File.dirname(template)}")
template
end
def render_template(template=nil)
context = Knife::Core::BootstrapContext.new(config, config[:run_list], Chef::Config)
Erubis::Eruby.new(template).evaluate(context)
end
def read_template
IO.read(@template_file).chomp
end
def run
validate_name_args!
@template_file = find_template(config[:bootstrap_template])
@node_name = Array(@name_args).first
# back compat--templates may use this setting:
config[:server_name] = @node_name
$stdout.sync = true
ui.info("Bootstrapping Chef on #{ui.color(@node_name, :bold)}")
begin
knife_ssh.run
rescue Net::SSH::AuthenticationFailed
unless config[:ssh_password]
ui.info("Failed to authenticate #{config[:ssh_user]} - trying password auth")
knife_ssh_with_password_auth.run
end
end
end
def validate_name_args!
if Array(@name_args).first.nil?
ui.error("Must pass an FQDN or ip to bootstrap")
exit 1
end
end
def server_name
Array(@name_args).first
end
def knife_ssh
ssh = Chef::Knife::Ssh.new
ssh.ui = ui
ssh.name_args = [ server_name, ssh_command ]
ssh.config[:ssh_user] = Chef::Config[:knife][:ssh_user] || config[:ssh_user]
ssh.config[:ssh_password] = config[:ssh_password]
ssh.config[:ssh_port] = Chef::Config[:knife][:ssh_port] || config[:ssh_port]
ssh.config[:ssh_gateway] = Chef::Config[:knife][:ssh_gateway] || config[:ssh_gateway]
ssh.config[:identity_file] = Chef::Config[:knife][:identity_file] || config[:identity_file]
ssh.config[:manual] = true
ssh.config[:host_key_verify] = Chef::Config[:knife][:host_key_verify] || config[:host_key_verify]
ssh.config[:on_error] = :raise
ssh
end
def knife_ssh_with_password_auth
ssh = knife_ssh
ssh.config[:identity_file] = nil
ssh.config[:ssh_password] = ssh.get_password
ssh
end
def ssh_command
command = render_template(read_template)
if config[:use_sudo]
command = "sudo #{command}"
end
command
end
end
end
end
Enable password to sudo from stdin for knife ssh bootstrap
#
# Author:: Adam Jacob (<adam@opscode.com>)
# Copyright:: Copyright (c) 2010 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/knife'
require 'erubis'
class Chef
class Knife
class Bootstrap < Knife
deps do
require 'chef/knife/core/bootstrap_context'
require 'chef/json_compat'
require 'tempfile'
require 'highline'
require 'net/ssh'
require 'net/ssh/multi'
require 'chef/knife/ssh'
Chef::Knife::Ssh.load_deps
end
banner "knife bootstrap FQDN (options)"
option :ssh_user,
:short => "-x USERNAME",
:long => "--ssh-user USERNAME",
:description => "The ssh username",
:default => "root"
option :ssh_password,
:short => "-P PASSWORD",
:long => "--ssh-password PASSWORD",
:description => "The ssh password"
option :ssh_port,
:short => "-p PORT",
:long => "--ssh-port PORT",
:description => "The ssh port",
:proc => Proc.new { |key| Chef::Config[:knife][:ssh_port] = key }
option :ssh_gateway,
:short => "-G GATEWAY",
:long => "--ssh-gateway GATEWAY",
:description => "The ssh gateway",
:proc => Proc.new { |key| Chef::Config[:knife][:ssh_gateway] = key }
option :identity_file,
:short => "-i IDENTITY_FILE",
:long => "--identity-file IDENTITY_FILE",
:description => "The SSH identity file used for authentication"
option :chef_node_name,
:short => "-N NAME",
:long => "--node-name NAME",
:description => "The Chef node name for your new node"
option :prerelease,
:long => "--prerelease",
:description => "Install the pre-release chef gems"
option :bootstrap_version,
:long => "--bootstrap-version VERSION",
:description => "The version of Chef to install",
:proc => lambda { |v| Chef::Config[:knife][:bootstrap_version] = v }
option :bootstrap_proxy,
:long => "--bootstrap-proxy PROXY_URL",
:description => "The proxy server for the node being bootstrapped",
:proc => Proc.new { |p| Chef::Config[:knife][:bootstrap_proxy] = p }
option :distro,
:short => "-d DISTRO",
:long => "--distro DISTRO",
:description => "Bootstrap a distro using a template",
:default => "chef-full"
option :use_sudo,
:long => "--sudo",
:description => "Execute the bootstrap via sudo",
:boolean => true
option :use_sudo_password,
:long => "--use-sudo-password",
:description => "Execute the bootstrap via sudo with password",
:boolean => false
option :template_file,
:long => "--template-file TEMPLATE",
:description => "Full path to location of template to use",
:default => false
option :run_list,
:short => "-r RUN_LIST",
:long => "--run-list RUN_LIST",
:description => "Comma separated list of roles/recipes to apply",
:proc => lambda { |o| o.split(/[\s,]+/) },
:default => []
option :first_boot_attributes,
:short => "-j JSON_ATTRIBS",
:long => "--json-attributes",
:description => "A JSON string to be added to the first run of chef-client",
:proc => lambda { |o| JSON.parse(o) },
:default => {}
option :host_key_verify,
:long => "--[no-]host-key-verify",
:description => "Verify host key, enabled by default.",
:boolean => true,
:default => true
option :hint,
:long => "--hint HINT_NAME[=HINT_FILE]",
:description => "Specify Ohai Hint to be set on the bootstrap target. Use multiple --hint options to specify multiple hints.",
:proc => Proc.new { |h|
Chef::Config[:knife][:hints] ||= Hash.new
name, path = h.split("=")
Chef::Config[:knife][:hints][name] = path ? JSON.parse(::File.read(path)) : Hash.new }
def find_template(template=nil)
# Are we bootstrapping using an already shipped template?
if config[:template_file]
bootstrap_files = config[:template_file]
else
bootstrap_files = []
bootstrap_files << File.join(File.dirname(__FILE__), 'bootstrap', "#{config[:distro]}.erb")
bootstrap_files << File.join(Knife.chef_config_dir, "bootstrap", "#{config[:distro]}.erb") if Knife.chef_config_dir
bootstrap_files << File.join(ENV['HOME'], '.chef', 'bootstrap', "#{config[:distro]}.erb") if ENV['HOME']
bootstrap_files << Gem.find_files(File.join("chef","knife","bootstrap","#{config[:distro]}.erb"))
bootstrap_files.flatten!
end
template = Array(bootstrap_files).find do |bootstrap_template|
Chef::Log.debug("Looking for bootstrap template in #{File.dirname(bootstrap_template)}")
File.exists?(bootstrap_template)
end
unless template
ui.info("Can not find bootstrap definition for #{config[:distro]}")
raise Errno::ENOENT
end
Chef::Log.debug("Found bootstrap template in #{File.dirname(template)}")
template
end
def render_template(template=nil)
context = Knife::Core::BootstrapContext.new(config, config[:run_list], Chef::Config)
Erubis::Eruby.new(template).evaluate(context)
end
def read_template
IO.read(@template_file).chomp
end
def run
validate_name_args!
@template_file = find_template(config[:bootstrap_template])
@node_name = Array(@name_args).first
# back compat--templates may use this setting:
config[:server_name] = @node_name
$stdout.sync = true
ui.info("Bootstrapping Chef on #{ui.color(@node_name, :bold)}")
begin
knife_ssh.run
rescue Net::SSH::AuthenticationFailed
unless config[:ssh_password]
ui.info("Failed to authenticate #{config[:ssh_user]} - trying password auth")
knife_ssh_with_password_auth.run
end
end
end
def validate_name_args!
if Array(@name_args).first.nil?
ui.error("Must pass an FQDN or ip to bootstrap")
exit 1
end
end
def server_name
Array(@name_args).first
end
def knife_ssh
ssh = Chef::Knife::Ssh.new
ssh.ui = ui
ssh.name_args = [ server_name, ssh_command ]
ssh.config[:ssh_user] = Chef::Config[:knife][:ssh_user] || config[:ssh_user]
ssh.config[:ssh_password] = config[:ssh_password]
ssh.config[:ssh_port] = Chef::Config[:knife][:ssh_port] || config[:ssh_port]
ssh.config[:ssh_gateway] = Chef::Config[:knife][:ssh_gateway] || config[:ssh_gateway]
ssh.config[:identity_file] = Chef::Config[:knife][:identity_file] || config[:identity_file]
ssh.config[:manual] = true
ssh.config[:host_key_verify] = Chef::Config[:knife][:host_key_verify] || config[:host_key_verify]
ssh.config[:on_error] = :raise
ssh
end
def knife_ssh_with_password_auth
ssh = knife_ssh
ssh.config[:identity_file] = nil
ssh.config[:ssh_password] = ssh.get_password
ssh
end
def ssh_command
command = render_template(read_template)
if config[:use_sudo]
command = config[:use_sudo_password] ? "echo #{config[:ssh_password]} | sudo -S #{command}" : "sudo #{command}"
end
command
end
end
end
end
|
require "knife/changelog/version"
require "berkshelf"
require 'chef/knife'
require 'mixlib/shellout'
class Chef
class Knife
class Changelog < Knife
banner 'knife changelog COOKBOOK [COOKBOOK ...]'
def initialize(options)
super
@tmp_prefix = 'knife-changelog'
@berksfile = Berkshelf::Berksfile.from_options({})
@tmp_dirs = []
end
option :linkify,
:short => '-l',
:long => '--linkify',
:description => 'add markdown links where relevant',
:boolean => true
option :ignore_changelog_file,
:long => '--ignore-changelog-file',
:description => "Ignore changelog file presence, use git history instead",
:boolean => true
def run
begin
if @name_args.empty?
cks = @berksfile.cookbooks.collect {|c| c.cookbook_name }
else
cks = @name_args
end
cks.each do |cookbook|
Log.debug "Checking changelog for #{cookbook}"
execute cookbook
end
ensure
clean
end
end
def clean
@tmp_dirs.each do |dir|
FileUtils.rm_r dir
end
end
def ck_dep(name)
@berksfile.lockfile.find(name)
end
def ck_location(name)
ck_dep(name).location
end
def version_for(name)
# FIXME uses public methods instead
@berksfile.lockfile.graph.instance_variable_get(:@graph)[name].version
end
def execute(name)
loc = ck_location(name)
changelog = case loc
when NilClass
handle_source name, ck_dep(name)
when Berkshelf::GitLocation
handle_git loc
when Berkshelf::PathLocation
Log.debug "path location are always at the last version"
""
else
raise "Cannot handle #{loc.class} yet"
end
print_changelog(name, changelog)
end
def print_changelog(name, changelog)
unless changelog.empty?
puts "--- Changelog for #{name} ---"
puts changelog
puts "-----------------"
end
end
def handle_source(name, dep)
ck = noauth_rest.get_rest("https://supermarket.getchef.com/api/v1/cookbooks/#{name}")
url = ck['source_url'] || ck ['external_url']
case url
when nil
fail "No external url for #{name}, can't find any changelog source"
when /github.com\/(.*)(.git)?/
options = {
:github => $1,
:revision => 'v' + version_for(name),
}
location = Berkshelf::GithubLocation.new dep, options
handle_git(location)
else
fail "External url #{url} points to unusable location!"
end
end
def handle_git(location)
tmp_dir = shallow_clone(@tmp_prefix,location.uri)
rev_parse = location.instance_variable_get(:@rev_parse)
cur_rev = location.revision.rstrip
ls_tree = Mixlib::ShellOut.new("git ls-tree -r #{rev_parse}", :cwd => tmp_dir)
ls_tree.run_command
changelog = ls_tree.stdout.lines.find { |line| line =~ /\s(changelog.*$)/i }
if changelog and not config[:ignore_changelog_file]
puts "Found changelog file : " + $1
generate_from_changelog_file($1, cur_rev, rev_parse, tmp_dir)
else
generate_from_git_history(tmp_dir, location, cur_rev, rev_parse)
end
end
def generate_from_changelog_file(filename, current_rev, rev_parse, tmp_dir)
diff = Mixlib::ShellOut.new("git diff #{current_rev}..#{rev_parse} -- #{filename}", :cwd => tmp_dir)
diff.run_command
diff.stdout.lines.collect {|line| $1 if line =~ /^\+([^+].*)/}.compact
end
def generate_from_git_history(tmp_dir, location, current_rev, rev_parse)
log = Mixlib::ShellOut.new("git log --no-merges --abbrev-commit --pretty=oneline #{current_rev}..#{rev_parse}", :cwd => tmp_dir)
log.run_command
c = log.stdout
n = https_url(location)
c = linkify(n, c) if config[:linkify] and n
c
end
def linkify(url, changelog)
changelog = changelog.lines.map { |line|
line.gsub(/^([a-f0-9]+) /, '[%s/commit/\1](\1) ' % [url])
}
end
def https_url(location)
if location.uri =~ /^\w+:\/\/(.*@)?(.*)(\.git?)/
"https://%s" % [ $2 ]
else
fail "Cannot guess http url from git remote url"
end
end
def short(location)
if location.uri =~ /([\w-]+)\/([\w-]+)(\.git)?$/
"%s/%s" % [$1,$2]
end
end
def shallow_clone(tmp_prefix, uri)
dir = Dir.mktmpdir(tmp_prefix)
@tmp_dirs << dir
clone = Mixlib::ShellOut.new("git clone --bare #{uri} bare-clone", :cwd => dir)
clone.run_command
::File.join(dir, 'bare-clone')
end
end
end
end
Handle all kind of empty urls
require "knife/changelog/version"
require "berkshelf"
require 'chef/knife'
require 'mixlib/shellout'
class Chef
class Knife
class Changelog < Knife
banner 'knife changelog COOKBOOK [COOKBOOK ...]'
def initialize(options)
super
@tmp_prefix = 'knife-changelog'
@berksfile = Berkshelf::Berksfile.from_options({})
@tmp_dirs = []
end
option :linkify,
:short => '-l',
:long => '--linkify',
:description => 'add markdown links where relevant',
:boolean => true
option :ignore_changelog_file,
:long => '--ignore-changelog-file',
:description => "Ignore changelog file presence, use git history instead",
:boolean => true
def run
begin
if @name_args.empty?
cks = @berksfile.cookbooks.collect {|c| c.cookbook_name }
else
cks = @name_args
end
cks.each do |cookbook|
Log.debug "Checking changelog for #{cookbook}"
execute cookbook
end
ensure
clean
end
end
def clean
@tmp_dirs.each do |dir|
FileUtils.rm_r dir
end
end
def ck_dep(name)
@berksfile.lockfile.find(name)
end
def ck_location(name)
ck_dep(name).location
end
def version_for(name)
# FIXME uses public methods instead
@berksfile.lockfile.graph.instance_variable_get(:@graph)[name].version
end
def execute(name)
loc = ck_location(name)
changelog = case loc
when NilClass
handle_source name, ck_dep(name)
when Berkshelf::GitLocation
handle_git loc
when Berkshelf::PathLocation
Log.debug "path location are always at the last version"
""
else
raise "Cannot handle #{loc.class} yet"
end
print_changelog(name, changelog)
end
def print_changelog(name, changelog)
unless changelog.empty?
puts "--- Changelog for #{name} ---"
puts changelog
puts "-----------------"
end
end
def handle_source(name, dep)
ck = noauth_rest.get_rest("https://supermarket.getchef.com/api/v1/cookbooks/#{name}")
url = ck['source_url'] || ck ['external_url']
case url.strip
when nil,""
fail "No external url for #{name}, can't find any changelog source"
when /github.com\/(.*)(.git)?/
options = {
:github => $1,
:revision => 'v' + version_for(name),
}
location = Berkshelf::GithubLocation.new dep, options
handle_git(location)
else
fail "External url #{url} points to unusable location!"
end
end
def handle_git(location)
tmp_dir = shallow_clone(@tmp_prefix,location.uri)
rev_parse = location.instance_variable_get(:@rev_parse)
cur_rev = location.revision.rstrip
ls_tree = Mixlib::ShellOut.new("git ls-tree -r #{rev_parse}", :cwd => tmp_dir)
ls_tree.run_command
changelog = ls_tree.stdout.lines.find { |line| line =~ /\s(changelog.*$)/i }
if changelog and not config[:ignore_changelog_file]
puts "Found changelog file : " + $1
generate_from_changelog_file($1, cur_rev, rev_parse, tmp_dir)
else
generate_from_git_history(tmp_dir, location, cur_rev, rev_parse)
end
end
def generate_from_changelog_file(filename, current_rev, rev_parse, tmp_dir)
diff = Mixlib::ShellOut.new("git diff #{current_rev}..#{rev_parse} -- #{filename}", :cwd => tmp_dir)
diff.run_command
diff.stdout.lines.collect {|line| $1 if line =~ /^\+([^+].*)/}.compact
end
def generate_from_git_history(tmp_dir, location, current_rev, rev_parse)
log = Mixlib::ShellOut.new("git log --no-merges --abbrev-commit --pretty=oneline #{current_rev}..#{rev_parse}", :cwd => tmp_dir)
log.run_command
c = log.stdout
n = https_url(location)
c = linkify(n, c) if config[:linkify] and n
c
end
def linkify(url, changelog)
changelog = changelog.lines.map { |line|
line.gsub(/^([a-f0-9]+) /, '[%s/commit/\1](\1) ' % [url])
}
end
def https_url(location)
if location.uri =~ /^\w+:\/\/(.*@)?(.*)(\.git?)/
"https://%s" % [ $2 ]
else
fail "Cannot guess http url from git remote url"
end
end
def short(location)
if location.uri =~ /([\w-]+)\/([\w-]+)(\.git)?$/
"%s/%s" % [$1,$2]
end
end
def shallow_clone(tmp_prefix, uri)
dir = Dir.mktmpdir(tmp_prefix)
@tmp_dirs << dir
clone = Mixlib::ShellOut.new("git clone --bare #{uri} bare-clone", :cwd => dir)
clone.run_command
::File.join(dir, 'bare-clone')
end
end
end
end
|
# Encoding: utf-8
require 'thor'
require 'rspec'
require 'rspec/retry'
require 'chemistrykit/cli/new'
require 'chemistrykit/cli/formula'
require 'chemistrykit/cli/beaker'
require 'chemistrykit/cli/helpers/formula_loader'
require 'chemistrykit/catalyst'
require 'chemistrykit/formula/base'
require 'chemistrykit/formula/formula_lab'
require 'chemistrykit/chemist/repository/csv_chemist_repository'
require 'selenium_connect'
require 'chemistrykit/configuration'
require 'chemistrykit/rspec/j_unit_formatter'
require 'chemistrykit/rspec/retry_formatter'
require 'rspec/core/formatters/html_formatter'
require 'chemistrykit/rspec/html_formatter'
require 'chemistrykit/reporting/html_report_assembler'
require 'chemistrykit/split_testing/provider_factory'
require 'allure-rspec'
require 'rubygems'
require 'logging'
require 'rspec/logging_helper'
require 'fileutils'
module ChemistryKit
module CLI
# Main Chemistry Kit CLI Class
class CKitCLI < Thor
register(ChemistryKit::CLI::New, 'new', 'new [NAME]', 'Creates a new ChemistryKit project')
check_unknown_options!
default_task :help
desc 'brew', 'Run ChemistryKit'
method_option :params, type: :hash
method_option :tag, type: :array
method_option :config, default: 'config.yaml', aliases: '-c', desc: 'Supply alternative config file.'
method_option :beakers, aliases: '-b', type: :array
method_option :retry, default: false, aliases: '-x', desc: 'How many times should a failing test be retried.'
method_option :all, default: false, aliases: '-a', desc: 'Run every beaker.', type: :boolean
def brew
config = load_config options['config']
# TODO: perhaps the params should be rolled into the available
# config object injected into the system?
pass_params if options['params']
# TODO: expand this to allow for more overrides as needed
config.retries_on_failure = options['retry'].to_i if options['retry']
load_page_objects
# get those beakers that should be executed
beakers = options['beakers'] ? options['beakers'] : Dir.glob(File.join(Dir.getwd, 'beakers/**/*')).select { |file| !File.directory?(file) }
# if tags are explicity defined, apply them to all beakers
setup_tags(options['tag'])
# configure rspec
rspec_config(config)
# based on concurrency parameter run tests
if config.concurrency > 1
exit_code = run_parallel beakers, config.concurrency
else
exit_code = run_rspec beakers
end
process_html
exit_code
end
protected
def process_html
results_folder = File.join(Dir.getwd, 'evidence')
output_file = File.join(Dir.getwd, 'evidence', 'final_results.html')
assembler = ChemistryKit::Reporting::HtmlReportAssembler.new(results_folder, output_file)
assembler.assemble
end
def pass_params
options['params'].each_pair do |key, value|
ENV[key] = value
end
end
def load_page_objects
loader = ChemistryKit::CLI::Helpers::FormulaLoader.new
loader.get_formulas(File.join(Dir.getwd, 'formulas')).each { |file| require file }
end
def load_config(file_name)
config_file = File.join(Dir.getwd, file_name)
ChemistryKit::Configuration.initialize_with_yaml config_file
end
def setup_tags(selected_tags)
@tags = {}
selected_tags.each do |tag|
filter_type = tag.start_with?('~') ? :exclusion_filter : :filter
name, value = tag.gsub(/^(~@|~|@)/, '').split(':')
name = name.to_sym
value = true if value.nil?
@tags[filter_type] ||= {}
@tags[filter_type][name] = value
end unless selected_tags.nil?
end
# rubocop:disable MethodLength
def rspec_config(config)
::AllureRSpec.configure do |c|
c.output_dir = "results"
end
::RSpec.configure do |c|
c.capture_log_messages
c.include AllureRSpec::Adaptor
c.treat_symbols_as_metadata_keys_with_true_values = true
unless options[:all]
c.filter_run @tags[:filter] unless @tags[:filter].nil?
c.filter_run_excluding @tags[:exclusion_filter] unless @tags[:exclusion_filter].nil?
end
c.before(:all) do
@config = config
ENV['BASE_URL'] = @config.base_url # assign base url to env variable for formulas
end
c.around(:each) do |example|
# create the beaker name from the example data
beaker_name = example.metadata[:example_group][:description_args].first.downcase.strip.gsub(' ', '_').gsub(/[^\w-]/, '')
test_name = example.metadata[:full_description].downcase.strip.gsub(' ', '_').gsub(/[^\w-]/, '')
# override log path with be beaker sub path
sc_config = @config.selenium_connect.dup
sc_config[:log] += "/#{beaker_name}"
beaker_path = File.join(Dir.getwd, sc_config[:log])
unless File.exists?(beaker_path)
Dir.mkdir beaker_path
end
sc_config[:log] += "/#{test_name}"
@test_path = File.join(Dir.getwd, sc_config[:log])
FileUtils.rm_rf(@test_path) if File.exists?(@test_path)
Dir.mkdir @test_path
# set the tags and permissions if sauce
if sc_config[:host] == 'saucelabs' || sc_config[:host] == 'appium'
tags = example.metadata.reject do |key, value|
[:example_group, :example_group_block, :description_args, :caller, :execution_result, :full_description].include? key
end
sauce_opts = {}
sauce_opts.merge!(public: tags.delete(:public)) if tags.key?(:public)
sauce_opts.merge!(tags: tags.map { |key, value| "#{key}:#{value}" }) unless tags.empty?
if sc_config[:sauce_opts]
sc_config[:sauce_opts].merge!(sauce_opts) unless sauce_opts.empty?
else
sc_config[:sauce_opts] = sauce_opts unless sauce_opts.empty?
end
end
# configure and start sc
configuration = SeleniumConnect::Configuration.new sc_config
@sc = SeleniumConnect.start configuration
@job = @sc.create_job # create a new job
@driver = @job.start name: test_name
# TODO: this is messy, and could be refactored out into a static on the lab
chemist_data_paths = Dir.glob(File.join(Dir.getwd, 'chemists', '*.csv'))
repo = ChemistryKit::Chemist::Repository::CsvChemistRepository.new chemist_data_paths
# make the formula lab available
@formula_lab = ChemistryKit::Formula::FormulaLab.new @driver, repo, File.join(Dir.getwd, 'formulas')
example.run
end
c.before(:each) do
if @config.basic_auth
@driver.get(@config.basic_auth.http_url) if @config.basic_auth.http?
@driver.get(@config.basic_auth.https_url) if @config.basic_auth.https?
end
if config.split_testing
ChemistryKit::SplitTesting::ProviderFactory.build(config.split_testing).split(@driver)
end
end
c.after(:each) do |x|
test_name = example.description.downcase.strip.gsub(' ', '_').gsub(/[^\w-]/, '')
if example.exception.nil? == false
@job.finish failed: true, failshot: @config.screenshot_on_fail
Dir[@job.get_evidence_folder+"/*"].each do |filename|
next if File.directory? filename
x.attach_file filename.split('/').last, File.new(filename)
end
else
@job.finish passed: true
end
@sc.finish
end
unless options[:all]
c.filter_run @tags[:filter] unless @tags[:filter].nil?
c.filter_run_excluding @tags[:exclusion_filter] unless @tags[:exclusion_filter].nil?
end
c.capture_log_messages
c.treat_symbols_as_metadata_keys_with_true_values = true
c.order = 'random'
c.output_stream = $stdout
# for rspec-retry
c.verbose_retry = true
c.default_retry_count = config.retries_on_failure
c.add_formatter 'progress'
c.add_formatter(ChemistryKit::RSpec::RetryFormatter)
html_log_name = "results.html"
Dir.glob(File.join(Dir.getwd, config.reporting.path, "results*")).each { |f| File.delete(f) }
c.add_formatter(ChemistryKit::RSpec::HtmlFormatter, File.join(Dir.getwd, config.reporting.path, html_log_name))
junit_log_name = "junit.xml"
Dir.glob(File.join(Dir.getwd, config.reporting.path, "junit*")).each { |f| File.delete(f) }
c.add_formatter(ChemistryKit::RSpec::JUnitFormatter, File.join(Dir.getwd, config.reporting.path, junit_log_name))
end
end
# rubocop:enable MethodLength
def run_parallel(beakers, concurrency)
require 'parallel_split_test/runner'
args = beakers + ['--parallel-test', concurrency.to_s]
::ParallelSplitTest::Runner.run(args)
end
def run_rspec(beakers)
::RSpec::Core::Runner.run(beakers)
end
end # CkitCLI
end # CLI
end # ChemistryKit
cli make beaker directory only if the directory doesn't exist
(change File.exists? to Dir.exist?)
# Encoding: utf-8
require 'thor'
require 'rspec'
require 'rspec/retry'
require 'chemistrykit/cli/new'
require 'chemistrykit/cli/formula'
require 'chemistrykit/cli/beaker'
require 'chemistrykit/cli/helpers/formula_loader'
require 'chemistrykit/catalyst'
require 'chemistrykit/formula/base'
require 'chemistrykit/formula/formula_lab'
require 'chemistrykit/chemist/repository/csv_chemist_repository'
require 'selenium_connect'
require 'chemistrykit/configuration'
require 'chemistrykit/rspec/j_unit_formatter'
require 'chemistrykit/rspec/retry_formatter'
require 'rspec/core/formatters/html_formatter'
require 'chemistrykit/rspec/html_formatter'
require 'chemistrykit/reporting/html_report_assembler'
require 'chemistrykit/split_testing/provider_factory'
require 'allure-rspec'
require 'rubygems'
require 'logging'
require 'rspec/logging_helper'
require 'fileutils'
module ChemistryKit
module CLI
# Main Chemistry Kit CLI Class
class CKitCLI < Thor
register(ChemistryKit::CLI::New, 'new', 'new [NAME]', 'Creates a new ChemistryKit project')
check_unknown_options!
default_task :help
desc 'brew', 'Run ChemistryKit'
method_option :params, type: :hash
method_option :tag, type: :array
method_option :config, default: 'config.yaml', aliases: '-c', desc: 'Supply alternative config file.'
method_option :beakers, aliases: '-b', type: :array
method_option :retry, default: false, aliases: '-x', desc: 'How many times should a failing test be retried.'
method_option :all, default: false, aliases: '-a', desc: 'Run every beaker.', type: :boolean
def brew
config = load_config options['config']
# TODO: perhaps the params should be rolled into the available
# config object injected into the system?
pass_params if options['params']
# TODO: expand this to allow for more overrides as needed
config.retries_on_failure = options['retry'].to_i if options['retry']
load_page_objects
# get those beakers that should be executed
beakers = options['beakers'] ? options['beakers'] : Dir.glob(File.join(Dir.getwd, 'beakers/**/*')).select { |file| !File.directory?(file) }
# if tags are explicity defined, apply them to all beakers
setup_tags(options['tag'])
# configure rspec
rspec_config(config)
# based on concurrency parameter run tests
if config.concurrency > 1
exit_code = run_parallel beakers, config.concurrency
else
exit_code = run_rspec beakers
end
process_html
exit_code
end
protected
def process_html
results_folder = File.join(Dir.getwd, 'evidence')
output_file = File.join(Dir.getwd, 'evidence', 'final_results.html')
assembler = ChemistryKit::Reporting::HtmlReportAssembler.new(results_folder, output_file)
assembler.assemble
end
def pass_params
options['params'].each_pair do |key, value|
ENV[key] = value
end
end
def load_page_objects
loader = ChemistryKit::CLI::Helpers::FormulaLoader.new
loader.get_formulas(File.join(Dir.getwd, 'formulas')).each { |file| require file }
end
def load_config(file_name)
config_file = File.join(Dir.getwd, file_name)
ChemistryKit::Configuration.initialize_with_yaml config_file
end
def setup_tags(selected_tags)
@tags = {}
selected_tags.each do |tag|
filter_type = tag.start_with?('~') ? :exclusion_filter : :filter
name, value = tag.gsub(/^(~@|~|@)/, '').split(':')
name = name.to_sym
value = true if value.nil?
@tags[filter_type] ||= {}
@tags[filter_type][name] = value
end unless selected_tags.nil?
end
# rubocop:disable MethodLength
def rspec_config(config)
::AllureRSpec.configure do |c|
c.output_dir = "results"
end
::RSpec.configure do |c|
c.capture_log_messages
c.include AllureRSpec::Adaptor
c.treat_symbols_as_metadata_keys_with_true_values = true
unless options[:all]
c.filter_run @tags[:filter] unless @tags[:filter].nil?
c.filter_run_excluding @tags[:exclusion_filter] unless @tags[:exclusion_filter].nil?
end
c.before(:all) do
@config = config
ENV['BASE_URL'] = @config.base_url # assign base url to env variable for formulas
end
c.around(:each) do |example|
# create the beaker name from the example data
beaker_name = example.metadata[:example_group][:description_args].first.downcase.strip.gsub(' ', '_').gsub(/[^\w-]/, '')
test_name = example.metadata[:full_description].downcase.strip.gsub(' ', '_').gsub(/[^\w-]/, '')
# override log path with be beaker sub path
sc_config = @config.selenium_connect.dup
sc_config[:log] += "/#{beaker_name}"
beaker_path = File.join(Dir.getwd, sc_config[:log])
Dir.mkdir beaker_path unless Dir.exist?(beaker_path)
sc_config[:log] += "/#{test_name}"
@test_path = File.join(Dir.getwd, sc_config[:log])
FileUtils.rm_rf(@test_path) if File.exists?(@test_path)
Dir.mkdir @test_path
# set the tags and permissions if sauce
if sc_config[:host] == 'saucelabs' || sc_config[:host] == 'appium'
tags = example.metadata.reject do |key, value|
[:example_group, :example_group_block, :description_args, :caller, :execution_result, :full_description].include? key
end
sauce_opts = {}
sauce_opts.merge!(public: tags.delete(:public)) if tags.key?(:public)
sauce_opts.merge!(tags: tags.map { |key, value| "#{key}:#{value}" }) unless tags.empty?
if sc_config[:sauce_opts]
sc_config[:sauce_opts].merge!(sauce_opts) unless sauce_opts.empty?
else
sc_config[:sauce_opts] = sauce_opts unless sauce_opts.empty?
end
end
# configure and start sc
configuration = SeleniumConnect::Configuration.new sc_config
@sc = SeleniumConnect.start configuration
@job = @sc.create_job # create a new job
@driver = @job.start name: test_name
# TODO: this is messy, and could be refactored out into a static on the lab
chemist_data_paths = Dir.glob(File.join(Dir.getwd, 'chemists', '*.csv'))
repo = ChemistryKit::Chemist::Repository::CsvChemistRepository.new chemist_data_paths
# make the formula lab available
@formula_lab = ChemistryKit::Formula::FormulaLab.new @driver, repo, File.join(Dir.getwd, 'formulas')
example.run
end
c.before(:each) do
if @config.basic_auth
@driver.get(@config.basic_auth.http_url) if @config.basic_auth.http?
@driver.get(@config.basic_auth.https_url) if @config.basic_auth.https?
end
if config.split_testing
ChemistryKit::SplitTesting::ProviderFactory.build(config.split_testing).split(@driver)
end
end
c.after(:each) do |x|
test_name = example.description.downcase.strip.gsub(' ', '_').gsub(/[^\w-]/, '')
if example.exception.nil? == false
@job.finish failed: true, failshot: @config.screenshot_on_fail
Dir[@job.get_evidence_folder+"/*"].each do |filename|
next if File.directory? filename
x.attach_file filename.split('/').last, File.new(filename)
end
else
@job.finish passed: true
end
@sc.finish
end
unless options[:all]
c.filter_run @tags[:filter] unless @tags[:filter].nil?
c.filter_run_excluding @tags[:exclusion_filter] unless @tags[:exclusion_filter].nil?
end
c.capture_log_messages
c.treat_symbols_as_metadata_keys_with_true_values = true
c.order = 'random'
c.output_stream = $stdout
# for rspec-retry
c.verbose_retry = true
c.default_retry_count = config.retries_on_failure
c.add_formatter 'progress'
c.add_formatter(ChemistryKit::RSpec::RetryFormatter)
html_log_name = "results.html"
Dir.glob(File.join(Dir.getwd, config.reporting.path, "results*")).each { |f| File.delete(f) }
c.add_formatter(ChemistryKit::RSpec::HtmlFormatter, File.join(Dir.getwd, config.reporting.path, html_log_name))
junit_log_name = "junit.xml"
Dir.glob(File.join(Dir.getwd, config.reporting.path, "junit*")).each { |f| File.delete(f) }
c.add_formatter(ChemistryKit::RSpec::JUnitFormatter, File.join(Dir.getwd, config.reporting.path, junit_log_name))
end
end
# rubocop:enable MethodLength
def run_parallel(beakers, concurrency)
require 'parallel_split_test/runner'
args = beakers + ['--parallel-test', concurrency.to_s]
::ParallelSplitTest::Runner.run(args)
end
def run_rspec(beakers)
::RSpec::Core::Runner.run(beakers)
end
end # CkitCLI
end # CLI
end # ChemistryKit
|
module Chitchat
module Client
class Chat
attr_accessor :chat_id
attr_accessor :status
attr_accessor :messages
class << self
# GET /chats/:id
def find(id)
response = Chitchat::Client.connection.get("/chats/#{id}.json")
return nil unless response.status == 200 && response.headers['content-type'] == "application/json" && response[:chat]
chat = response[:chat]
status = chat[:status]
messages = chat[:messages]
end
end
def initialize
end
# PUT /chats/:id/answer
def answer
end
# PUT /chats/:id/hang_up
def hang_up
end
# POST /calls/:id/messages?from=[user_id]&body=[text]
def send_message(from_id, body)
end
end
end
end
More class stuff.
module Chitchat
module Client
class Chat
attr_accessor :chat_id
attr_accessor :status
attr_accessor :messages
class << self
# GET /chats/:id
def find(id)
response = Chitchat::Client.connection.get("/chats/#{id}.json")
return nil unless response.status == 200 && response.headers['content-type'] == "application/json" && response[:chat]
chat = response[:chat]
Chitchat::Client.new(chat[:chat_id], chat[:status], chat[:messages])
end
# POST /chats?from=[my_user_id]&to=[their_user_id]
def create(from_user_id, to_user_id)
response = Chitchat::Client.connection.post("/chats.json", {:from => from_user_id, :to => to_user_id})
end
end
def initialize(chat_id, status, messages=[])
@chat_id = chat_id
@status = status
@messages = messages
self
end
# PUT /chats/:id/answer
def answer
end
# PUT /chats/:id/hang_up
def hang_up
end
# POST /calls/:id/messages?from=[user_id]&body=[text]
def send_message(from_id, body)
response = Chitchat::Client.connection.post("/calls/#{chat_id}", {:from => from_id, :body => body})
end
private
def
end
end
end
|
require 'active_record'
require 'active_record/connection_adapters/postgresql_adapter'
module ChronoModel
# This class implements all ActiveRecord::ConnectionAdapters::SchemaStatements
# methods adding support for temporal extensions. It inherits from the Postgres
# adapter for a clean override of its methods using super.
#
class Adapter < ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
# The schema holding current data
TEMPORAL_SCHEMA = 'temporal'
# The schema holding historical data
HISTORY_SCHEMA = 'history'
# Chronomodel is supported starting with PostgreSQL >= 9.0
#
def chrono_supported?
postgresql_version >= 90000
end
# Creates the given table, possibly creating the temporal schema
# objects if the `:temporal` option is given and set to true.
#
def create_table(table_name, options = {})
# No temporal features requested, skip
return super unless options[:temporal]
if options[:id] == false
logger.warn "WARNING - Temporal Temporal tables require a primary key."
logger.warn "WARNING - Creating a \"__chrono_id\" primary key to fulfill the requirement"
options[:id] = '__chrono_id'
end
# Create required schemas
chrono_create_schemas!
transaction do
_on_temporal_schema { super }
_on_history_schema { chrono_create_history_for(table_name) }
chrono_create_view_for(table_name)
TableCache.add! table_name
end
end
# If renaming a temporal table, rename the history and view as well.
#
def rename_table(name, new_name)
return super unless is_chrono?(name)
clear_cache!
transaction do
[TEMPORAL_SCHEMA, HISTORY_SCHEMA].each do |schema|
on_schema(schema) do
seq = serial_sequence(name, primary_key(name))
new_seq = seq.sub(name.to_s, new_name.to_s).split('.').last
execute "ALTER SEQUENCE #{seq} RENAME TO #{new_seq}"
execute "ALTER TABLE #{name} RENAME TO #{new_name}"
end
end
execute "ALTER VIEW #{name} RENAME TO #{new_name}"
TableCache.del! name
TableCache.add! new_name
end
end
# If changing a temporal table, redirect the change to the table in the
# temporal schema and recreate views.
#
# If the `:temporal` option is specified, enables or disables temporal
# features on the given table. Please note that you'll lose your history
# when demoting a temporal table to a plain one.
#
def change_table(table_name, options = {}, &block)
transaction do
# Add an empty proc to support calling change_table without a block.
#
block ||= proc { }
if options[:temporal] == true
if !is_chrono?(table_name)
# Add temporal features to this table
#
if !primary_key(table_name)
execute "ALTER TABLE #{table_name} ADD __chrono_id SERIAL PRIMARY KEY"
end
execute "ALTER TABLE #{table_name} SET SCHEMA #{TEMPORAL_SCHEMA}"
_on_history_schema { chrono_create_history_for(table_name) }
chrono_create_view_for(table_name)
TableCache.add! table_name
# Optionally copy the plain table data, setting up history
# retroactively.
#
if options[:copy_data]
seq = _on_history_schema { serial_sequence(table_name, primary_key(table_name)) }
from = options[:validity] || '0001-01-01 00:00:00'
execute %[
INSERT INTO #{HISTORY_SCHEMA}.#{table_name}
SELECT *,
nextval('#{seq}') AS hid,
timestamp '#{from}' AS valid_from,
timestamp '9999-12-31 00:00:00' AS valid_to,
timezone('UTC', now()) AS recorded_at
FROM #{TEMPORAL_SCHEMA}.#{table_name}
]
end
end
chrono_alter(table_name) { super table_name, options, &block }
else
if options[:temporal] == false && is_chrono?(table_name)
# Remove temporal features from this table
#
execute "DROP VIEW #{table_name}"
_on_history_schema { execute "DROP TABLE #{table_name}" }
default_schema = select_value 'SELECT current_schema()'
_on_temporal_schema do
if primary_key(table_name) == '__chrono_id'
execute "ALTER TABLE #{table_name} DROP __chrono_id"
end
execute "ALTER TABLE #{table_name} SET SCHEMA #{default_schema}"
end
TableCache.del! table_name
end
super table_name, options, &block
end
end
end
# If dropping a temporal table, drops it from the temporal schema
# adding the CASCADE option so to delete the history, view and rules.
#
def drop_table(table_name, *)
return super unless is_chrono?(table_name)
_on_temporal_schema { execute "DROP TABLE #{table_name} CASCADE" }
TableCache.del! table_name
end
# If adding an index to a temporal table, add it to the one in the
# temporal schema and to the history one. If the `:unique` option is
# present, it is removed from the index created in the history table.
#
def add_index(table_name, column_name, options = {})
return super unless is_chrono?(table_name)
transaction do
_on_temporal_schema { super }
# Uniqueness constraints do not make sense in the history table
options = options.dup.tap {|o| o.delete(:unique)} if options[:unique].present?
_on_history_schema { super table_name, column_name, options }
end
end
# If removing an index from a temporal table, remove it both from the
# temporal and the history schemas.
#
def remove_index(table_name, *)
return super unless is_chrono?(table_name)
transaction do
_on_temporal_schema { super }
_on_history_schema { super }
end
end
# If adding a column to a temporal table, creates it in the table in
# the temporal schema and updates the view rules.
#
def add_column(table_name, *)
return super unless is_chrono?(table_name)
transaction do
# Add the column to the temporal table
_on_temporal_schema { super }
# Update the rules
chrono_create_view_for(table_name)
end
end
# If renaming a column of a temporal table, rename it in the table in
# the temporal schema and update the view rules.
#
def rename_column(table_name, *)
return super unless is_chrono?(table_name)
# Rename the column in the temporal table and in the view
transaction do
_on_temporal_schema { super }
super
# Update the rules
chrono_create_view_for(table_name)
end
end
# If removing a column from a temporal table, we are forced to drop the
# view, then change the column from the table in the temporal schema and
# eventually recreate the rules.
#
def change_column(table_name, *)
return super unless is_chrono?(table_name)
chrono_alter(table_name) { super }
end
# Change the default on the temporal schema table.
#
def change_column_default(table_name, *)
return super unless is_chrono?(table_name)
_on_temporal_schema { super }
end
# Change the null constraint on the temporal schema table.
#
def change_column_null(table_name, *)
return super unless is_chrono?(table_name)
_on_temporal_schema { super }
end
# If removing a column from a temporal table, we are forced to drop the
# view, then drop the column from the table in the temporal schema and
# eventually recreate the rules.
#
def remove_column(table_name, *)
return super unless is_chrono?(table_name)
chrono_alter(table_name) { super }
end
# Runs column_definitions, primary_key and indexes in the temporal schema,
# as the table there defined is the source for this information.
#
# Moreover, the PostgreSQLAdapter +indexes+ method uses current_schema(),
# thus this is the only (and cleanest) way to make injection work.
#
# Schema nesting is disabled on these calls, make sure to fetch metadata
# from the first caller's selected schema and not from the current one.
#
[:column_definitions, :primary_key, :indexes].each do |method|
define_method(method) do |table_name|
return super(table_name) unless is_chrono?(table_name)
_on_temporal_schema(false) { super(table_name) }
end
end
# Evaluates the given block in the given +schema+ search path.
#
# By default, nested call are allowed, to disable this feature
# pass +false+ as the second parameter.
#
def on_schema(schema, nesting = true, &block)
@_on_schema_nesting = (@_on_schema_nesting || 0) + 1
if nesting || @_on_schema_nesting == 1
old_path = self.schema_search_path
self.schema_search_path = schema
end
block.call
ensure
if (nesting || @_on_schema_nesting == 1)
# If the transaction is aborted, any execute() call will raise
# "transaction is aborted errors" - thus calling the Adapter's
# setter won't update the memoized variable.
#
# Here we reset it to +nil+ to refresh it on the next call, as
# there is no way to know which path will be restored when the
# transaction ends.
#
if @connection.transaction_status == PGconn::PQTRANS_INERROR
@schema_search_path = nil
else
self.schema_search_path = old_path
end
end
@_on_schema_nesting -= 1
end
TableCache = (Class.new(HashWithIndifferentAccess) do
def all ; keys; ; end
def add! table ; self[table] = true ; end
def del! table ; self[table] = nil ; end
def fetch table ; self[table] ||= yield ; end
end).new
# Returns true if the given name references a temporal table.
#
def is_chrono?(table)
TableCache.fetch(table) do
_on_temporal_schema { table_exists?(table) } &&
_on_history_schema { table_exists?(table) }
end
end
def chrono_create_schemas!
[TEMPORAL_SCHEMA, HISTORY_SCHEMA].each do |schema|
execute "CREATE SCHEMA #{schema}" unless schema_exists?(schema)
end
end
# Disable savepoints support, as they break history keeping.
# http://archives.postgresql.org/pgsql-hackers/2012-08/msg01094.php
#
def supports_savepoints?
false
end
def create_savepoint; end
def rollback_to_savepoint; end
def release_savepoint; end
private
# Create the history table in the history schema
def chrono_create_history_for(table)
parent = "#{TEMPORAL_SCHEMA}.#{table}"
p_pkey = primary_key(parent)
execute <<-SQL
CREATE TABLE #{table} (
hid SERIAL PRIMARY KEY,
valid_from timestamp NOT NULL,
valid_to timestamp NOT NULL DEFAULT '9999-12-31',
recorded_at timestamp NOT NULL DEFAULT timezone('UTC', now()),
CONSTRAINT #{table}_from_before_to CHECK (valid_from < valid_to),
CONSTRAINT #{table}_overlapping_times EXCLUDE USING gist (
box(
point( date_part( 'epoch', valid_from), #{p_pkey} ),
point( date_part( 'epoch', valid_to - INTERVAL '1 millisecond'), #{p_pkey} )
) with &&
)
) INHERITS ( #{parent} )
SQL
# Inherited primary key
execute "CREATE INDEX #{table}_inherit_pkey ON #{table} ( #{p_pkey} )"
chrono_create_history_indexes_for(table, p_pkey)
end
def chrono_create_history_indexes_for(table, p_pkey = nil)
# Duplicate because of Migrate.upgrade_indexes_for
# TODO remove me.
p_pkey ||= primary_key("#{TEMPORAL_SCHEMA}.#{table}")
# Create spatial indexes for timestamp search. Conceptually identical
# to the above EXCLUDE constraint but without the millisecond removal.
#
# This index is used by TimeMachine.at to built the temporal WHERE
# clauses that fetch the state of the records at a single point in
# history.
#
execute <<-SQL
CREATE INDEX #{table}_snapshot ON #{table} USING gist (
box(
point( date_part( 'epoch', valid_from ), 0 ),
point( date_part( 'epoch', valid_to ), 0 )
)
)
SQL
# History sorting
#
execute "CREATE INDEX #{table}_recorded_at ON #{table} ( recorded_at )"
execute "CREATE INDEX #{table}_instance_history ON #{table} ( #{p_pkey}, recorded_at )"
end
# Create the public view and its rewrite rules
#
def chrono_create_view_for(table)
pk = primary_key(table)
current = [TEMPORAL_SCHEMA, table].join('.')
history = [HISTORY_SCHEMA, table].join('.')
# SELECT - return only current data
#
execute "DROP VIEW #{table}" if table_exists? table
execute "CREATE VIEW #{table} AS SELECT *, xmin AS __xid FROM ONLY #{current}"
columns = columns(table).map{|c| quote_column_name(c.name)}
columns.delete(quote_column_name(pk))
sequence = serial_sequence(current, pk) # For INSERT
updates = columns.map {|c| "#{c} = new.#{c}"}.join(",\n") # For UPDATE
fields, values = columns.join(', '), columns.map {|c| "new.#{c}"}.join(', ')
# INSERT - insert data both in the temporal table and in the history one.
#
# A separate sequence is used to keep the primary keys in the history
# in sync with the temporal table, instead of using currval(), because
# when using INSERT INTO .. SELECT, currval() returns the value of the
# last inserted row - while nextval() gets expanded by the rule system
# for each row to be inserted. Ref: GH Issue #4.
#
if sequence.present?
history_sequence = sequence.sub(TEMPORAL_SCHEMA, HISTORY_SCHEMA)
execute "DROP SEQUENCE IF EXISTS #{history_sequence}"
c, i = query("SELECT last_value, increment_by FROM #{sequence}").first
execute "CREATE SEQUENCE #{history_sequence} START WITH #{c} INCREMENT BY #{i}"
execute <<-SQL
CREATE RULE #{table}_ins AS ON INSERT TO #{table} DO INSTEAD (
INSERT INTO #{current} ( #{fields} ) VALUES ( #{values} );
INSERT INTO #{history} ( #{pk}, #{fields}, valid_from )
VALUES ( nextval('#{history_sequence}'), #{values}, timezone('UTC', now()) )
RETURNING #{pk}, #{fields}, xmin
)
SQL
else
fields_with_pk = "#{pk}, " << fields
values_with_pk = "new.#{pk}, " << values
execute <<-SQL
CREATE RULE #{table}_ins AS ON INSERT TO #{table} DO INSTEAD (
INSERT INTO #{current} ( #{fields_with_pk} ) VALUES ( #{values_with_pk} );
INSERT INTO #{history} ( #{fields_with_pk}, valid_from )
VALUES ( #{values_with_pk}, timezone('UTC', now()) )
RETURNING #{fields_with_pk}, xmin
)
SQL
end
# UPDATE - set the last history entry validity to now, save the current data
# in a new history entry and update the temporal table with the new data.
# If this is the first statement of a transaction, inferred by the last
# transaction ID that updated the row, create a new row in the history.
#
# The current transaction ID is returned by txid_current() as a 64-bit
# signed integer, while the last transaction ID that changed a row is
# stored into a 32-bit unsigned integer in the __xid column. As XIDs
# wrap over time, txid_current() adds an "epoch" counter in the most
# significant bits (http://bit.ly/W2Srt7) of the int - thus here we
# remove it by and'ing with 2^32-1.
#
# XID are 32-bit unsigned integers, and by design cannot be casted nor
# compared to anything else, adding a CAST or an operator requires
# super-user privileges, so here we do a double-cast from varchar to
# int8, to finally compare it with the current XID. We're using 64bit
# integers as in PG there is no 32-bit unsigned data type.
#
execute <<-SQL
CREATE RULE #{table}_upd_first AS ON UPDATE TO #{table}
WHERE old.__xid::char(10)::int8 <> (txid_current() & (2^32-1)::int8)
DO INSTEAD (
UPDATE #{history} SET valid_to = timezone('UTC', now())
WHERE #{pk} = old.#{pk} AND valid_to = '9999-12-31';
INSERT INTO #{history} ( #{pk}, #{fields}, valid_from )
VALUES ( old.#{pk}, #{values}, timezone('UTC', now()) );
UPDATE ONLY #{current} SET #{updates}
WHERE #{pk} = old.#{pk}
)
SQL
# Else, update the already present history row with new data. This logic
# makes possible to "squash" together changes made in a transaction in a
# single history row, assuring timestamps consistency.
#
execute <<-SQL
CREATE RULE #{table}_upd_next AS ON UPDATE TO #{table} DO INSTEAD (
UPDATE #{history} SET #{updates}
WHERE #{pk} = old.#{pk} AND valid_from = timezone('UTC', now());
UPDATE ONLY #{current} SET #{updates}
WHERE #{pk} = old.#{pk}
)
SQL
# DELETE - save the current data in the history and eventually delete the
# data from the temporal table.
# The first DELETE is required to remove history for records INSERTed and
# DELETEd in the same transaction.
#
execute <<-SQL
CREATE RULE #{table}_del AS ON DELETE TO #{table} DO INSTEAD (
DELETE FROM #{history}
WHERE #{pk} = old.#{pk}
AND valid_from = timezone('UTC', now())
AND valid_to = '9999-12-31';
UPDATE #{history} SET valid_to = timezone('UTC', now())
WHERE #{pk} = old.#{pk} AND valid_to = '9999-12-31';
DELETE FROM ONLY #{current}
WHERE #{current}.#{pk} = old.#{pk}
)
SQL
end
# In destructive changes, such as removing columns or changing column
# types, the view must be dropped and recreated, while the change has
# to be applied to the table in the temporal schema.
#
def chrono_alter(table_name)
transaction do
execute "DROP VIEW #{table_name}"
_on_temporal_schema { yield }
# Recreate the rules
chrono_create_view_for(table_name)
end
end
def _on_temporal_schema(nesting = true, &block)
on_schema(TEMPORAL_SCHEMA, nesting, &block)
end
def _on_history_schema(nesting = true, &block)
on_schema(HISTORY_SCHEMA, nesting, &block)
end
end
end
Reintroduce TS indexes to optimize history rules
require 'active_record'
require 'active_record/connection_adapters/postgresql_adapter'
module ChronoModel
# This class implements all ActiveRecord::ConnectionAdapters::SchemaStatements
# methods adding support for temporal extensions. It inherits from the Postgres
# adapter for a clean override of its methods using super.
#
class Adapter < ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
# The schema holding current data
TEMPORAL_SCHEMA = 'temporal'
# The schema holding historical data
HISTORY_SCHEMA = 'history'
# Chronomodel is supported starting with PostgreSQL >= 9.0
#
def chrono_supported?
postgresql_version >= 90000
end
# Creates the given table, possibly creating the temporal schema
# objects if the `:temporal` option is given and set to true.
#
def create_table(table_name, options = {})
# No temporal features requested, skip
return super unless options[:temporal]
if options[:id] == false
logger.warn "WARNING - Temporal Temporal tables require a primary key."
logger.warn "WARNING - Creating a \"__chrono_id\" primary key to fulfill the requirement"
options[:id] = '__chrono_id'
end
# Create required schemas
chrono_create_schemas!
transaction do
_on_temporal_schema { super }
_on_history_schema { chrono_create_history_for(table_name) }
chrono_create_view_for(table_name)
TableCache.add! table_name
end
end
# If renaming a temporal table, rename the history and view as well.
#
def rename_table(name, new_name)
return super unless is_chrono?(name)
clear_cache!
transaction do
[TEMPORAL_SCHEMA, HISTORY_SCHEMA].each do |schema|
on_schema(schema) do
seq = serial_sequence(name, primary_key(name))
new_seq = seq.sub(name.to_s, new_name.to_s).split('.').last
execute "ALTER SEQUENCE #{seq} RENAME TO #{new_seq}"
execute "ALTER TABLE #{name} RENAME TO #{new_name}"
end
end
execute "ALTER VIEW #{name} RENAME TO #{new_name}"
TableCache.del! name
TableCache.add! new_name
end
end
# If changing a temporal table, redirect the change to the table in the
# temporal schema and recreate views.
#
# If the `:temporal` option is specified, enables or disables temporal
# features on the given table. Please note that you'll lose your history
# when demoting a temporal table to a plain one.
#
def change_table(table_name, options = {}, &block)
transaction do
# Add an empty proc to support calling change_table without a block.
#
block ||= proc { }
if options[:temporal] == true
if !is_chrono?(table_name)
# Add temporal features to this table
#
if !primary_key(table_name)
execute "ALTER TABLE #{table_name} ADD __chrono_id SERIAL PRIMARY KEY"
end
execute "ALTER TABLE #{table_name} SET SCHEMA #{TEMPORAL_SCHEMA}"
_on_history_schema { chrono_create_history_for(table_name) }
chrono_create_view_for(table_name)
TableCache.add! table_name
# Optionally copy the plain table data, setting up history
# retroactively.
#
if options[:copy_data]
seq = _on_history_schema { serial_sequence(table_name, primary_key(table_name)) }
from = options[:validity] || '0001-01-01 00:00:00'
execute %[
INSERT INTO #{HISTORY_SCHEMA}.#{table_name}
SELECT *,
nextval('#{seq}') AS hid,
timestamp '#{from}' AS valid_from,
timestamp '9999-12-31 00:00:00' AS valid_to,
timezone('UTC', now()) AS recorded_at
FROM #{TEMPORAL_SCHEMA}.#{table_name}
]
end
end
chrono_alter(table_name) { super table_name, options, &block }
else
if options[:temporal] == false && is_chrono?(table_name)
# Remove temporal features from this table
#
execute "DROP VIEW #{table_name}"
_on_history_schema { execute "DROP TABLE #{table_name}" }
default_schema = select_value 'SELECT current_schema()'
_on_temporal_schema do
if primary_key(table_name) == '__chrono_id'
execute "ALTER TABLE #{table_name} DROP __chrono_id"
end
execute "ALTER TABLE #{table_name} SET SCHEMA #{default_schema}"
end
TableCache.del! table_name
end
super table_name, options, &block
end
end
end
# If dropping a temporal table, drops it from the temporal schema
# adding the CASCADE option so to delete the history, view and rules.
#
def drop_table(table_name, *)
return super unless is_chrono?(table_name)
_on_temporal_schema { execute "DROP TABLE #{table_name} CASCADE" }
TableCache.del! table_name
end
# If adding an index to a temporal table, add it to the one in the
# temporal schema and to the history one. If the `:unique` option is
# present, it is removed from the index created in the history table.
#
def add_index(table_name, column_name, options = {})
return super unless is_chrono?(table_name)
transaction do
_on_temporal_schema { super }
# Uniqueness constraints do not make sense in the history table
options = options.dup.tap {|o| o.delete(:unique)} if options[:unique].present?
_on_history_schema { super table_name, column_name, options }
end
end
# If removing an index from a temporal table, remove it both from the
# temporal and the history schemas.
#
def remove_index(table_name, *)
return super unless is_chrono?(table_name)
transaction do
_on_temporal_schema { super }
_on_history_schema { super }
end
end
# If adding a column to a temporal table, creates it in the table in
# the temporal schema and updates the view rules.
#
def add_column(table_name, *)
return super unless is_chrono?(table_name)
transaction do
# Add the column to the temporal table
_on_temporal_schema { super }
# Update the rules
chrono_create_view_for(table_name)
end
end
# If renaming a column of a temporal table, rename it in the table in
# the temporal schema and update the view rules.
#
def rename_column(table_name, *)
return super unless is_chrono?(table_name)
# Rename the column in the temporal table and in the view
transaction do
_on_temporal_schema { super }
super
# Update the rules
chrono_create_view_for(table_name)
end
end
# If removing a column from a temporal table, we are forced to drop the
# view, then change the column from the table in the temporal schema and
# eventually recreate the rules.
#
def change_column(table_name, *)
return super unless is_chrono?(table_name)
chrono_alter(table_name) { super }
end
# Change the default on the temporal schema table.
#
def change_column_default(table_name, *)
return super unless is_chrono?(table_name)
_on_temporal_schema { super }
end
# Change the null constraint on the temporal schema table.
#
def change_column_null(table_name, *)
return super unless is_chrono?(table_name)
_on_temporal_schema { super }
end
# If removing a column from a temporal table, we are forced to drop the
# view, then drop the column from the table in the temporal schema and
# eventually recreate the rules.
#
def remove_column(table_name, *)
return super unless is_chrono?(table_name)
chrono_alter(table_name) { super }
end
# Runs column_definitions, primary_key and indexes in the temporal schema,
# as the table there defined is the source for this information.
#
# Moreover, the PostgreSQLAdapter +indexes+ method uses current_schema(),
# thus this is the only (and cleanest) way to make injection work.
#
# Schema nesting is disabled on these calls, make sure to fetch metadata
# from the first caller's selected schema and not from the current one.
#
[:column_definitions, :primary_key, :indexes].each do |method|
define_method(method) do |table_name|
return super(table_name) unless is_chrono?(table_name)
_on_temporal_schema(false) { super(table_name) }
end
end
# Evaluates the given block in the given +schema+ search path.
#
# By default, nested call are allowed, to disable this feature
# pass +false+ as the second parameter.
#
def on_schema(schema, nesting = true, &block)
@_on_schema_nesting = (@_on_schema_nesting || 0) + 1
if nesting || @_on_schema_nesting == 1
old_path = self.schema_search_path
self.schema_search_path = schema
end
block.call
ensure
if (nesting || @_on_schema_nesting == 1)
# If the transaction is aborted, any execute() call will raise
# "transaction is aborted errors" - thus calling the Adapter's
# setter won't update the memoized variable.
#
# Here we reset it to +nil+ to refresh it on the next call, as
# there is no way to know which path will be restored when the
# transaction ends.
#
if @connection.transaction_status == PGconn::PQTRANS_INERROR
@schema_search_path = nil
else
self.schema_search_path = old_path
end
end
@_on_schema_nesting -= 1
end
TableCache = (Class.new(HashWithIndifferentAccess) do
def all ; keys; ; end
def add! table ; self[table] = true ; end
def del! table ; self[table] = nil ; end
def fetch table ; self[table] ||= yield ; end
end).new
# Returns true if the given name references a temporal table.
#
def is_chrono?(table)
TableCache.fetch(table) do
_on_temporal_schema { table_exists?(table) } &&
_on_history_schema { table_exists?(table) }
end
end
def chrono_create_schemas!
[TEMPORAL_SCHEMA, HISTORY_SCHEMA].each do |schema|
execute "CREATE SCHEMA #{schema}" unless schema_exists?(schema)
end
end
# Disable savepoints support, as they break history keeping.
# http://archives.postgresql.org/pgsql-hackers/2012-08/msg01094.php
#
def supports_savepoints?
false
end
def create_savepoint; end
def rollback_to_savepoint; end
def release_savepoint; end
private
# Create the history table in the history schema
def chrono_create_history_for(table)
parent = "#{TEMPORAL_SCHEMA}.#{table}"
p_pkey = primary_key(parent)
execute <<-SQL
CREATE TABLE #{table} (
hid SERIAL PRIMARY KEY,
valid_from timestamp NOT NULL,
valid_to timestamp NOT NULL DEFAULT '9999-12-31',
recorded_at timestamp NOT NULL DEFAULT timezone('UTC', now()),
CONSTRAINT #{table}_from_before_to CHECK (valid_from < valid_to),
CONSTRAINT #{table}_overlapping_times EXCLUDE USING gist (
box(
point( date_part( 'epoch', valid_from), #{p_pkey} ),
point( date_part( 'epoch', valid_to - INTERVAL '1 millisecond'), #{p_pkey} )
) with &&
)
) INHERITS ( #{parent} )
SQL
# Inherited primary key
execute "CREATE INDEX #{table}_inherit_pkey ON #{table} ( #{p_pkey} )"
chrono_create_history_indexes_for(table, p_pkey)
end
def chrono_create_history_indexes_for(table, p_pkey = nil)
# Duplicate because of Migrate.upgrade_indexes_for
# TODO remove me.
p_pkey ||= primary_key("#{TEMPORAL_SCHEMA}.#{table}")
# Create spatial indexes for timestamp search. Conceptually identical
# to the above EXCLUDE constraint but without the millisecond removal.
#
# This index is used by TimeMachine.at to built the temporal WHERE
# clauses that fetch the state of the records at a single point in
# history.
#
execute <<-SQL
CREATE INDEX #{table}_snapshot ON #{table} USING gist (
box(
point( date_part( 'epoch', valid_from ), 0 ),
point( date_part( 'epoch', valid_to ), 0 )
)
)
SQL
# History sorting and update / delete rules
#
execute "CREATE INDEX #{table}_valid_from ON #{table} ( valid_from )"
execute "CREATE INDEX #{table}_valid_to ON #{table} ( valid_to )"
execute "CREATE INDEX #{table}_recorded_at ON #{table} ( recorded_at )"
execute "CREATE INDEX #{table}_instance_history ON #{table} ( #{p_pkey}, recorded_at )"
end
# Create the public view and its rewrite rules
#
def chrono_create_view_for(table)
pk = primary_key(table)
current = [TEMPORAL_SCHEMA, table].join('.')
history = [HISTORY_SCHEMA, table].join('.')
# SELECT - return only current data
#
execute "DROP VIEW #{table}" if table_exists? table
execute "CREATE VIEW #{table} AS SELECT *, xmin AS __xid FROM ONLY #{current}"
columns = columns(table).map{|c| quote_column_name(c.name)}
columns.delete(quote_column_name(pk))
sequence = serial_sequence(current, pk) # For INSERT
updates = columns.map {|c| "#{c} = new.#{c}"}.join(",\n") # For UPDATE
fields, values = columns.join(', '), columns.map {|c| "new.#{c}"}.join(', ')
# INSERT - insert data both in the temporal table and in the history one.
#
# A separate sequence is used to keep the primary keys in the history
# in sync with the temporal table, instead of using currval(), because
# when using INSERT INTO .. SELECT, currval() returns the value of the
# last inserted row - while nextval() gets expanded by the rule system
# for each row to be inserted. Ref: GH Issue #4.
#
if sequence.present?
history_sequence = sequence.sub(TEMPORAL_SCHEMA, HISTORY_SCHEMA)
execute "DROP SEQUENCE IF EXISTS #{history_sequence}"
c, i = query("SELECT last_value, increment_by FROM #{sequence}").first
execute "CREATE SEQUENCE #{history_sequence} START WITH #{c} INCREMENT BY #{i}"
execute <<-SQL
CREATE RULE #{table}_ins AS ON INSERT TO #{table} DO INSTEAD (
INSERT INTO #{current} ( #{fields} ) VALUES ( #{values} );
INSERT INTO #{history} ( #{pk}, #{fields}, valid_from )
VALUES ( nextval('#{history_sequence}'), #{values}, timezone('UTC', now()) )
RETURNING #{pk}, #{fields}, xmin
)
SQL
else
fields_with_pk = "#{pk}, " << fields
values_with_pk = "new.#{pk}, " << values
execute <<-SQL
CREATE RULE #{table}_ins AS ON INSERT TO #{table} DO INSTEAD (
INSERT INTO #{current} ( #{fields_with_pk} ) VALUES ( #{values_with_pk} );
INSERT INTO #{history} ( #{fields_with_pk}, valid_from )
VALUES ( #{values_with_pk}, timezone('UTC', now()) )
RETURNING #{fields_with_pk}, xmin
)
SQL
end
# UPDATE - set the last history entry validity to now, save the current data
# in a new history entry and update the temporal table with the new data.
# If this is the first statement of a transaction, inferred by the last
# transaction ID that updated the row, create a new row in the history.
#
# The current transaction ID is returned by txid_current() as a 64-bit
# signed integer, while the last transaction ID that changed a row is
# stored into a 32-bit unsigned integer in the __xid column. As XIDs
# wrap over time, txid_current() adds an "epoch" counter in the most
# significant bits (http://bit.ly/W2Srt7) of the int - thus here we
# remove it by and'ing with 2^32-1.
#
# XID are 32-bit unsigned integers, and by design cannot be casted nor
# compared to anything else, adding a CAST or an operator requires
# super-user privileges, so here we do a double-cast from varchar to
# int8, to finally compare it with the current XID. We're using 64bit
# integers as in PG there is no 32-bit unsigned data type.
#
execute <<-SQL
CREATE RULE #{table}_upd_first AS ON UPDATE TO #{table}
WHERE old.__xid::char(10)::int8 <> (txid_current() & (2^32-1)::int8)
DO INSTEAD (
UPDATE #{history} SET valid_to = timezone('UTC', now())
WHERE #{pk} = old.#{pk} AND valid_to = '9999-12-31';
INSERT INTO #{history} ( #{pk}, #{fields}, valid_from )
VALUES ( old.#{pk}, #{values}, timezone('UTC', now()) );
UPDATE ONLY #{current} SET #{updates}
WHERE #{pk} = old.#{pk}
)
SQL
# Else, update the already present history row with new data. This logic
# makes possible to "squash" together changes made in a transaction in a
# single history row, assuring timestamps consistency.
#
execute <<-SQL
CREATE RULE #{table}_upd_next AS ON UPDATE TO #{table} DO INSTEAD (
UPDATE #{history} SET #{updates}
WHERE #{pk} = old.#{pk} AND valid_from = timezone('UTC', now());
UPDATE ONLY #{current} SET #{updates}
WHERE #{pk} = old.#{pk}
)
SQL
# DELETE - save the current data in the history and eventually delete the
# data from the temporal table.
# The first DELETE is required to remove history for records INSERTed and
# DELETEd in the same transaction.
#
execute <<-SQL
CREATE RULE #{table}_del AS ON DELETE TO #{table} DO INSTEAD (
DELETE FROM #{history}
WHERE #{pk} = old.#{pk}
AND valid_from = timezone('UTC', now())
AND valid_to = '9999-12-31';
UPDATE #{history} SET valid_to = timezone('UTC', now())
WHERE #{pk} = old.#{pk} AND valid_to = '9999-12-31';
DELETE FROM ONLY #{current}
WHERE #{current}.#{pk} = old.#{pk}
)
SQL
end
# In destructive changes, such as removing columns or changing column
# types, the view must be dropped and recreated, while the change has
# to be applied to the table in the temporal schema.
#
def chrono_alter(table_name)
transaction do
execute "DROP VIEW #{table_name}"
_on_temporal_schema { yield }
# Recreate the rules
chrono_create_view_for(table_name)
end
end
def _on_temporal_schema(nesting = true, &block)
on_schema(TEMPORAL_SCHEMA, nesting, &block)
end
def _on_history_schema(nesting = true, &block)
on_schema(HISTORY_SCHEMA, nesting, &block)
end
end
end
|
require 'circuit_breaker-ruby/version'
require 'timeout'
class CircuitBreaker
class Open < StandardError; end
include Version
FAILURE_THRESHOLD = 10
FAILURE_THRESHOLD_PERCENTAGE = 0.5
INVOCATION_TIMEOUT = 10
RETRY_TIMEOUT = 60
module States
OPEN = :open
CLOSED = :closed
HALF_OPEN = :half_open
end
attr_reader :invocation_timeout, :failure_threshold, :failure_threshold_percentage, :total_count, :failure_count
def initialize(**options)
@failure_count = 0
@total_count = 0
@failure_threshold = options[:failure_threshold] || FAILURE_THRESHOLD
@failure_threshold_percentage = options[:failure_threshold_percentage] || FAILURE_THRESHOLD_PERCENTAGE
@invocation_timeout = options[:invocation_timeout] || TIMEOUT
@retry_timeout = options[:retry_timeout] || RETRY_TIMEOUT
end
def call(&block)
case prev_state = state
when States::CLOSED, States::HALF_OPEN
connect(&block)
update_total_count(prev_state)
when States::OPEN
raise Open
end
end
private
def state
case
when reached_failure_threshold? && reached_retry_timeout?
States::HALF_OPEN
when reached_failure_threshold?
States::OPEN
else
States::CLOSED
end
end
def reached_failure_threshold?
(failure_count >= failure_threshold) &&
(total_count != 0 &&
(failure_count.to_f / total_count.to_f) >= failure_threshold_percentage)
end
def reached_retry_timeout?
(Time.now - @last_failure_time) > @retry_timeout
end
def reset
@failure_count = 0
@state = States::CLOSED
end
def connect(&block)
begin
Timeout::timeout(invocation_timeout) do
block.call
end
reset
rescue Timeout::Error => e
record_failure
end
end
def update_total_count(state)
if state == States::HALF_OPEN
@total_count = 0
else
@total_count += 1
end
end
def record_failure
@last_failure_time = Time.now
@failure_count += 1
end
end
Fix constant name in CircuitBreaker#initialize
require 'circuit_breaker-ruby/version'
require 'timeout'
class CircuitBreaker
class Open < StandardError; end
include Version
FAILURE_THRESHOLD = 10
FAILURE_THRESHOLD_PERCENTAGE = 0.5
INVOCATION_TIMEOUT = 10
RETRY_TIMEOUT = 60
module States
OPEN = :open
CLOSED = :closed
HALF_OPEN = :half_open
end
attr_reader :invocation_timeout, :failure_threshold, :failure_threshold_percentage, :total_count, :failure_count
def initialize(**options)
@failure_count = 0
@total_count = 0
@failure_threshold = options[:failure_threshold] || FAILURE_THRESHOLD
@failure_threshold_percentage = options[:failure_threshold_percentage] || FAILURE_THRESHOLD_PERCENTAGE
@invocation_timeout = options[:invocation_timeout] || INVOCATION_TIMEOUT
@retry_timeout = options[:retry_timeout] || RETRY_TIMEOUT
end
def call(&block)
case prev_state = state
when States::CLOSED, States::HALF_OPEN
connect(&block)
update_total_count(prev_state)
when States::OPEN
raise Open
end
end
private
def state
case
when reached_failure_threshold? && reached_retry_timeout?
States::HALF_OPEN
when reached_failure_threshold?
States::OPEN
else
States::CLOSED
end
end
def reached_failure_threshold?
(failure_count >= failure_threshold) &&
(total_count != 0 &&
(failure_count.to_f / total_count.to_f) >= failure_threshold_percentage)
end
def reached_retry_timeout?
(Time.now - @last_failure_time) > @retry_timeout
end
def reset
@failure_count = 0
@state = States::CLOSED
end
def connect(&block)
begin
Timeout::timeout(invocation_timeout) do
block.call
end
reset
rescue Timeout::Error => e
record_failure
end
end
def update_total_count(state)
if state == States::HALF_OPEN
@total_count = 0
else
@total_count += 1
end
end
def record_failure
@last_failure_time = Time.now
@failure_count += 1
end
end
|
require 'ruby_vim_sdk'
require 'cloud/vsphere/cloud_searcher'
require 'cloud/vsphere/soap_stub'
module VSphereCloud
class Client
include VimSdk
class AlreadyLoggedInException < StandardError; end
class NotLoggedInException < StandardError; end
attr_reader :cloud_searcher, :service_content, :service_instance, :soap_stub
def initialize(host, options={})
@soap_stub = SoapStub.new(host, options[:soap_log]).create
@service_instance =Vim::ServiceInstance.new('ServiceInstance', @soap_stub)
@service_content = @service_instance.content
@metrics_cache = {}
@lock = Mutex.new
@logger = Bosh::Clouds::Config.logger
@cloud_searcher = CloudSearcher.new(service_content, @logger)
end
def login(username, password, locale)
raise AlreadyLoggedInException if @session
@session = @service_content.session_manager.login(username, password, locale)
end
def logout
raise NotLoggedInException unless @session
@session = nil
@service_content.session_manager.logout
end
def find_parent(obj, parent_type)
while obj && obj.class != parent_type
obj = @cloud_searcher.get_property(obj, obj.class, "parent", :ensure_all => true)
end
obj
end
def reconfig_vm(vm, config)
task = vm.reconfigure(config)
wait_for_task(task)
end
def delete_vm(vm)
task = vm.destroy
wait_for_task(task)
end
def answer_vm(vm, question, answer)
vm.answer(question, answer)
end
def power_on_vm(datacenter, vm)
task = datacenter.power_on_vm([vm], nil)
result = wait_for_task(task)
raise 'Recommendations were detected, you may be running in Manual DRS mode. Aborting.' if result.recommendations.any?
if result.attempted.empty?
raise "Could not power on VM: #{result.not_attempted.map(&:msg).join(', ')}"
else
task = result.attempted.first.task
wait_for_task(task)
end
end
def power_off_vm(vm_mob)
task = vm_mob.power_off
wait_for_task(task)
end
def get_cdrom_device(vm)
devices = @cloud_searcher.get_property(vm, Vim::VirtualMachine, 'config.hardware.device', ensure_all: true)
devices.find { |device| device.kind_of?(Vim::Vm::Device::VirtualCdrom) }
end
def delete_path(datacenter, path)
task = @service_content.file_manager.delete_file(path, datacenter)
begin
wait_for_task(task)
rescue => e
unless e.message =~ /File .* was not found/
raise e
end
end
end
def delete_disk(datacenter, path)
base_path = path.chomp(File.extname(path))
[".vmdk", "-flat.vmdk"].each do |extension|
delete_path(datacenter, "#{base_path}#{extension}")
end
end
def move_disk(source_datacenter, source_path, dest_datacenter, dest_path)
tasks = []
base_source_path = source_path.chomp(File.extname(source_path))
base_dest_path = source_path.chomp(File.extname(dest_path))
[".vmdk", "-flat.vmdk"].each do |extension|
tasks << @service_content.file_manager.move_file(
"#{base_source_path}#{extension}", source_datacenter,
"#{base_dest_path}#{extension}", dest_datacenter, false
)
end
tasks.each { |task| wait_for_task(task) }
end
def create_datastore_folder(folder_path, datacenter)
@service_content.file_manager.make_directory(folder_path, datacenter, true)
end
def create_folder(name)
@service_content.root_folder.create_folder(name)
end
def move_into_folder(folder, objects)
task = folder.move_into(objects)
wait_for_task(task)
end
def move_into_root_folder(objects)
task = @service_content.root_folder.move_into(objects)
wait_for_task(task)
end
def delete_folder(folder)
task = folder.destroy
wait_for_task(task)
end
def find_by_inventory_path(path)
full_path = Array(path).join("/")
@service_content.search_index.find_by_inventory_path(full_path)
end
def wait_for_task(task)
interval = 1.0
started = Time.now
loop do
properties = @cloud_searcher.get_properties(
[task],
Vim::Task,
["info.progress", "info.state", "info.result", "info.error"],
ensure: ["info.state"]
)[task]
duration = Time.now - started
raise "Task taking too long" if duration > 3600 # 1 hour
# Update the polling interval based on task progress
if properties["info.progress"] && properties["info.progress"] > 0
interval = ((duration * 100 / properties["info.progress"]) - duration) / 5
if interval < 1
interval = 1
elsif interval > 10
interval = 10
elsif interval > duration
interval = duration
end
end
case properties["info.state"]
when Vim::TaskInfo::State::RUNNING
sleep(interval)
when Vim::TaskInfo::State::QUEUED
sleep(interval)
when Vim::TaskInfo::State::SUCCESS
return properties["info.result"]
when Vim::TaskInfo::State::ERROR
raise properties["info.error"].msg
end
end
end
def get_perf_counters(mobs, names, options = {})
metrics = find_perf_metric_names(mobs.first, names)
metric_ids = metrics.values
metric_name_by_id = {}
metrics.each { |name, metric| metric_name_by_id[metric.counter_id] = name }
queries = []
mobs.each do |mob|
queries << Vim::PerformanceManager::QuerySpec.new(
:entity => mob,
:metric_id => metric_ids,
:format => Vim::PerformanceManager::Format::CSV,
:interval_id => options[:interval_id] || 20,
:max_sample => options[:max_sample])
end
query_perf_response = @service_content.perf_manager.query_stats(queries)
result = {}
query_perf_response.each do |mob_stats|
mob_entry = {}
counters = mob_stats.value
counters.each do |counter_stats|
counter_id = counter_stats.id.counter_id
values = counter_stats.value
mob_entry[metric_name_by_id[counter_id]] = values
end
result[mob_stats.entity] = mob_entry
end
result
end
def find_disk(disk_cid, datastore, disk_folder)
disk_path = "[#{datastore.name}] #{disk_folder}/#{disk_cid}.vmdk"
disk_size_in_mb = find_disk_size_using_browser(datastore, disk_cid, disk_folder)
disk_size_in_mb.nil? ? nil : Resources::Disk.new(disk_cid, disk_size_in_mb, datastore, disk_path)
end
private
def find_disk_size_using_browser(datastore, disk_cid, disk_folder)
search_spec_details = VimSdk::Vim::Host::DatastoreBrowser::FileInfo::Details.new
search_spec_details.file_type = true # actually return VmDiskInfos not FileInfos
query_details = VimSdk::Vim::Host::DatastoreBrowser::VmDiskQuery::Details.new
query_details.capacity_kb = true
query = VimSdk::Vim::Host::DatastoreBrowser::VmDiskQuery.new
query.details = query_details
search_spec = VimSdk::Vim::Host::DatastoreBrowser::SearchSpec.new
search_spec.details = search_spec_details
search_spec.match_pattern = ["#{disk_cid}.vmdk"]
search_spec.query = [query]
vm_disk_infos = wait_for_task(datastore.mob.browser.search("[#{datastore.name}] #{disk_folder}", search_spec)).file
return nil if vm_disk_infos.empty?
vm_disk_infos.first.capacity_kb / 1024
rescue VimSdk::SoapError
nil
end
def find_perf_metric_names(mob, names)
@lock.synchronize do
unless @metrics_cache.has_key?(mob.class)
@metrics_cache[mob.class] = fetch_perf_metric_names(mob)
end
end
result = {}
@metrics_cache[mob.class].each do |name, metric|
result[name] = metric if names.include?(name)
end
result
end
def fetch_perf_metric_names(mob)
metrics = @service_content.perf_manager.query_available_metric(mob, nil, nil, 300)
metric_ids = metrics.collect { |metric| metric.counter_id }
metric_names = {}
metrics_info = @service_content.perf_manager.query_counter(metric_ids)
metrics_info.each do |perf_counter_info|
name = "#{perf_counter_info.group_info.key}.#{perf_counter_info.name_info.key}.#{perf_counter_info.rollup_type}"
metric_names[perf_counter_info.key] = name
end
result = {}
metrics.each { |metric| result[metric_names[metric.counter_id]] = metric }
result
end
end
end
VSphereClient can optionally have its logger specified
Signed-off-by: Kihyeon Kim <3900da17246426210a3d6fd6e4d6195079876ae8@gmail.com>
require 'ruby_vim_sdk'
require 'cloud/vsphere/cloud_searcher'
require 'cloud/vsphere/soap_stub'
module VSphereCloud
class Client
include VimSdk
class AlreadyLoggedInException < StandardError; end
class NotLoggedInException < StandardError; end
attr_reader :cloud_searcher, :service_content, :service_instance, :soap_stub
def initialize(host, options={})
@soap_stub = SoapStub.new(host, options[:soap_log]).create
@service_instance =Vim::ServiceInstance.new('ServiceInstance', @soap_stub)
@service_content = @service_instance.content
@metrics_cache = {}
@lock = Mutex.new
@logger = options.fetch(:logger) { Bosh::Clouds::Config.logger }
@cloud_searcher = CloudSearcher.new(service_content, @logger)
end
def login(username, password, locale)
raise AlreadyLoggedInException if @session
@session = @service_content.session_manager.login(username, password, locale)
end
def logout
raise NotLoggedInException unless @session
@session = nil
@service_content.session_manager.logout
end
def find_parent(obj, parent_type)
while obj && obj.class != parent_type
obj = @cloud_searcher.get_property(obj, obj.class, "parent", :ensure_all => true)
end
obj
end
def reconfig_vm(vm, config)
task = vm.reconfigure(config)
wait_for_task(task)
end
def delete_vm(vm)
task = vm.destroy
wait_for_task(task)
end
def answer_vm(vm, question, answer)
vm.answer(question, answer)
end
def power_on_vm(datacenter, vm)
task = datacenter.power_on_vm([vm], nil)
result = wait_for_task(task)
raise 'Recommendations were detected, you may be running in Manual DRS mode. Aborting.' if result.recommendations.any?
if result.attempted.empty?
raise "Could not power on VM: #{result.not_attempted.map(&:msg).join(', ')}"
else
task = result.attempted.first.task
wait_for_task(task)
end
end
def power_off_vm(vm_mob)
task = vm_mob.power_off
wait_for_task(task)
end
def get_cdrom_device(vm)
devices = @cloud_searcher.get_property(vm, Vim::VirtualMachine, 'config.hardware.device', ensure_all: true)
devices.find { |device| device.kind_of?(Vim::Vm::Device::VirtualCdrom) }
end
def delete_path(datacenter, path)
task = @service_content.file_manager.delete_file(path, datacenter)
begin
wait_for_task(task)
rescue => e
unless e.message =~ /File .* was not found/
raise e
end
end
end
def delete_disk(datacenter, path)
base_path = path.chomp(File.extname(path))
[".vmdk", "-flat.vmdk"].each do |extension|
delete_path(datacenter, "#{base_path}#{extension}")
end
end
def move_disk(source_datacenter, source_path, dest_datacenter, dest_path)
tasks = []
base_source_path = source_path.chomp(File.extname(source_path))
base_dest_path = source_path.chomp(File.extname(dest_path))
[".vmdk", "-flat.vmdk"].each do |extension|
tasks << @service_content.file_manager.move_file(
"#{base_source_path}#{extension}", source_datacenter,
"#{base_dest_path}#{extension}", dest_datacenter, false
)
end
tasks.each { |task| wait_for_task(task) }
end
def create_datastore_folder(folder_path, datacenter)
@service_content.file_manager.make_directory(folder_path, datacenter, true)
end
def create_folder(name)
@service_content.root_folder.create_folder(name)
end
def move_into_folder(folder, objects)
task = folder.move_into(objects)
wait_for_task(task)
end
def move_into_root_folder(objects)
task = @service_content.root_folder.move_into(objects)
wait_for_task(task)
end
def delete_folder(folder)
task = folder.destroy
wait_for_task(task)
end
def find_by_inventory_path(path)
full_path = Array(path).join("/")
@service_content.search_index.find_by_inventory_path(full_path)
end
def wait_for_task(task)
interval = 1.0
started = Time.now
loop do
properties = @cloud_searcher.get_properties(
[task],
Vim::Task,
["info.progress", "info.state", "info.result", "info.error"],
ensure: ["info.state"]
)[task]
duration = Time.now - started
raise "Task taking too long" if duration > 3600 # 1 hour
# Update the polling interval based on task progress
if properties["info.progress"] && properties["info.progress"] > 0
interval = ((duration * 100 / properties["info.progress"]) - duration) / 5
if interval < 1
interval = 1
elsif interval > 10
interval = 10
elsif interval > duration
interval = duration
end
end
case properties["info.state"]
when Vim::TaskInfo::State::RUNNING
sleep(interval)
when Vim::TaskInfo::State::QUEUED
sleep(interval)
when Vim::TaskInfo::State::SUCCESS
return properties["info.result"]
when Vim::TaskInfo::State::ERROR
raise properties["info.error"].msg
end
end
end
def get_perf_counters(mobs, names, options = {})
metrics = find_perf_metric_names(mobs.first, names)
metric_ids = metrics.values
metric_name_by_id = {}
metrics.each { |name, metric| metric_name_by_id[metric.counter_id] = name }
queries = []
mobs.each do |mob|
queries << Vim::PerformanceManager::QuerySpec.new(
:entity => mob,
:metric_id => metric_ids,
:format => Vim::PerformanceManager::Format::CSV,
:interval_id => options[:interval_id] || 20,
:max_sample => options[:max_sample])
end
query_perf_response = @service_content.perf_manager.query_stats(queries)
result = {}
query_perf_response.each do |mob_stats|
mob_entry = {}
counters = mob_stats.value
counters.each do |counter_stats|
counter_id = counter_stats.id.counter_id
values = counter_stats.value
mob_entry[metric_name_by_id[counter_id]] = values
end
result[mob_stats.entity] = mob_entry
end
result
end
def find_disk(disk_cid, datastore, disk_folder)
disk_path = "[#{datastore.name}] #{disk_folder}/#{disk_cid}.vmdk"
disk_size_in_mb = find_disk_size_using_browser(datastore, disk_cid, disk_folder)
disk_size_in_mb.nil? ? nil : Resources::Disk.new(disk_cid, disk_size_in_mb, datastore, disk_path)
end
private
def find_disk_size_using_browser(datastore, disk_cid, disk_folder)
search_spec_details = VimSdk::Vim::Host::DatastoreBrowser::FileInfo::Details.new
search_spec_details.file_type = true # actually return VmDiskInfos not FileInfos
query_details = VimSdk::Vim::Host::DatastoreBrowser::VmDiskQuery::Details.new
query_details.capacity_kb = true
query = VimSdk::Vim::Host::DatastoreBrowser::VmDiskQuery.new
query.details = query_details
search_spec = VimSdk::Vim::Host::DatastoreBrowser::SearchSpec.new
search_spec.details = search_spec_details
search_spec.match_pattern = ["#{disk_cid}.vmdk"]
search_spec.query = [query]
vm_disk_infos = wait_for_task(datastore.mob.browser.search("[#{datastore.name}] #{disk_folder}", search_spec)).file
return nil if vm_disk_infos.empty?
vm_disk_infos.first.capacity_kb / 1024
rescue VimSdk::SoapError
nil
end
def find_perf_metric_names(mob, names)
@lock.synchronize do
unless @metrics_cache.has_key?(mob.class)
@metrics_cache[mob.class] = fetch_perf_metric_names(mob)
end
end
result = {}
@metrics_cache[mob.class].each do |name, metric|
result[name] = metric if names.include?(name)
end
result
end
def fetch_perf_metric_names(mob)
metrics = @service_content.perf_manager.query_available_metric(mob, nil, nil, 300)
metric_ids = metrics.collect { |metric| metric.counter_id }
metric_names = {}
metrics_info = @service_content.perf_manager.query_counter(metric_ids)
metrics_info.each do |perf_counter_info|
name = "#{perf_counter_info.group_info.key}.#{perf_counter_info.name_info.key}.#{perf_counter_info.rollup_type}"
metric_names[perf_counter_info.key] = name
end
result = {}
metrics.each { |metric| result[metric_names[metric.counter_id]] = metric }
result
end
end
end
|
class CloudScrape
VERSION = "0.1.2"
end
Bump version again
class CloudScrape
VERSION = "0.1.3"
end
|
#encoding: utf-8
#main CommandExec
module CommandExec
# version of the library
VERSION = '0.1.3'
end
version bump to
#main CommandExec
module CommandExec
VERSION = ''
end |
require 'test_helper'
class RespectTest < Test::Unit::TestCase
def test_schema_name_for
[
[ "foo", "Respect::FooSchema" ],
[ "foo_bar", "Respect::FooBarSchema" ],
[ "equal_to", "Respect::EqualToSchema", "regular" ],
[ "a_b", "Respect::ABSchema", "two single letter menmonics" ],
[ "a_b_", "Respect::ABSchema", "trailing underscore" ],
[ "_a_b", "Respect::ABSchema", "leading underscore" ],
[ "schema", "Respect::Schema", "special 'schema' case" ],
[ :schema, "Respect::Schema", "special 'schema' case (symbol)" ],
[ :string, "Respect::StringSchema", "string schema" ],
[ :any, "Respect::AnySchema", "any schema" ],
[ :circle, "Respect::CircleSchema", "user defined schema" ],
[ :does_not_exist, "Respect::DoesNotExistSchema", "undefined schema" ],
[ :request, "Respect::RequestSchema", "well named class but not a candidate" ],
].each do |data|
assert_equal data[1], Respect.schema_name_for(data[0]), data[2]
end
end
def test_schema_name_for_invalid_statement_names_raise_error
assert_raises(ArgumentError) do
Respect.schema_name_for("[]=")
end
end
def test_schema_for
{
# root schema
schema: nil,
# internal schema definition
string: Respect::StringSchema,
integer: Respect::IntegerSchema,
numeric: Respect::NumericSchema,
float: Respect::FloatSchema,
any: Respect::AnySchema,
uri: Respect::URISchema,
# user defined schema definition in support/respect
circle: Respect::CircleSchema,
point: Respect::PointSchema,
rgba: Respect::RgbaSchema,
# valid class but with no statement
request: nil, # not a Schema sub-class
composite: nil, # abstract
undefined_schema: nil, # undefined
}.each do |statement, schema_class|
klass = nil
assert_nothing_raised("nothing raised for '#{statement}'") do
klass = Respect.schema_for(statement)
end
assert_equal schema_class, klass, "correct class for '#{statement}'"
end
end
def test_schema_defined_for
assert_equal true, Respect.schema_defined_for?("string")
assert_equal false, Respect.schema_defined_for?("request"), "not a schema"
assert_equal false, Respect.schema_defined_for?("composite"), "abstract"
assert_equal false, Respect.schema_defined_for?("schema"), "root"
assert_equal false, Respect.schema_defined_for?("undefined"), "undefined"
assert_equal true, Respect.schema_defined_for?("hash"), "hash"
assert_equal false, Respect.schema_defined_for?("object"), "object"
end
def test_validator_name_for
[
[ "equal_to", "Respect::EqualToValidator", "regular" ],
[ "a_b", "Respect::ABValidator", "two single letter menmonics" ],
[ "a_b_", "Respect::ABValidator", "trailing underscore" ],
[ "_a_b", "Respect::ABValidator", "leading underscore" ],
].each do |data|
assert_equal data[1], Respect.validator_name_for(data[0]), data[2]
end
end
def test_validator_for
{
equal_to: Respect::EqualToValidator,
format: Respect::FormatValidator,
greater_than_or_equal_to: Respect::GreaterThanOrEqualToValidator,
undefined_validator: nil # undefined
}.each do |constraint, validator_class|
klass = nil
assert_nothing_raised("nothing raised for '#{constraint}'") do
klass = Respect.validator_for(constraint)
end
assert_equal validator_class, klass, "correct class for '#{constraint}'"
end
end
def test_validator_defined_for
assert Respect.validator_defined_for?(:equal_to)
assert Respect.validator_defined_for?(:format)
assert Respect.validator_defined_for?(:greater_than_or_equal_to)
assert !Respect.validator_defined_for?(:undefined_validator)
end
end
Test #schema_for calls #schema_name_for.
require 'test_helper'
class RespectTest < Test::Unit::TestCase
def test_schema_name_for
[
[ "foo", "Respect::FooSchema" ],
[ "foo_bar", "Respect::FooBarSchema" ],
[ "equal_to", "Respect::EqualToSchema", "regular" ],
[ "a_b", "Respect::ABSchema", "two single letter menmonics" ],
[ "a_b_", "Respect::ABSchema", "trailing underscore" ],
[ "_a_b", "Respect::ABSchema", "leading underscore" ],
[ "schema", "Respect::Schema", "special 'schema' case" ],
[ :schema, "Respect::Schema", "special 'schema' case (symbol)" ],
[ :string, "Respect::StringSchema", "string schema" ],
[ :any, "Respect::AnySchema", "any schema" ],
[ :circle, "Respect::CircleSchema", "user defined schema" ],
[ :does_not_exist, "Respect::DoesNotExistSchema", "undefined schema" ],
[ :request, "Respect::RequestSchema", "well named class but not a candidate" ],
].each do |data|
assert_equal data[1], Respect.schema_name_for(data[0]), data[2]
end
end
def test_schema_name_for_invalid_statement_names_raise_error
assert_raises(ArgumentError) do
Respect.schema_name_for("[]=")
end
end
def test_schema_for
{
# root schema
schema: nil,
# internal schema definition
string: Respect::StringSchema,
integer: Respect::IntegerSchema,
numeric: Respect::NumericSchema,
float: Respect::FloatSchema,
any: Respect::AnySchema,
uri: Respect::URISchema,
# user defined schema definition in support/respect
circle: Respect::CircleSchema,
point: Respect::PointSchema,
rgba: Respect::RgbaSchema,
# valid class but with no statement
request: nil, # not a Schema sub-class
composite: nil, # abstract
undefined_schema: nil, # undefined
}.each do |statement, schema_class|
klass = nil
assert_nothing_raised("nothing raised for '#{statement}'") do
klass = Respect.schema_for(statement)
end
assert_equal schema_class, klass, "correct class for '#{statement}'"
end
end
def test_schema_for_calls_schema_name_for
statement_name = "string"
schema_name = "Respect::StringSchema"
Respect.expects(:schema_name_for).with(statement_name).returns(schema_name).once
assert_equal Respect::StringSchema, Respect.schema_for(statement_name)
end
def test_schema_defined_for
assert_equal true, Respect.schema_defined_for?("string")
assert_equal false, Respect.schema_defined_for?("request"), "not a schema"
assert_equal false, Respect.schema_defined_for?("composite"), "abstract"
assert_equal false, Respect.schema_defined_for?("schema"), "root"
assert_equal false, Respect.schema_defined_for?("undefined"), "undefined"
assert_equal true, Respect.schema_defined_for?("hash"), "hash"
assert_equal false, Respect.schema_defined_for?("object"), "object"
end
def test_validator_name_for
[
[ "equal_to", "Respect::EqualToValidator", "regular" ],
[ "a_b", "Respect::ABValidator", "two single letter menmonics" ],
[ "a_b_", "Respect::ABValidator", "trailing underscore" ],
[ "_a_b", "Respect::ABValidator", "leading underscore" ],
].each do |data|
assert_equal data[1], Respect.validator_name_for(data[0]), data[2]
end
end
def test_validator_for
{
equal_to: Respect::EqualToValidator,
format: Respect::FormatValidator,
greater_than_or_equal_to: Respect::GreaterThanOrEqualToValidator,
undefined_validator: nil # undefined
}.each do |constraint, validator_class|
klass = nil
assert_nothing_raised("nothing raised for '#{constraint}'") do
klass = Respect.validator_for(constraint)
end
assert_equal validator_class, klass, "correct class for '#{constraint}'"
end
end
def test_validator_defined_for
assert Respect.validator_defined_for?(:equal_to)
assert Respect.validator_defined_for?(:format)
assert Respect.validator_defined_for?(:greater_than_or_equal_to)
assert !Respect.validator_defined_for?(:undefined_validator)
end
end
|
module CommonMarker
VERSION = '0.14.4'.freeze
end
:gem: bump to 0.14.5
module CommonMarker
VERSION = '0.14.5'.freeze
end
|
module Condensation
VERSION = "1.0.4"
end
Version 1.0.5 [ci skip]
module Condensation
VERSION = "1.0.5"
end
|
module Constellation
#
# Constellation::Config is used for evaluating the ConstellationFile
#
class Config
def initialize
# Includes each file, that should be watched by Constellation
# Insert a file in this list by using Config.watch
@watched_files = []
# Default values for the data store
@data_store = DataStore.new
end
# Adds a new log file to the watched files list, that gets observer for changes.
#
# Example usage: watch "logs._txt"
#
def watch(file_name)
raise LogFileNotFoundError unless File::exists?(file_name)
raise LogFileAlreadyIncluded if @watched_files.include?(file_name)
@watched_files << file_name
end
# Used as wrapper for several configuration options used for setting up the data store
#
# Example usage: data_store.host = :localhost
# data_store.username = :admin
# data_store.password = "secret"
# data_store.keyspace = :constellation
#
def data_store
@data_store
end
end
end
Reformatted documentation
module Constellation
#
# Constellation::Config is used for evaluating the ConstellationFile
#
class Config
def initialize
# Includes each file, that should be watched by Constellation
# Insert a file in this list by using Config.watch
@watched_files = []
# Default values for the data store
@data_store = DataStore.new
end
# Adds a new log file to the watched files list, that gets observer for changes.
#
# Example usage:
# watch "logs.txt"
#
def watch(file_name)
raise LogFileNotFoundError unless File::exists?(file_name)
raise LogFileAlreadyIncluded if @watched_files.include?(file_name)
@watched_files << file_name
end
# Used as wrapper for several configuration options used for setting up the data store
#
# Example usage:
# data_store.host = :localhost
# data_store.username = :admin
# data_store.password = "secret"
# data_store.keyspace = :constellation
#
def data_store
@data_store
end
end
end |
require "thor"
module Constellation
class Runner < Thor
include Thor::Actions
@@config = Config.new
def initialize(*)
super
end
desc "init", "Generates a ConstellationFile and initializes the application"
def init
puts "Initializing new application"
end
desc "start", "Starts watching for log entries"
def start
end
desc "stop", "Stops watching for log entries"
def stop
end
desc "restart", "Restarts watching for log entries"
def restart
end
desc "version", "Shows the version of the currently installed Constellation gem"
def version
puts ::Constellation::VERSION
end
map %w(-v --version) => :version
desc "help", "Shows the example usage of all available command line options"
def help
puts "Available command line options:"
puts ""
puts "constellation init Generates a ConstellationFile and initializes the application"
puts "constellation start Starts watching for log entries"
puts "constellation stop Stops watching for log entries"
puts "constellation restart Restarts watching for log entries"
puts "constellation version Shows the version of the currently installed Constellation gem"
puts "constellation help Shows the example usage of all available command line options"
end
map %w(--help) => :help
end
end
Change config to an instance variable
require "thor"
module Constellation
class Runner < Thor
include Thor::Actions
def initialize(*)
super
@config = Config.new
end
desc "init", "Generates a ConstellationFile and initializes the application"
def init
puts "Initializing new application"
end
desc "start", "Starts watching for log entries"
def start
end
desc "stop", "Stops watching for log entries"
def stop
end
desc "restart", "Restarts watching for log entries"
def restart
end
desc "version", "Shows the version of the currently installed Constellation gem"
def version
puts ::Constellation::VERSION
end
map %w(-v --version) => :version
desc "help", "Shows the example usage of all available command line options"
def help
puts "Available command line options:"
puts ""
puts "constellation init Generates a ConstellationFile and initializes the application"
puts "constellation start Starts watching for log entries"
puts "constellation stop Stops watching for log entries"
puts "constellation restart Restarts watching for log entries"
puts "constellation version Shows the version of the currently installed Constellation gem"
puts "constellation help Shows the example usage of all available command line options"
end
map %w(--help) => :help
end
end |
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "jquery-ui-bootstrap-rails"
s.version = "0.1.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Kristian Mandrup"]
s.date = "2012-09-03"
s.description = "Use jQuery UI with Twitter Bootstrap in your Rails app :)"
s.email = "kmandrup@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = `git ls-files`.split($/)
s.homepage = "http://github.com/kristianmandrup/jquery-ui-bootstrap-rails"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "jQuery UI Bootstrap for Rails asset pipeline"
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_runtime_dependency(%q<rails>, [">= 0"])
s.add_development_dependency(%q<rspec>, [">= 2.8.0"])
s.add_development_dependency(%q<rdoc>, [">= 3.12"])
s.add_development_dependency(%q<bundler>, [">= 1.0.0"])
s.add_development_dependency(%q<jeweler>, [">= 1.8.3"])
s.add_development_dependency(%q<simplecov>, [">= 0.5"])
else
s.add_dependency(%q<rails>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.8.0"])
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, [">= 1.8.3"])
s.add_dependency(%q<simplecov>, [">= 0.5"])
end
else
s.add_dependency(%q<rails>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.8.0"])
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, [">= 1.8.3"])
s.add_dependency(%q<simplecov>, [">= 0.5"])
end
end
Regenerate gemspec for version 0.1.1
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "jquery-ui-bootstrap-rails"
s.version = "0.1.1"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Kristian Mandrup"]
s.date = "2014-02-14"
s.description = "Use jQuery UI with Twitter Bootstrap in your Rails app :)"
s.email = "kmandrup@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
".rspec",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.md",
"Rakefile",
"VERSION",
"jquery-ui-bootstrap-rails.gemspec",
"lib/jquery-ui-bootstrap-rails.rb",
"lib/jquery-ui-bootstrap-rails/engine.rb",
"lib/jquery-ui-bootstrap-rails/engine3.rb",
"lib/jquery-ui-bootstrap-rails/railtie.rb",
"spec/index.html",
"spec/spec_helper.rb",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_flat_0_aaaaaa_40x100.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_glass_55_fbf9ee_1x400.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_glass_65_ffffff_1x400.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_glass_75_dadada_1x400.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_glass_75_e6e6e6_1x400.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_glass_75_ffffff_1x400.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_highlight-soft_75_cccccc_1x100.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-bg_inset-soft_95_fef1ec_1x100.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-icons_222222_256x240.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-icons_2e83ff_256x240.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-icons_454545_256x240.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-icons_888888_256x240.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-icons_cd0a0a_256x240.png",
"vendor/assets/images/ui-bootstrap/custom-theme/ui-icons_f6cf3b_256x240.png",
"vendor/assets/images/ui-file_input/icon-generic.gif",
"vendor/assets/images/ui-file_input/icon-image.gif",
"vendor/assets/images/ui-file_input/icon-media.gif",
"vendor/assets/images/ui-file_input/icon-zip.gif",
"vendor/assets/javascripts/ui-bootstrap/demo.js",
"vendor/assets/javascripts/ui-date_range_picker/date.js",
"vendor/assets/javascripts/ui-date_range_picker/jquery.daterangepicker.js",
"vendor/assets/javascripts/ui-date_range_picker/jquery.daterangepicker.min.js",
"vendor/assets/javascripts/ui-file_input/enhance.min.js",
"vendor/assets/javascripts/ui-file_input/jquery.fileinput.js",
"vendor/assets/javascripts/wijmo/jquery.bgiframe-2.1.3-pre.js",
"vendor/assets/javascripts/wijmo/jquery.mousewheel.min.js",
"vendor/assets/javascripts/wijmo/jquery.wijmo-open.all.min.js",
"vendor/assets/stylesheets/ui-bootstrap/jquery-ui-bootstrap.css.scss",
"vendor/assets/stylesheets/ui-bootstrap/jquery-ui-bootstrap.latest.css.scss",
"vendor/assets/stylesheets/ui-bootstrap/ui-wijmo.css",
"vendor/assets/stylesheets/ui-date_range_picker/ui.daterangepicker.css",
"vendor/assets/stylesheets/ui-file_input/enhance.css.scss",
"vendor/assets/stylesheets/wijmo/jquery.wijmo-open.2.2.0.css"
]
s.homepage = "http://github.com/kristianmandrup/jquery-ui-bootstrap-rails"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "2.0.0"
s.summary = "jQuery UI Bootstrap for Rails asset pipeline"
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<rails>, [">= 0"])
s.add_development_dependency(%q<rspec>, [">= 2.8.0"])
s.add_development_dependency(%q<rdoc>, [">= 3.12"])
s.add_development_dependency(%q<bundler>, [">= 1.0.0"])
s.add_development_dependency(%q<jeweler>, [">= 1.8.3"])
s.add_development_dependency(%q<simplecov>, [">= 0.5"])
else
s.add_dependency(%q<rails>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.8.0"])
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, [">= 1.8.3"])
s.add_dependency(%q<simplecov>, [">= 0.5"])
end
else
s.add_dependency(%q<rails>, [">= 0"])
s.add_dependency(%q<rspec>, [">= 2.8.0"])
s.add_dependency(%q<rdoc>, [">= 3.12"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, [">= 1.8.3"])
s.add_dependency(%q<simplecov>, [">= 0.5"])
end
end
|
require 'securerandom'
module CruLib
class AccessToken < ActiveModelSerializers::Model
attr_accessor :key_guid, :email, :first_name, :last_name, :token, :pgt
def initialize(attributes = {})
attributes.symbolize_keys!
super(attributes)
@token = generate_access_token unless attributes[:token]
write
end
class << self
def read(token)
json = exist?(token)
new(Oj.load(json)) if json
end
def exist?(token)
redis_client.get(redis_key(token))
end
def redis_client
@redis_client ||= CruLib.redis_client
end
def redis_key(token)
['cru_lib', 'access_token', token].join(':')
end
def del(token)
redis_client.del(redis_key(token))
end
end
private
def generate_access_token
loop do
attributes[:token] = SecureRandom.uuid.gsub(/\-/, '')
break unless self.class.exist?(attributes[:token])
end
attributes[:token]
end
def write
self.class.redis_client.setex(self.class.redis_key(attributes[:token]), 30.minutes.to_i, to_json)
end
end
end
Add additional guid attributes
require 'securerandom'
module CruLib
class AccessToken < ActiveModelSerializers::Model
attr_accessor :key_guid, :relay_guid, :guid, :email, :first_name, :last_name, :token, :pgt
def initialize(attributes = {})
attributes.symbolize_keys!
super(attributes)
@token = generate_access_token unless attributes[:token]
write
end
class << self
def read(token)
json = exist?(token)
new(Oj.load(json)) if json
end
def exist?(token)
redis_client.get(redis_key(token))
end
def redis_client
@redis_client ||= CruLib.redis_client
end
def redis_key(token)
['cru_lib', 'access_token', token].join(':')
end
def del(token)
redis_client.del(redis_key(token))
end
end
private
def generate_access_token
loop do
attributes[:token] = SecureRandom.uuid.gsub(/\-/, '')
break unless self.class.exist?(attributes[:token])
end
attributes[:token]
end
def write
self.class.redis_client.setex(self.class.redis_key(attributes[:token]), 30.minutes.to_i, to_json)
end
end
end
|
require 'csvlint'
require 'rdf'
module Csvlint
module Csvw
class Csv2Rdf
include Csvlint::ErrorCollector
attr_reader :result, :minimal, :validate
def initialize(source, dialect = {}, schema = nil, options = {})
reset
@source = source
@result = RDF::Graph.new
@minimal = options[:minimal] || false
@validate = options[:validate] || false
if schema.nil?
@table_group = RDF::Node.new
@result << [ @table_group, RDF.type, CSVW.TableGroup ] unless @minimal
@rownum = 0
@columns = []
@validator = Csvlint::Validator.new( @source, dialect, schema, { :validate => @validate, :lambda => lambda { |v| transform(v) } } )
@errors += @validator.errors
@warnings += @validator.warnings
else
@table_group = RDF::Node.new
@result << [ @table_group, RDF.type, CSVW.TableGroup ] unless @minimal
schema.tables.each do |table_url, table|
@source = table_url
@rownum = 0
@columns = []
@validator = Csvlint::Validator.new( @source, dialect, schema, { :validate => @validate, :lambda => table.suppress_output ? lambda { |a| nil } : lambda { |v| transform(v) } } )
@warnings += @validator.errors
@warnings += @validator.warnings
end
end
end
private
def transform(v)
if v.data[-1]
if @columns.empty?
initialize_result(v)
end
if v.current_line > v.dialect["headerRowCount"]
@rownum += 1
@row = RDF::Node.new
row_data = transform_data(v.data[-1], v.current_line)
unless @minimal
@result << [ @table, CSVW.row, @row ]
@result << [ @row, RDF.type, CSVW.Row ]
@result << [ @row, CSVW.rownum, @rownum ]
@result << [ @row, CSVW.url, RDF::Resource.new("#{@source}#row=#{v.current_line}") ]
row_data.each do |r|
@result << [ @row, CSVW.describes, r ]
end
end
end
else
build_errors(:blank_rows, :structure)
end
end
def initialize_result(v)
unless v.errors.empty?
@errors += v.errors
end
@row_title_columns = []
if v.schema.nil?
v.data[0].each_with_index do |h,i|
@columns.push Csvlint::Csvw::Column.new(i+1, h)
end
@table = RDF::Node.new
unless @minimal
@result << [ @table_group, CSVW.table, @table ]
@result << [ @table, RDF.type, CSVW.Table ]
@result << [ @table, CSVW.url, RDF::Resource.new(@source) ]
end
else
table = v.schema.tables[@source]
@table = table.id ? RDF::Resource.new(table.id) : RDF::Node.new
unless @minimal
v.schema.annotations.each do |a,v|
transform_annotation(@table_group, a, v)
end
unless table.suppress_output
@result << [ @table_group, CSVW.table, @table ]
@result << [ @table, RDF.type, CSVW.Table ]
@result << [ @table, CSVW.url, RDF::Resource.new(@source) ]
table.annotations.each do |a,v|
transform_annotation(@table, a, v)
end
transform_annotation(@table, CSVW.note, table.notes) unless table.notes.empty?
end
end
if table.columns.empty?
v.data[0].each_with_index do |h,i|
@columns.push Csvlint::Csvw::Column.new(i+1, "_col.#{i+1}")
end
else
@columns = table.columns.clone
remainder = v.data[0][table.columns.length..-1]
remainder.each_with_index do |h,i|
@columns.push Csvlint::Csvw::Column.new(i+1, "_col.#{table.columns.length+i+1}")
end if remainder
end
table.row_title_columns.each do |c|
@row_title_columns << (c.name || c.default_name)
end if table.row_title_columns
end
# @result["tables"][-1]["row"] = []
end
def transform_data(data, sourceRow)
values = {}
@columns.each_with_index do |column,i|
unless data[i].nil?
column_name = column.name || column.default_name
base_type = column.datatype["base"] || column.datatype["@id"]
datatype = column.datatype["@id"] || base_type
if data[i].is_a? Array
v = []
data[i].each do |d|
v << Csv2Rdf.value_to_rdf(d, datatype, base_type, column.lang)
end
else
v = Csv2Rdf.value_to_rdf(data[i], datatype, base_type, column.lang)
end
values[column_name] = v
end
end
values["_row"] = @rownum
values["_sourceRow"] = sourceRow
@row_title_columns.each do |column_name|
@result << [ @row, CSVW.title, values[column_name] ]
end unless @minimal
row_subject = RDF::Node.new
subjects = []
@columns.each_with_index do |column,i|
unless column.suppress_output
column_name = column.name || column.default_name
values["_column"] = i
values["_sourceColumn"] = i
values["_name"] = column_name
subject = column.about_url ? RDF::Resource.new(URI.join(@source, column.about_url.expand(values)).to_s) : row_subject
subjects << subject
property = property(column, values)
if column.value_url
value = value(column, values, property == "@type")
else
value = values[column_name]
end
unless value.nil?
Array(value).each do |v|
@result << [ subject, property, v ]
end
end
end
end
return subjects.uniq
end
def transform_annotation(subject, property, value)
property = RDF::Resource.new(Csv2Rdf.expand_prefixes(property)) unless property.is_a? RDF::Resource
case value
when Hash
if value["@id"]
@result << [ subject, property, RDF::Resource.new(value["@id"]) ]
elsif value["@value"]
if value["@type"]
@result << [ subject, property, RDF::Literal.new(value["@value"], :datatype => Csv2Rdf.expand_prefixes(value["@type"])) ]
else
@result << [ subject, property, RDF::Literal.new(value["@value"], :language => value["@language"]) ]
end
else
object = RDF::Node.new
@result << [ subject, property, object ]
value.each do |a,v|
if a == "@type"
@result << [ object, RDF.type, RDF::Resource.new(Csv2Rdf.expand_prefixes(v)) ]
else
transform_annotation(object, a, v)
end
end
end
when Array
value.each do |v|
transform_annotation(subject, property, v)
end
else
@result << [ subject, property, value ]
end
end
def property(column, values)
if column.property_url
url = column.property_url.expand(values)
url = Csv2Rdf.expand_prefixes(url)
url = URI.join(@source, url)
else
url = column.name || column.default_name || "_col.#{column.number}"
url = URI.join(@source, "##{URI.escape(url, Regexp.new("[^A-Za-z0-9_.]"))}")
end
return RDF::Resource.new(url)
end
def value(column, values, compact)
if values[column.name || column.default_name].nil? && !column.virtual
return nil
else
url = column.value_url.expand(values)
url = Csv2Rdf.expand_prefixes(url) unless compact
url = URI.join(@source, url)
return RDF::Resource.new(url)
end
end
def Csv2Rdf.value_to_rdf(value, datatype, base_type, lang)
return value[:invalid] if value.is_a? Hash and value[:invalid]
if value.is_a? Float
if value.nan?
return RDF::Literal.new("NaN", :datatype => datatype)
elsif value == Float::INFINITY
return RDF::Literal.new("INF", :datatype => datatype)
elsif value == -Float::INFINITY
return RDF::Literal.new("-INF", :datatype => datatype)
else
return RDF::Literal.new(value, :datatype => datatype)
end
elsif NUMERIC_DATATYPES.include? base_type
return RDF::Literal.new(value, :datatype => datatype)
elsif base_type == "http://www.w3.org/2001/XMLSchema#boolean"
return value
elsif DATETIME_DATATYPES.include? base_type
return RDF::Literal.new(value[:string], :datatype => datatype)
elsif base_type == "http://www.w3.org/2001/XMLSchema#string"
return RDF::Literal.new(value.to_s, :datatype => datatype) if datatype != base_type
return RDF::Literal.new(value.to_s, :language => lang == "und" ? nil : lang)
else
return RDF::Literal.new(value.to_s, :datatype => datatype)
end
end
def Csv2Rdf.expand_prefixes(url)
return "http://www.w3.org/ns/csvw##{url}" if TERMS.include?(url)
NAMESPACES.each do |prefix,ns|
url = url.gsub(Regexp.new("^#{Regexp.escape(prefix)}:"), "#{ns}")
end
return url
end
CSVW = RDF::Vocabulary.new("http://www.w3.org/ns/csvw#")
NAMESPACES = {
"dcat" => "http://www.w3.org/ns/dcat#",
"qb" => "http://purl.org/linked-data/cube#",
"grddl" => "http://www.w3.org/2003/g/data-view#",
"ma" => "http://www.w3.org/ns/ma-ont#",
"org" => "http://www.w3.org/ns/org#",
"owl" => "http://www.w3.org/2002/07/owl#",
"prov" => "http://www.w3.org/ns/prov#",
"rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfa" => "http://www.w3.org/ns/rdfa#",
"rdfs" => "http://www.w3.org/2000/01/rdf-schema#",
"rif" => "http://www.w3.org/2007/rif#",
"rr" => "http://www.w3.org/ns/r2rml#",
"sd" => "http://www.w3.org/ns/sparql-service-description#",
"skos" => "http://www.w3.org/2004/02/skos/core#",
"skosxl" => "http://www.w3.org/2008/05/skos-xl#",
"wdr" => "http://www.w3.org/2007/05/powder#",
"void" => "http://rdfs.org/ns/void#",
"wdrs" => "http://www.w3.org/2007/05/powder-s#",
"xhv" => "http://www.w3.org/1999/xhtml/vocab#",
"xml" => "http://www.w3.org/XML/1998/namespace",
"xsd" => "http://www.w3.org/2001/XMLSchema#",
"csvw" => "http://www.w3.org/ns/csvw#",
"cnt" => "http://www.w3.org/2008/content",
"earl" => "http://www.w3.org/ns/earl#",
"ht" => "http://www.w3.org/2006/http#",
"oa" => "http://www.w3.org/ns/oa#",
"ptr" => "http://www.w3.org/2009/pointers#",
"cc" => "http://creativecommons.org/ns#",
"ctag" => "http://commontag.org/ns#",
"dc" => "http://purl.org/dc/terms/",
"dcterms" => "http://purl.org/dc/terms/",
"dc11" => "http://purl.org/dc/elements/1.1/",
"foaf" => "http://xmlns.com/foaf/0.1/",
"gr" => "http://purl.org/goodrelations/v1#",
"ical" => "http://www.w3.org/2002/12/cal/icaltzd#",
"og" => "http://ogp.me/ns#",
"rev" => "http://purl.org/stuff/rev#",
"sioc" => "http://rdfs.org/sioc/ns#",
"v" => "http://rdf.data-vocabulary.org/#",
"vcard" => "http://www.w3.org/2006/vcard/ns#",
"schema" => "http://schema.org/"
}
TERMS =
NAMESPACES.keys +
[ "TableGroup", "Table", "Column", "Row", "Cell", "Schema", "Datatype", "Dialect", "Direction", "ForeignKey", "NumericFormat", "TableReference", "Transformation" ]
NUMERIC_DATATYPES = [
"http://www.w3.org/2001/XMLSchema#decimal",
"http://www.w3.org/2001/XMLSchema#integer",
"http://www.w3.org/2001/XMLSchema#long",
"http://www.w3.org/2001/XMLSchema#int",
"http://www.w3.org/2001/XMLSchema#short",
"http://www.w3.org/2001/XMLSchema#byte",
"http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
"http://www.w3.org/2001/XMLSchema#positiveInteger",
"http://www.w3.org/2001/XMLSchema#unsignedLong",
"http://www.w3.org/2001/XMLSchema#unsignedInt",
"http://www.w3.org/2001/XMLSchema#unsignedShort",
"http://www.w3.org/2001/XMLSchema#unsignedByte",
"http://www.w3.org/2001/XMLSchema#nonPositiveInteger",
"http://www.w3.org/2001/XMLSchema#negativeInteger",
"http://www.w3.org/2001/XMLSchema#double",
"http://www.w3.org/2001/XMLSchema#float"
]
DATETIME_DATATYPES = [
"http://www.w3.org/2001/XMLSchema#date",
"http://www.w3.org/2001/XMLSchema#dateTime",
"http://www.w3.org/2001/XMLSchema#dateTimeStamp",
"http://www.w3.org/2001/XMLSchema#time",
"http://www.w3.org/2001/XMLSchema#gYear",
"http://www.w3.org/2001/XMLSchema#gYearMonth",
"http://www.w3.org/2001/XMLSchema#gMonth",
"http://www.w3.org/2001/XMLSchema#gMonthDay",
"http://www.w3.org/2001/XMLSchema#gDay",
]
end
end
end
support ordered values (8 failing)
require 'csvlint'
require 'rdf'
module Csvlint
module Csvw
class Csv2Rdf
include Csvlint::ErrorCollector
attr_reader :result, :minimal, :validate
def initialize(source, dialect = {}, schema = nil, options = {})
reset
@source = source
@result = RDF::Graph.new
@minimal = options[:minimal] || false
@validate = options[:validate] || false
if schema.nil?
@table_group = RDF::Node.new
@result << [ @table_group, RDF.type, CSVW.TableGroup ] unless @minimal
@rownum = 0
@columns = []
@validator = Csvlint::Validator.new( @source, dialect, schema, { :validate => @validate, :lambda => lambda { |v| transform(v) } } )
@errors += @validator.errors
@warnings += @validator.warnings
else
@table_group = RDF::Node.new
@result << [ @table_group, RDF.type, CSVW.TableGroup ] unless @minimal
schema.tables.each do |table_url, table|
@source = table_url
@rownum = 0
@columns = []
@validator = Csvlint::Validator.new( @source, dialect, schema, { :validate => @validate, :lambda => table.suppress_output ? lambda { |a| nil } : lambda { |v| transform(v) } } )
@warnings += @validator.errors
@warnings += @validator.warnings
end
end
end
private
def transform(v)
if v.data[-1]
if @columns.empty?
initialize_result(v)
end
if v.current_line > v.dialect["headerRowCount"]
@rownum += 1
@row = RDF::Node.new
row_data = transform_data(v.data[-1], v.current_line)
unless @minimal
@result << [ @table, CSVW.row, @row ]
@result << [ @row, RDF.type, CSVW.Row ]
@result << [ @row, CSVW.rownum, @rownum ]
@result << [ @row, CSVW.url, RDF::Resource.new("#{@source}#row=#{v.current_line}") ]
row_data.each do |r|
@result << [ @row, CSVW.describes, r ]
end
end
end
else
build_errors(:blank_rows, :structure)
end
end
def initialize_result(v)
unless v.errors.empty?
@errors += v.errors
end
@row_title_columns = []
if v.schema.nil?
v.data[0].each_with_index do |h,i|
@columns.push Csvlint::Csvw::Column.new(i+1, h)
end
@table = RDF::Node.new
unless @minimal
@result << [ @table_group, CSVW.table, @table ]
@result << [ @table, RDF.type, CSVW.Table ]
@result << [ @table, CSVW.url, RDF::Resource.new(@source) ]
end
else
table = v.schema.tables[@source]
@table = table.id ? RDF::Resource.new(table.id) : RDF::Node.new
unless @minimal
v.schema.annotations.each do |a,v|
transform_annotation(@table_group, a, v)
end
unless table.suppress_output
@result << [ @table_group, CSVW.table, @table ]
@result << [ @table, RDF.type, CSVW.Table ]
@result << [ @table, CSVW.url, RDF::Resource.new(@source) ]
table.annotations.each do |a,v|
transform_annotation(@table, a, v)
end
transform_annotation(@table, CSVW.note, table.notes) unless table.notes.empty?
end
end
if table.columns.empty?
v.data[0].each_with_index do |h,i|
@columns.push Csvlint::Csvw::Column.new(i+1, "_col.#{i+1}")
end
else
@columns = table.columns.clone
remainder = v.data[0][table.columns.length..-1]
remainder.each_with_index do |h,i|
@columns.push Csvlint::Csvw::Column.new(i+1, "_col.#{table.columns.length+i+1}")
end if remainder
end
table.row_title_columns.each do |c|
@row_title_columns << (c.name || c.default_name)
end if table.row_title_columns
end
# @result["tables"][-1]["row"] = []
end
def transform_data(data, sourceRow)
values = {}
@columns.each_with_index do |column,i|
unless data[i].nil?
column_name = column.name || column.default_name
base_type = column.datatype["base"] || column.datatype["@id"]
datatype = column.datatype["@id"] || base_type
if data[i].is_a? Array
v = []
data[i].each do |d|
v << Csv2Rdf.value_to_rdf(d, datatype, base_type, column.lang)
end
else
v = Csv2Rdf.value_to_rdf(data[i], datatype, base_type, column.lang)
end
values[column_name] = v
end
end
values["_row"] = @rownum
values["_sourceRow"] = sourceRow
@row_title_columns.each do |column_name|
@result << [ @row, CSVW.title, values[column_name] ]
end unless @minimal
row_subject = RDF::Node.new
subjects = []
@columns.each_with_index do |column,i|
unless column.suppress_output
column_name = column.name || column.default_name
values["_column"] = i
values["_sourceColumn"] = i
values["_name"] = column_name
subject = column.about_url ? RDF::Resource.new(URI.join(@source, column.about_url.expand(values)).to_s) : row_subject
subjects << subject
property = property(column, values)
if column.value_url
value = value(column, values, property == "@type")
else
value = values[column_name]
end
unless value.nil?
if column.separator && column.ordered
list = RDF::List[]
list[0..Array(value).length] = Array(value)
@result << [ subject, property, list.subject ]
list.each_statement do |s|
@result << s
end
else
Array(value).each do |v|
@result << [ subject, property, v ]
end
end
end
end
end
return subjects.uniq
end
def transform_annotation(subject, property, value)
property = RDF::Resource.new(Csv2Rdf.expand_prefixes(property)) unless property.is_a? RDF::Resource
case value
when Hash
if value["@id"]
@result << [ subject, property, RDF::Resource.new(value["@id"]) ]
elsif value["@value"]
if value["@type"]
@result << [ subject, property, RDF::Literal.new(value["@value"], :datatype => Csv2Rdf.expand_prefixes(value["@type"])) ]
else
@result << [ subject, property, RDF::Literal.new(value["@value"], :language => value["@language"]) ]
end
else
object = RDF::Node.new
@result << [ subject, property, object ]
value.each do |a,v|
if a == "@type"
@result << [ object, RDF.type, RDF::Resource.new(Csv2Rdf.expand_prefixes(v)) ]
else
transform_annotation(object, a, v)
end
end
end
when Array
value.each do |v|
transform_annotation(subject, property, v)
end
else
@result << [ subject, property, value ]
end
end
def property(column, values)
if column.property_url
url = column.property_url.expand(values)
url = Csv2Rdf.expand_prefixes(url)
url = URI.join(@source, url)
else
url = column.name || column.default_name || "_col.#{column.number}"
url = URI.join(@source, "##{URI.escape(url, Regexp.new("[^A-Za-z0-9_.]"))}")
end
return RDF::Resource.new(url)
end
def value(column, values, compact)
if values[column.name || column.default_name].nil? && !column.virtual
return nil
else
url = column.value_url.expand(values)
url = Csv2Rdf.expand_prefixes(url) unless compact
url = URI.join(@source, url)
return RDF::Resource.new(url)
end
end
def Csv2Rdf.value_to_rdf(value, datatype, base_type, lang)
return value[:invalid] if value.is_a? Hash and value[:invalid]
if value.is_a? Float
if value.nan?
return RDF::Literal.new("NaN", :datatype => datatype)
elsif value == Float::INFINITY
return RDF::Literal.new("INF", :datatype => datatype)
elsif value == -Float::INFINITY
return RDF::Literal.new("-INF", :datatype => datatype)
else
return RDF::Literal.new(value, :datatype => datatype)
end
elsif NUMERIC_DATATYPES.include? base_type
return RDF::Literal.new(value, :datatype => datatype)
elsif base_type == "http://www.w3.org/2001/XMLSchema#boolean"
return value
elsif DATETIME_DATATYPES.include? base_type
return RDF::Literal.new(value[:string], :datatype => datatype)
elsif base_type == "http://www.w3.org/2001/XMLSchema#string"
return RDF::Literal.new(value.to_s, :datatype => datatype) if datatype != base_type
return RDF::Literal.new(value.to_s, :language => lang == "und" ? nil : lang)
else
return RDF::Literal.new(value.to_s, :datatype => datatype)
end
end
def Csv2Rdf.expand_prefixes(url)
return "http://www.w3.org/ns/csvw##{url}" if TERMS.include?(url)
NAMESPACES.each do |prefix,ns|
url = url.gsub(Regexp.new("^#{Regexp.escape(prefix)}:"), "#{ns}")
end
return url
end
CSVW = RDF::Vocabulary.new("http://www.w3.org/ns/csvw#")
NAMESPACES = {
"dcat" => "http://www.w3.org/ns/dcat#",
"qb" => "http://purl.org/linked-data/cube#",
"grddl" => "http://www.w3.org/2003/g/data-view#",
"ma" => "http://www.w3.org/ns/ma-ont#",
"org" => "http://www.w3.org/ns/org#",
"owl" => "http://www.w3.org/2002/07/owl#",
"prov" => "http://www.w3.org/ns/prov#",
"rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfa" => "http://www.w3.org/ns/rdfa#",
"rdfs" => "http://www.w3.org/2000/01/rdf-schema#",
"rif" => "http://www.w3.org/2007/rif#",
"rr" => "http://www.w3.org/ns/r2rml#",
"sd" => "http://www.w3.org/ns/sparql-service-description#",
"skos" => "http://www.w3.org/2004/02/skos/core#",
"skosxl" => "http://www.w3.org/2008/05/skos-xl#",
"wdr" => "http://www.w3.org/2007/05/powder#",
"void" => "http://rdfs.org/ns/void#",
"wdrs" => "http://www.w3.org/2007/05/powder-s#",
"xhv" => "http://www.w3.org/1999/xhtml/vocab#",
"xml" => "http://www.w3.org/XML/1998/namespace",
"xsd" => "http://www.w3.org/2001/XMLSchema#",
"csvw" => "http://www.w3.org/ns/csvw#",
"cnt" => "http://www.w3.org/2008/content",
"earl" => "http://www.w3.org/ns/earl#",
"ht" => "http://www.w3.org/2006/http#",
"oa" => "http://www.w3.org/ns/oa#",
"ptr" => "http://www.w3.org/2009/pointers#",
"cc" => "http://creativecommons.org/ns#",
"ctag" => "http://commontag.org/ns#",
"dc" => "http://purl.org/dc/terms/",
"dcterms" => "http://purl.org/dc/terms/",
"dc11" => "http://purl.org/dc/elements/1.1/",
"foaf" => "http://xmlns.com/foaf/0.1/",
"gr" => "http://purl.org/goodrelations/v1#",
"ical" => "http://www.w3.org/2002/12/cal/icaltzd#",
"og" => "http://ogp.me/ns#",
"rev" => "http://purl.org/stuff/rev#",
"sioc" => "http://rdfs.org/sioc/ns#",
"v" => "http://rdf.data-vocabulary.org/#",
"vcard" => "http://www.w3.org/2006/vcard/ns#",
"schema" => "http://schema.org/"
}
TERMS =
NAMESPACES.keys +
[ "TableGroup", "Table", "Column", "Row", "Cell", "Schema", "Datatype", "Dialect", "Direction", "ForeignKey", "NumericFormat", "TableReference", "Transformation" ]
NUMERIC_DATATYPES = [
"http://www.w3.org/2001/XMLSchema#decimal",
"http://www.w3.org/2001/XMLSchema#integer",
"http://www.w3.org/2001/XMLSchema#long",
"http://www.w3.org/2001/XMLSchema#int",
"http://www.w3.org/2001/XMLSchema#short",
"http://www.w3.org/2001/XMLSchema#byte",
"http://www.w3.org/2001/XMLSchema#nonNegativeInteger",
"http://www.w3.org/2001/XMLSchema#positiveInteger",
"http://www.w3.org/2001/XMLSchema#unsignedLong",
"http://www.w3.org/2001/XMLSchema#unsignedInt",
"http://www.w3.org/2001/XMLSchema#unsignedShort",
"http://www.w3.org/2001/XMLSchema#unsignedByte",
"http://www.w3.org/2001/XMLSchema#nonPositiveInteger",
"http://www.w3.org/2001/XMLSchema#negativeInteger",
"http://www.w3.org/2001/XMLSchema#double",
"http://www.w3.org/2001/XMLSchema#float"
]
DATETIME_DATATYPES = [
"http://www.w3.org/2001/XMLSchema#date",
"http://www.w3.org/2001/XMLSchema#dateTime",
"http://www.w3.org/2001/XMLSchema#dateTimeStamp",
"http://www.w3.org/2001/XMLSchema#time",
"http://www.w3.org/2001/XMLSchema#gYear",
"http://www.w3.org/2001/XMLSchema#gYearMonth",
"http://www.w3.org/2001/XMLSchema#gMonth",
"http://www.w3.org/2001/XMLSchema#gMonthDay",
"http://www.w3.org/2001/XMLSchema#gDay",
]
end
end
end
|
module ActionController
module Resources
class Resource
attr_reader :path_segment, :actions_as, :resources_as, :namespaces_as
def initialize(entities, options)
@plural ||= entities
@singular ||= options[:singular] || plural.to_s.singularize
@resources_as = options.delete(:resources_as) || {}
@actions_as = options.delete(:actions_as) || {}
@namespaces_as = options.delete(:namespaces_as) || {}
@path_segment = options.delete(:as) || @resources_as[entities] || @plural
@options = options
arrange_actions
add_default_actions
set_prefixes
end
def path
@path ||= "#{path_prefix}/#{path_segment}"
end
def new_path
action_new = @actions_as[:new] || 'new'
@new_path ||= "#{path}/#{action_new}"
end
def set_prefixes
@path_prefix = change_namespace(options.delete(:path_prefix))
@name_prefix = options.delete(:name_prefix)
end
def change_namespace(prefix)
if prefix && @namespaces_as.has_key?(prefix)
@namespaces_as[prefix].to_sym
else
prefix
end
end
end
def map_resource(entities, options = {}, &block)
options.merge!(:actions_as => @actions_as, :resources_as => @resources_as, :namespaces_as => @namespaces_as)
resource = Resource.new(entities, options)
with_options :controller => resource.controller do |map|
map_collection_actions(map, resource)
map_default_collection_actions(map, resource)
map_new_actions(map, resource)
map_member_actions(map, resource)
map_associations(resource, options)
if block_given?
with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], &block)
end
end
end
def aliases(*args)
if args.size > 0
options = args.extract_options!
case args[0]
when :resources
@resources_as = options || {}
when :actions
@actions_as = options || {}
when :namespaces
@namespaces_as = options || {}
end
end
end
def map_collection_actions(map, resource)
resource.collection_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
if resource.actions_as.has_key?(action)
map.named_route("#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{resource.actions_as[action]}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{resource.actions_as[action]}.:format", action_options)
else
map.named_route("#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}.:format", action_options)
end
end
end
end
def map_member_actions(map, resource)
resource.member_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
if resource.actions_as.has_key?(action)
map.named_route("#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{resource.actions_as[action]}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{resource.actions_as[action]}.:format", action_options)
elsif
map.named_route("#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action}.:format", action_options)
end
end
end
show_action_options = action_options_for("show", resource)
map.named_route("#{resource.name_prefix}#{resource.singular}", resource.member_path, show_action_options)
map.named_route("formatted_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}.:format", show_action_options)
update_action_options = action_options_for("update", resource)
map.connect(resource.member_path, update_action_options)
map.connect("#{resource.member_path}.:format", update_action_options)
destroy_action_options = action_options_for("destroy", resource)
map.connect(resource.member_path, destroy_action_options)
map.connect("#{resource.member_path}.:format", destroy_action_options)
end
end
end
Adding the option actions_as in map.resources to customize the actions of the route by an individual.
module ActionController
module Resources
class Resource
attr_reader :path_segment, :actions_as, :resources_as, :namespaces_as
def initialize(entities, options)
@plural ||= entities
@singular ||= options[:singular] || plural.to_s.singularize
@resources_as = options.delete(:resources_as) || {}
@actions_as = options.delete(:actions_as) || {}
@namespaces_as = options.delete(:namespaces_as) || {}
@path_segment = options.delete(:as) || @resources_as[entities] || @plural
@options = options
arrange_actions
add_default_actions
set_prefixes
end
def path
@path ||= "#{path_prefix}/#{path_segment}"
end
def new_path
action_new = @actions_as[:new] || 'new'
@new_path ||= "#{path}/#{action_new}"
end
def set_prefixes
@path_prefix = change_namespace(options.delete(:path_prefix))
@name_prefix = options.delete(:name_prefix)
end
def change_namespace(prefix)
if prefix && @namespaces_as.has_key?(prefix)
@namespaces_as[prefix].to_sym
else
prefix
end
end
end
def map_resource(entities, options = {}, &block)
@actions_as ||= {}
actions_as = options.has_key?(:actions_as) ? @actions_as.merge(options[:actions_as]) : @actions_as
options.merge!(:actions_as => actions_as, :resources_as => @resources_as, :namespaces_as => @namespaces_as)
resource = Resource.new(entities, options)
with_options :controller => resource.controller do |map|
map_collection_actions(map, resource)
map_default_collection_actions(map, resource)
map_new_actions(map, resource)
map_member_actions(map, resource)
map_associations(resource, options)
if block_given?
with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], &block)
end
end
end
def aliases(*args)
if args.size > 0
options = args.extract_options!
case args[0]
when :resources
@resources_as = options || {}
when :actions
@actions_as = options || {}
when :namespaces
@namespaces_as = options || {}
end
end
end
def map_collection_actions(map, resource)
resource.collection_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
if resource.actions_as.has_key?(action)
map.named_route("#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{resource.actions_as[action]}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{resource.actions_as[action]}.:format", action_options)
else
map.named_route("#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}.:format", action_options)
end
end
end
end
def map_member_actions(map, resource)
resource.member_methods.each do |method, actions|
actions.each do |action|
action_options = action_options_for(action, resource, method)
if resource.actions_as.has_key?(action)
map.named_route("#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{resource.actions_as[action]}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{resource.actions_as[action]}.:format", action_options)
elsif
map.named_route("#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action}", action_options)
map.named_route("formatted_#{action}_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action}.:format", action_options)
end
end
end
show_action_options = action_options_for("show", resource)
map.named_route("#{resource.name_prefix}#{resource.singular}", resource.member_path, show_action_options)
map.named_route("formatted_#{resource.name_prefix}#{resource.singular}", "#{resource.member_path}.:format", show_action_options)
update_action_options = action_options_for("update", resource)
map.connect(resource.member_path, update_action_options)
map.connect("#{resource.member_path}.:format", update_action_options)
destroy_action_options = action_options_for("destroy", resource)
map.connect(resource.member_path, destroy_action_options)
map.connect("#{resource.member_path}.:format", destroy_action_options)
end
end
end |
require 'danger/commands/init_helpers/interviewer'
require 'danger/ci_source/local_git_repo'
require 'yaml'
module Danger
class Init < Runner
self.summary = 'Helps you set up Danger.'
self.command = 'init'
def self.options
[
['--impatient', "'I've not got all day here. Don't add any thematic delays please.'"],
['--mousey', "'Don't make me press return to continue the adventure.'"]
].concat(super)
end
def initialize(argv)
ui.no_delay = argv.flag?('impatient', false)
ui.no_waiting = argv.flag?('mousey', false)
@bot_name = File.basename(Dir.getwd).split(".").first.capitalize + "Bot"
super
end
def run
ui = Interviewer.new
ui.say "\nOK, thanks #{ENV['LOGNAME']}, grab a seat and we'll get you started.\n".yellow
ui.pause 1
show_todo_state
ui.pause 1.4
setup_dangerfile
setup_github_account
setup_access_token
setup_danger_ci
info
thanks
end
def ui
@ui ||= Interviewer.new
end
def show_todo_state
ui.say "We need to do the following steps:\n"
ui.pause 0.6
ui.say " - [ ] Create a Dangerfile and add a few simple rules."
ui.pause 0.6
ui.say " - [#{@account_created ? 'x' : ' '}] Create a GitHub account for Danger use for messaging."
ui.pause 0.6
ui.say " - [ ] Set up an access token for Danger."
ui.pause 0.6
ui.say " - [ ] Set up Danger to run on your CI.\n\n"
end
def setup_dangerfile
dir = Danger.gem_path
content = File.read(File.join(dir, "lib", "assets", "DangerfileTemplate"))
File.write("Dangerfile", content)
ui.header 'Step 1: Creating a starter Dangerfile'
ui.say "I've set up an example Dangerfile for you in this folder.\n"
ui.pause 1
ui.say "cat #{Dir.pwd}/Dangerfile\n".blue
content.lines.each do |l|
ui.say " " + l.chomp.green
end
ui.say ""
ui.pause 2
ui.say "There's a collection of small, simple ideas in here, but Danger is about being able to easily"
ui.say "iterate. The power comes from you have the ability to codify fixes to some of the problems"
ui.say "that come up in day to day programming. It can be difficult to try and see those from day 1."
ui.say "\nIf you'd like to investigate the file, and make some changes - I'll wait here,"
ui.say "press return when you're ready to move on..."
ui.wait_for_return
end
def setup_github_account
ui.header 'Step 2: Creating a GitHub account'
ui.say "In order to get the most out of Danger, I'd recommend giving her the ability to post in"
ui.say "the code-review comment section.\n\n"
ui.pause 1
ui.say "IMO, it's best to do this by using the private mode of your browser. Create an account like"
ui.say "#{@bot_name}, and don't forget a cool robot avatar.\n\n"
ui.pause 1
ui.say 'Here are great resources for creative commons images of robots:'
ui.link 'https://www.flickr.com/search/?text=robot&license=2%2C3%2C4%2C5%2C6%2C9'
ui.link 'https://www.google.com/search?q=robot&tbs=sur:fmc&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwjgy8-f95jLAhWI7hoKHV_UD00QsAQIMQ&biw=1265&bih=1359'
ui.say ""
note_about_clicking_links
ui.pause 1
ui.say "\nCool, please press return when you have your account ready (and you've verified the email...)"
ui.wait_for_return
end
def setup_access_token
ui.header 'Step 3: Configuring a GitHub Personal Access Token'
ui.say "Here's the link, you should open this in the private session where you just created the new GitHub account"
ui.link "https://github.com/settings/tokens/new"
ui.pause 1
@is_open_source = ui.ask_with_answers("For token access rights, I need to know if this is for an Open Source or Closed Source project\n", ["Open", "Closed"])
if considered_an_oss_repo?
ui.say "For Open Source projects, I'd recommend giving the token the smallest scope possible."
ui.say "This means only providing access to " + "public_info".yellow + " in the token.\n\n"
ui.pause 1
ui.say "This token limits Danger's abilities to just to writing comments on OSS projects. I recommend"
ui.say "this because the token can quite easily be extracted from the environment via pull requests."
ui.say "#{@bot_name} does not need admin access to your repo. So its ability to cause chaos is minimalized.\n"
elsif @is_open_source == "closed"
ui.say "For Closed Source projects, I'd recommend giving the token access to the whole repo scope."
ui.say "This means only providing access to " + "repo".yellow + ", and its children in the token.\n\n"
ui.pause 1
ui.say "It's worth noting that you " + "should not".bold.white + " re-use this token for OSS repos."
ui.say "Make a new one for those repos with just " + "public_info".yellow + "."
end
ui.say "\n👍, please press return when you have your token set up..."
ui.wait_for_return
end
def considered_an_oss_repo?
@is_open_source == "open"
end
def current_repo_slug
@repo ||= Danger::CISource::LocalGitRepo.new
@repo.repo_slug || "[Your/Repo]"
end
def setup_danger_ci
ui.header 'Step 4: Add Danger for your CI'
uses_travis if File.exist? ".travis.yml"
uses_circle if File.exist? "circle.yml"
unsure_ci unless File.exist?(".travis.yml") || File.exist?(".circle.yml")
ui.say "\nOK, I'll give you a moment to do this..."
ui.wait_for_return
ui.say "Final step: exposing the GitHub token as an environment build variable."
ui.pause 0.4
if considered_an_oss_repo?
ui.say "As you have an Open Source repo, this token should be considered public, otherwise you cannot"
ui.say "run Danger on pull requests from forks, limiting its use.\n"
ui.pause 1
end
travis_token if File.exist? ".travis.yml"
circle_token if File.exist? "circle.yml"
unsure_token unless File.exist?(".travis.yml") || File.exist?(".circle.yml")
ui.pause 0.6
ui.say "This is the last step, I can give you a second..."
ui.wait_for_return
end
def uses_travis
danger = "bundle exec danger".yellow
config = YAML.load(File.read(".travis.yml"))
if config["script"]
ui.say "Add " + "- ".yellow + danger + " as a new step in the " + "script".yellow + " section of your .travis.yml file."
else
ui.say "I'd recommend adding " + "script: ".yellow + danger + " to the script section of your .travis.yml file."
end
ui.pause 1
ui.say "You shouldn't use " + "after_success, after_failure, after_script".red + " as they cannot fail your builds."
end
def uses_circle
danger = "bundle exec danger".yellow
config = YAML.load(File.read("circle.yml"))
if config["test"]
if config["test"]["post"]
ui.say "Add " + danger + " as a new step in the " + "test:post:".yellow + " section of your circle.yml file."
else
ui.say "Add " + danger + " as a new step in the " + "test:override:".yellow + " section of your circle.yml file."
end
else
ui.say "Add this to the bottom of your circle.yml file:"
ui.say "test:".green
ui.say " post:".green
ui.say " - bundle exec danger".green
end
end
def unsure_ci
danger = "bundle exec danger".yellow
ui.say "As I'm not sure what CI you want to run Danger on based on the files in your repo, I'll just offer some generic"
ui.say "advice. You want to run " + danger + " after your tests have finished running, it should still be during the testing"
ui.say "process so the build can fail."
end
def travis_token
# https://travis-ci.org/artsy/eigen/settings
ui.say "In order to add an environment variable, go to:"
ui.link "https://travis-ci.org/#{current_repo_slug}/settings"
ui.say "\nThe name is " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
if @is_open_source
ui.say "Make sure to have \"Display value in build log\" enabled."
end
end
def circle_token
# https://circleci.com/gh/artsy/eigen/edit#env-vars
if considered_an_oss_repo?
ui.say "Before we start, it's important to be up-front. CircleCI only really has one option to support running Danger"
ui.say "for forks on OSS repos. It is quite a drastic option, and I want to let you know the best place to understand"
ui.say "the ramifications of turning on a setting I'm about to advise.\n"
ui.link "https://circleci.com/docs/fork-pr-builds"
ui.say "TLDR: If you have anything other than Danger config settings in CircleCI, then you should not turn on the setting."
ui.say "I'll give you a minute to read it..."
ui.wait_for_return
ui.say "On Danger/Danger we turn on " + "Permissive building of fork pull requests".yellow + " this exposes the token to Danger"
ui.say "You can find this setting at:"
ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#experimental\n"
ui.say "I'll hold..."
ui.wait_for_return
end
ui.say "In order to expose an environment variable, go to:"
ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#env-vars"
ui.say "The name is " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
end
def unsure_token
ui.say "You need to expose a token called " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
ui.say "Depending on the CI system, this may need to be done on the machine ( in the " + "~/.bashprofile".yellow + ") or in a web UI somewhere."
end
def note_about_clicking_links
ui.say "Note: Holding cmd ( ⌘ ) and #{ENV['ITERM_SESSION_ID'] ? '' : 'double '}clicking a link will open it in your browser."
end
def info
ui.header "Useful info"
ui.say "- One of the best ways to test out new rules locally is via " + "bundle exec danger local".yellow + "."
ui.pause 0.6
ui.say "- You can have Danger output all of its variables to the console via the " + "--verbose".yellow + "option."
ui.pause 0.6
ui.say "- You can look at the following Dangerfiles to get some more ideas:"
ui.pause 0.6
ui.link "https://github.com/danger/danger/blob/master/Dangerfile"
ui.link "https://github.com/artsy/eigen/blob/master/Dangerfile"
ui.pause 1
end
def thanks
ui.say "\n\n🎉"
ui.pause 0.6
ui.say "And you're set. Danger is a collaboration between Orta Therox, Gem 'Danger' McShane and Felix Krause."
ui.say "If you like it, let others know. If you want to know more, follow " + "@orta".yellow + " and " + "@KrauseFx".yellow + " on Twitter."
ui.say "If you don't like it, help us improve it! xxx"
end
end
end
Added missing space after `--verbose` #trivial
require 'danger/commands/init_helpers/interviewer'
require 'danger/ci_source/local_git_repo'
require 'yaml'
module Danger
class Init < Runner
self.summary = 'Helps you set up Danger.'
self.command = 'init'
def self.options
[
['--impatient', "'I've not got all day here. Don't add any thematic delays please.'"],
['--mousey', "'Don't make me press return to continue the adventure.'"]
].concat(super)
end
def initialize(argv)
ui.no_delay = argv.flag?('impatient', false)
ui.no_waiting = argv.flag?('mousey', false)
@bot_name = File.basename(Dir.getwd).split(".").first.capitalize + "Bot"
super
end
def run
ui = Interviewer.new
ui.say "\nOK, thanks #{ENV['LOGNAME']}, grab a seat and we'll get you started.\n".yellow
ui.pause 1
show_todo_state
ui.pause 1.4
setup_dangerfile
setup_github_account
setup_access_token
setup_danger_ci
info
thanks
end
def ui
@ui ||= Interviewer.new
end
def show_todo_state
ui.say "We need to do the following steps:\n"
ui.pause 0.6
ui.say " - [ ] Create a Dangerfile and add a few simple rules."
ui.pause 0.6
ui.say " - [#{@account_created ? 'x' : ' '}] Create a GitHub account for Danger use for messaging."
ui.pause 0.6
ui.say " - [ ] Set up an access token for Danger."
ui.pause 0.6
ui.say " - [ ] Set up Danger to run on your CI.\n\n"
end
def setup_dangerfile
dir = Danger.gem_path
content = File.read(File.join(dir, "lib", "assets", "DangerfileTemplate"))
File.write("Dangerfile", content)
ui.header 'Step 1: Creating a starter Dangerfile'
ui.say "I've set up an example Dangerfile for you in this folder.\n"
ui.pause 1
ui.say "cat #{Dir.pwd}/Dangerfile\n".blue
content.lines.each do |l|
ui.say " " + l.chomp.green
end
ui.say ""
ui.pause 2
ui.say "There's a collection of small, simple ideas in here, but Danger is about being able to easily"
ui.say "iterate. The power comes from you have the ability to codify fixes to some of the problems"
ui.say "that come up in day to day programming. It can be difficult to try and see those from day 1."
ui.say "\nIf you'd like to investigate the file, and make some changes - I'll wait here,"
ui.say "press return when you're ready to move on..."
ui.wait_for_return
end
def setup_github_account
ui.header 'Step 2: Creating a GitHub account'
ui.say "In order to get the most out of Danger, I'd recommend giving her the ability to post in"
ui.say "the code-review comment section.\n\n"
ui.pause 1
ui.say "IMO, it's best to do this by using the private mode of your browser. Create an account like"
ui.say "#{@bot_name}, and don't forget a cool robot avatar.\n\n"
ui.pause 1
ui.say 'Here are great resources for creative commons images of robots:'
ui.link 'https://www.flickr.com/search/?text=robot&license=2%2C3%2C4%2C5%2C6%2C9'
ui.link 'https://www.google.com/search?q=robot&tbs=sur:fmc&tbm=isch&tbo=u&source=univ&sa=X&ved=0ahUKEwjgy8-f95jLAhWI7hoKHV_UD00QsAQIMQ&biw=1265&bih=1359'
ui.say ""
note_about_clicking_links
ui.pause 1
ui.say "\nCool, please press return when you have your account ready (and you've verified the email...)"
ui.wait_for_return
end
def setup_access_token
ui.header 'Step 3: Configuring a GitHub Personal Access Token'
ui.say "Here's the link, you should open this in the private session where you just created the new GitHub account"
ui.link "https://github.com/settings/tokens/new"
ui.pause 1
@is_open_source = ui.ask_with_answers("For token access rights, I need to know if this is for an Open Source or Closed Source project\n", ["Open", "Closed"])
if considered_an_oss_repo?
ui.say "For Open Source projects, I'd recommend giving the token the smallest scope possible."
ui.say "This means only providing access to " + "public_info".yellow + " in the token.\n\n"
ui.pause 1
ui.say "This token limits Danger's abilities to just to writing comments on OSS projects. I recommend"
ui.say "this because the token can quite easily be extracted from the environment via pull requests."
ui.say "#{@bot_name} does not need admin access to your repo. So its ability to cause chaos is minimalized.\n"
elsif @is_open_source == "closed"
ui.say "For Closed Source projects, I'd recommend giving the token access to the whole repo scope."
ui.say "This means only providing access to " + "repo".yellow + ", and its children in the token.\n\n"
ui.pause 1
ui.say "It's worth noting that you " + "should not".bold.white + " re-use this token for OSS repos."
ui.say "Make a new one for those repos with just " + "public_info".yellow + "."
end
ui.say "\n👍, please press return when you have your token set up..."
ui.wait_for_return
end
def considered_an_oss_repo?
@is_open_source == "open"
end
def current_repo_slug
@repo ||= Danger::CISource::LocalGitRepo.new
@repo.repo_slug || "[Your/Repo]"
end
def setup_danger_ci
ui.header 'Step 4: Add Danger for your CI'
uses_travis if File.exist? ".travis.yml"
uses_circle if File.exist? "circle.yml"
unsure_ci unless File.exist?(".travis.yml") || File.exist?(".circle.yml")
ui.say "\nOK, I'll give you a moment to do this..."
ui.wait_for_return
ui.say "Final step: exposing the GitHub token as an environment build variable."
ui.pause 0.4
if considered_an_oss_repo?
ui.say "As you have an Open Source repo, this token should be considered public, otherwise you cannot"
ui.say "run Danger on pull requests from forks, limiting its use.\n"
ui.pause 1
end
travis_token if File.exist? ".travis.yml"
circle_token if File.exist? "circle.yml"
unsure_token unless File.exist?(".travis.yml") || File.exist?(".circle.yml")
ui.pause 0.6
ui.say "This is the last step, I can give you a second..."
ui.wait_for_return
end
def uses_travis
danger = "bundle exec danger".yellow
config = YAML.load(File.read(".travis.yml"))
if config["script"]
ui.say "Add " + "- ".yellow + danger + " as a new step in the " + "script".yellow + " section of your .travis.yml file."
else
ui.say "I'd recommend adding " + "script: ".yellow + danger + " to the script section of your .travis.yml file."
end
ui.pause 1
ui.say "You shouldn't use " + "after_success, after_failure, after_script".red + " as they cannot fail your builds."
end
def uses_circle
danger = "bundle exec danger".yellow
config = YAML.load(File.read("circle.yml"))
if config["test"]
if config["test"]["post"]
ui.say "Add " + danger + " as a new step in the " + "test:post:".yellow + " section of your circle.yml file."
else
ui.say "Add " + danger + " as a new step in the " + "test:override:".yellow + " section of your circle.yml file."
end
else
ui.say "Add this to the bottom of your circle.yml file:"
ui.say "test:".green
ui.say " post:".green
ui.say " - bundle exec danger".green
end
end
def unsure_ci
danger = "bundle exec danger".yellow
ui.say "As I'm not sure what CI you want to run Danger on based on the files in your repo, I'll just offer some generic"
ui.say "advice. You want to run " + danger + " after your tests have finished running, it should still be during the testing"
ui.say "process so the build can fail."
end
def travis_token
# https://travis-ci.org/artsy/eigen/settings
ui.say "In order to add an environment variable, go to:"
ui.link "https://travis-ci.org/#{current_repo_slug}/settings"
ui.say "\nThe name is " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
if @is_open_source
ui.say "Make sure to have \"Display value in build log\" enabled."
end
end
def circle_token
# https://circleci.com/gh/artsy/eigen/edit#env-vars
if considered_an_oss_repo?
ui.say "Before we start, it's important to be up-front. CircleCI only really has one option to support running Danger"
ui.say "for forks on OSS repos. It is quite a drastic option, and I want to let you know the best place to understand"
ui.say "the ramifications of turning on a setting I'm about to advise.\n"
ui.link "https://circleci.com/docs/fork-pr-builds"
ui.say "TLDR: If you have anything other than Danger config settings in CircleCI, then you should not turn on the setting."
ui.say "I'll give you a minute to read it..."
ui.wait_for_return
ui.say "On Danger/Danger we turn on " + "Permissive building of fork pull requests".yellow + " this exposes the token to Danger"
ui.say "You can find this setting at:"
ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#experimental\n"
ui.say "I'll hold..."
ui.wait_for_return
end
ui.say "In order to expose an environment variable, go to:"
ui.link "https://circleci.com/gh/#{current_repo_slug}/edit#env-vars"
ui.say "The name is " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
end
def unsure_token
ui.say "You need to expose a token called " + "DANGER_GITHUB_API_TOKEN".yellow + " and the value is the GitHub Personal Acess Token."
ui.say "Depending on the CI system, this may need to be done on the machine ( in the " + "~/.bashprofile".yellow + ") or in a web UI somewhere."
end
def note_about_clicking_links
ui.say "Note: Holding cmd ( ⌘ ) and #{ENV['ITERM_SESSION_ID'] ? '' : 'double '}clicking a link will open it in your browser."
end
def info
ui.header "Useful info"
ui.say "- One of the best ways to test out new rules locally is via " + "bundle exec danger local".yellow + "."
ui.pause 0.6
ui.say "- You can have Danger output all of its variables to the console via the " + "--verbose".yellow + " option."
ui.pause 0.6
ui.say "- You can look at the following Dangerfiles to get some more ideas:"
ui.pause 0.6
ui.link "https://github.com/danger/danger/blob/master/Dangerfile"
ui.link "https://github.com/artsy/eigen/blob/master/Dangerfile"
ui.pause 1
end
def thanks
ui.say "\n\n🎉"
ui.pause 0.6
ui.say "And you're set. Danger is a collaboration between Orta Therox, Gem 'Danger' McShane and Felix Krause."
ui.say "If you like it, let others know. If you want to know more, follow " + "@orta".yellow + " and " + "@KrauseFx".yellow + " on Twitter."
ui.say "If you don't like it, help us improve it! xxx"
end
end
end
|
# Copyright 2006-2008 by Mike Bailey. All rights reserved.
Capistrano::Configuration.instance(:must_exist).load do
namespace :centos do namespace :monit do
set :monit_user, 'monit'
set :monit_group, 'monit'
set :monit_confd_dir, '/etc/monit.d'
set :monit_check_interval, 60
set :monit_log, 'syslog facility log_daemon'
set :monit_mailserver, nil
set :monit_mail_from, 'monit@deprec.enabled.slice'
set :monit_alert_recipients, %w(root@localhost)
set :monit_timeout_recipients, %w(root@localhost)
set :monit_webserver_enabled, true
set :monit_webserver_port, 2812
set :monit_webserver_address, 'localhost'
set :monit_webserver_allowed_hosts_and_networks, %w(localhost)
set :monit_webserver_auth_user, 'admin'
set :monit_webserver_auth_pass, 'monit'
# Upstream changes: http://www.tildeslash.com/monit/dist/CHANGES.txt
# rpmforge has packages of monit 4.9.2, let's use it instead of newest
# version from sources
=begin
SRC_PACKAGES[:monit] = {
:filename => 'monit-4.10.1.tar.gz',
:md5sum => "d3143b0bbd79b53f1b019d2fc1dae656 monit-4.10.1.tar.gz",
:dir => 'monit-4.10.1',
:url => "http://www.tildeslash.com/monit/dist/monit-4.10.1.tar.gz",
:unpack => "tar zxf monit-4.10.1.tar.gz;",
:configure => %w(
./configure
;
).reject{|arg| arg.match '#'}.join(' '),
:make => 'make;',
:install => 'make install;'
}
=end
desc "Install monit"
task :install do
install_deps
yum.enable_repository(:rpmforge)
apt.install( {:base => %w(monit)}, :stable )
#deprec2.download_src(SRC_PACKAGES[:monit], src_dir)
#deprec2.install_from_src(SRC_PACKAGES[:monit], src_dir)
activate
end
# install dependencies for monit
task :install_deps do
apt.install( {:base => %w(flex bison openssl openssl-devel)}, :stable )
end
SYSTEM_CONFIG_FILES[:monit] = [
{:template => 'monit-init-script',
:path => '/etc/init.d/monit',
:mode => 0755,
:owner => 'root:root'},
{:template => 'monitrc.erb',
:path => "/etc/monitrc",
:mode => 0700,
:owner => 'root:root'},
{:template => 'nothing',
:path => "/etc/monit.d/nothing",
:mode => 0700,
:owner => 'root:root'}
]
desc <<-DESC
Generate nginx config from template. Note that this does not
push the config to the server, it merely generates required
configuration files. These should be kept under source control.
The can be pushed to the server with the :config task.
DESC
task :config_gen do
SYSTEM_CONFIG_FILES[:monit].each do |file|
deprec2.render_template(:monit, file)
end
end
desc "Push monit config files to server"
task :config do
deprec2.push_configs(:monit, SYSTEM_CONFIG_FILES[:monit])
end
desc "Start Monit"
task :start, :roles => :app do
send(run_method, "/etc/init.d/monit start")
end
desc "Stop Monit"
task :stop, :roles => :app do
send(run_method, "/etc/init.d/monit stop")
end
desc "Restart Monit"
task :restart, :roles => :app do
send(run_method, "/etc/init.d/monit restart")
end
desc "Reload Monit"
task :reload, :roles => :app do
send(run_method, "/etc/init.d/monit reload")
end
desc <<-DESC
Activate monit start scripts on server.
Setup server to start monit on boot.
DESC
task :activate do
# TODO: service monit does not support chkconfig
# send(run_method, "/sbin/chkconfig --add monit")
# send(run_method, "/sbin/chkconfig --level 45 monit on")
end
desc <<-DESC
Dectivate monit start scripts on server.
Setup server to start monit on boot.
DESC
task :deactivate do
send(run_method, "/sbin/chkconfig --del monit")
end
task :backup do
# there's nothing to backup for monit
end
task :restore do
# there's nothing to restore for monit
end
end end
end
Updates from deprec2: removed call to :activate from :install task. The init script is currently copied out by the :config task however this is not run by :install. [Mike Bailey]
# Copyright 2006-2008 by Mike Bailey. All rights reserved.
Capistrano::Configuration.instance(:must_exist).load do
namespace :centos do namespace :monit do
set :monit_user, 'monit'
set :monit_group, 'monit'
set :monit_confd_dir, '/etc/monit.d'
set :monit_check_interval, 60
set :monit_log, 'syslog facility log_daemon'
set :monit_mailserver, nil
set :monit_mail_from, 'monit@deprec.enabled.slice'
set :monit_alert_recipients, %w(root@localhost)
set :monit_timeout_recipients, %w(root@localhost)
set :monit_webserver_enabled, true
set :monit_webserver_port, 2812
set :monit_webserver_address, 'localhost'
set :monit_webserver_allowed_hosts_and_networks, %w(localhost)
set :monit_webserver_auth_user, 'admin'
set :monit_webserver_auth_pass, 'monit'
# Upstream changes: http://www.tildeslash.com/monit/dist/CHANGES.txt
# rpmforge has packages of monit 4.9.2, let's use it instead of newest
# version from sources
=begin
SRC_PACKAGES[:monit] = {
:filename => 'monit-4.10.1.tar.gz',
:md5sum => "d3143b0bbd79b53f1b019d2fc1dae656 monit-4.10.1.tar.gz",
:dir => 'monit-4.10.1',
:url => "http://www.tildeslash.com/monit/dist/monit-4.10.1.tar.gz",
:unpack => "tar zxf monit-4.10.1.tar.gz;",
:configure => %w(
./configure
;
).reject{|arg| arg.match '#'}.join(' '),
:make => 'make;',
:install => 'make install;'
}
=end
desc "Install monit"
task :install do
install_deps
yum.enable_repository(:rpmforge)
apt.install( {:base => %w(monit)}, :stable )
#deprec2.download_src(SRC_PACKAGES[:monit], src_dir)
#deprec2.install_from_src(SRC_PACKAGES[:monit], src_dir)
end
# install dependencies for monit
task :install_deps do
apt.install( {:base => %w(flex bison openssl openssl-devel)}, :stable )
end
SYSTEM_CONFIG_FILES[:monit] = [
{:template => 'monit-init-script',
:path => '/etc/init.d/monit',
:mode => 0755,
:owner => 'root:root'},
{:template => 'monitrc.erb',
:path => "/etc/monitrc",
:mode => 0700,
:owner => 'root:root'},
{:template => 'nothing',
:path => "/etc/monit.d/nothing",
:mode => 0700,
:owner => 'root:root'}
]
desc <<-DESC
Generate nginx config from template. Note that this does not
push the config to the server, it merely generates required
configuration files. These should be kept under source control.
The can be pushed to the server with the :config task.
DESC
task :config_gen do
SYSTEM_CONFIG_FILES[:monit].each do |file|
deprec2.render_template(:monit, file)
end
end
desc "Push monit config files to server"
task :config do
deprec2.push_configs(:monit, SYSTEM_CONFIG_FILES[:monit])
end
desc "Start Monit"
task :start, :roles => :app do
send(run_method, "/etc/init.d/monit start")
end
desc "Stop Monit"
task :stop, :roles => :app do
send(run_method, "/etc/init.d/monit stop")
end
desc "Restart Monit"
task :restart, :roles => :app do
send(run_method, "/etc/init.d/monit restart")
end
desc "Reload Monit"
task :reload, :roles => :app do
send(run_method, "/etc/init.d/monit reload")
end
desc <<-DESC
Activate monit start scripts on server.
Setup server to start monit on boot.
DESC
task :activate do
# TODO: service monit does not support chkconfig
# send(run_method, "/sbin/chkconfig --add monit")
# send(run_method, "/sbin/chkconfig --level 45 monit on")
end
desc <<-DESC
Dectivate monit start scripts on server.
Setup server to start monit on boot.
DESC
task :deactivate do
send(run_method, "/sbin/chkconfig --del monit")
end
task :backup do
# there's nothing to backup for monit
end
task :restore do
# there's nothing to restore for monit
end
end end
end
|
Capistrano::Configuration.instance(:must_exist).load do
namespace :deprec do namespace :nginx do
set :nginx_server_name, nil
# Configuration summary
# + threads are not used
# + using system PCRE library
# + OpenSSL library is not used
# + md5 library is not used
# + sha1 library is not used
# + using system zlib library
#
# nginx path prefix: "/usr/local/nginx"
# nginx binary file: "/usr/local/nginx/sbin/nginx"
# nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
# nginx pid file: "/usr/local/nginx/logs/nginx.pid"
# nginx error log file: "/usr/local/nginx/logs/error.log"
# nginx http access log file: "/usr/local/nginx/logs/access.log"
# nginx http client request body temporary files: "/usr/local/nginx/client_body_temp"
# nginx http proxy temporary files: "/usr/local/nginx/proxy_temp"
# nginx http fastcgi temporary files: "/usr/local/nginx/fastcgi_temp"
# http://sysoev.ru/nginx/nginx-0.5.33.tar.gz
desc "Install nginx"
task :install do
version = 'nginx-0.5.33'
set :src_package, {
:file => version + '.tar.gz',
:md5sum => "a78be74b4fd8e009545ef02488fcac86 #{version}.tar.gz",
:dir => version,
:url => "http://sysoev.ru/nginx/#{version}.tar.gz",
:unpack => "tar zxf #{version}.tar.gz;",
:configure => %w(
./configure
--with-http_ssl_module
--with-http_dav_module
;
).reject{|arg| arg.match '#'}.join(' '),
:make => 'make;',
:install => 'make install;',
:post_install => ''
}
install_deps
deprec2.download_src(src_package, src_dir)
deprec2.install_from_src(src_package, src_dir)
end
# install dependencies for apache
task :install_deps do
puts "This function should be overridden by your OS plugin!"
apt.install( {:base => %w(build-essential zlib1g-dev zlib1g openssl libssl-dev libpcre3-dev libgcrypt11-dev)}, :stable )
end
SYSTEM_CONFIG_FILES[:nginx] = [
{:template => 'nginx-init-gutsy',
:path => '/etc/init.d/nginx',
:mode => '0755',
:owner => 'root:root'},
{:template => 'nginx.conf-gutsy.erb',
:path => "/usr/local/nginx/conf/nginx.conf",
:mode => '0644',
:owner => 'root:root'}
]
PROJECT_CONFIG_FILES[:nginx] = [
]
desc <<-DESC
Generate nginx config from template. Note that this does not
push the config to the server, it merely generates required
configuration files. These should be kept under source control.
The can be pushed to the server with the :config task.
DESC
task :config_gen do
config_gen_system
# config_gen_project
end
task :config_gen_system do
SYSTEM_CONFIG_FILES[:nginx].each do |file|
render_template(:nginx, file)
end
end
# task :config_gen_project do
# PROJECT_CONFIG_FILES[:nginx].each do |file|
# render_template(:nginx, file)
# end
# end
desc "Push trac config files to server"
task :config, :roles => :web do
config_system
# config_project
end
task :config_system, :roles => :web do
deprec2.push_configs(:nginx, SYSTEM_CONFIG_FILES[:nginx])
end
# task :config_project, :roles => :web do
# deprec2.push_configs(:nginx, PROJECT_CONFIG_FILES[:nginx])
# end
desc "Start Nginx"
task :start, :roles => :web do
puts "starting nginx"
end
desc "Stop Nginx"
task :stop, :roles => :web do
puts "stopping nginx"
end
desc "Restart Nginx"
task :restart, :roles => :web do
stop
start
end
desc <<-DESC
Activate nginx start scripts on server.
Setup server to start nginx on boot.
DESC
task :activate, :roles => :web do
end
desc <<-DESC
Dectivate nginx start scripts on server.
Setup server to start nginx on boot.
DESC
task :deactivate, :roles => :web do
end
task :backup, :roles => :web do
# there's nothing to backup for nginx
end
task :restore, :roles => :web do
# there's nothing to store for nginx
end
end end
end
ready to use
git-svn-id: 0d33e6f6e41b2d8f20308dc5448449f229f93212@264 479ab18a-db23-0410-b897-fa3724b950b0
Capistrano::Configuration.instance(:must_exist).load do
namespace :deprec do namespace :nginx do
set :nginx_server_name, nil
set :nginx_user, 'nginx'
set :nginx_group, 'nginx'
# Configuration summary
# + threads are not used
# + using system PCRE library
# + OpenSSL library is not used
# + md5 library is not used
# + sha1 library is not used
# + using system zlib library
#
# nginx path prefix: "/usr/local/nginx"
# nginx binary file: "/usr/local/nginx/sbin/nginx"
# nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
# nginx pid file: "/usr/local/nginx/logs/nginx.pid"
# nginx error log file: "/usr/local/nginx/logs/error.log"
# nginx http access log file: "/usr/local/nginx/logs/access.log"
# nginx http client request body temporary files: "/usr/local/nginx/client_body_temp"
# nginx http proxy temporary files: "/usr/local/nginx/proxy_temp"
# nginx http fastcgi temporary files: "/usr/local/nginx/fastcgi_temp"
SRC_PACKAGES[:nginx] = {
:filename => 'nginx-0.5.34.tar.gz',
:md5sum => "8f7d3efcd7caaf1f06e4d95dfaeac238 nginx-0.5.34.tar.gz",
:dir => 'nginx-0.5.34',
:url => "http://sysoev.ru/nginx/nginx-0.5.34.tar.gz",
:unpack => "tar zxf nginx-0.5.34.tar.gz;",
:configure => %w(
./configure
--sbin-path=/usr/local/sbin
--with-http_ssl_module
;
).reject{|arg| arg.match '#'}.join(' '),
:make => 'make;',
:install => 'make install;'
}
desc "Install nginx"
task :install do
install_deps
deprec2.download_src(SRC_PACKAGES[:nginx], src_dir)
deprec2.install_from_src(SRC_PACKAGES[:nginx], src_dir)
create_nginx_user
# setup_vhost_dir # XXX not done yet
# install_index_page # XXX not done yet
end
# install dependencies for nginx
task :install_deps do
apt.install( {:base => %w(libpcre3 libpcre3-dev libpcrecpp0 libssl-dev zlib1g-dev)}, :stable )
# do we need libgcrypt11-dev?
end
task :create_nginx_user do
deprec2.groupadd(nginx_group)
deprec2.useradd(nginx_user, :group => nginx_group, :homedir => false)
end
SYSTEM_CONFIG_FILES[:nginx] = [
{:template => 'nginx-init-script',
:path => '/etc/init.d/nginx',
:mode => '0755',
:owner => 'root:root'},
{:template => 'nginx.conf.erb',
:path => "/usr/local/nginx/conf/nginx.conf",
:mode => '0644',
:owner => 'root:root'},
{:template => 'mime.types.erb',
:path => "/usr/local/nginx/conf/mime.types",
:mode => '0644',
:owner => 'root:root'}
]
PROJECT_CONFIG_FILES[:nginx] = [
]
desc <<-DESC
Generate nginx config from template. Note that this does not
push the config to the server, it merely generates required
configuration files. These should be kept under source control.
The can be pushed to the server with the :config task.
DESC
task :config_gen do
SYSTEM_CONFIG_FILES[:nginx].each do |file|
deprec2.render_template(:nginx, file)
end
end
# task :config_gen_project do
# PROJECT_CONFIG_FILES[:nginx].each do |file|
# render_template(:nginx, file)
# end
# end
desc "Push trac config files to server"
task :config, :roles => :web do
deprec2.push_configs(:nginx, SYSTEM_CONFIG_FILES[:nginx])
end
desc "Start Nginx"
task :start, :roles => :web do
send(run_method, "/etc/init.d/nginx start")
end
desc "Stop Nginx"
task :stop, :roles => :web do
send(run_method, "/etc/init.d/nginx stop")
end
desc "Restart Nginx"
task :restart, :roles => :web do
send(run_method, "/etc/init.d/nginx restart")
end
desc "Reload Nginx"
task :reload, :roles => :web do
send(run_method, "/etc/init.d/nginx reload")
end
desc <<-DESC
Activate nginx start scripts on server.
Setup server to start nginx on boot.
DESC
task :activate, :roles => :web do
send(run_method, "update-rc.d nginx defaults")
end
desc <<-DESC
Dectivate nginx start scripts on server.
Setup server to start nginx on boot.
DESC
task :deactivate, :roles => :web do
send(run_method, "update-rc.d -f nginx remove")
end
task :backup, :roles => :web do
# there's nothing to backup for nginx
end
task :restore, :roles => :web do
# there's nothing to store for nginx
end
end end
end |
require 'devise_userbin/strategy'
module Devise
module Models
module Userbin
extend ActiveSupport::Concern
::Userbin.config.app_id = Devise.userbin_app_id
::Userbin.config.api_secret = Devise.userbin_api_secret
included do
attr_reader :password, :current_password
attr_accessor :password_confirmation
before_create do
begin
user = ::Userbin::User.create(email: email, password: password)
self.userbin_id = user.id
rescue ::Userbin::Error => error
self.errors[:base] << error.to_s
false
end
end
end
def password=(new_password)
@password = new_password
end
module ClassMethods
def find_for_userbin_authentication(attributes={}, password)
begin
user = ::Userbin::User.authenticate(
'credentials[email]' => attributes[:email],
'credentials[password]' => password
)
rescue ::Userbin::Error => error
return
end
to_adapter.find_first(
devise_parameter_filter.filter({userbin_id: user.id}))
end
end
end
end
end
No special handling of password needed
require 'devise_userbin/strategy'
module Devise
module Models
module Userbin
extend ActiveSupport::Concern
::Userbin.config.app_id = Devise.userbin_app_id
::Userbin.config.api_secret = Devise.userbin_api_secret
included do
attr_reader :current_password
attr_accessor :password, :password_confirmation
before_create do
begin
user = ::Userbin::User.create(email: email, password: password)
self.userbin_id = user.id
rescue ::Userbin::Error => error
self.errors[:base] << error.to_s
false
end
end
end
module ClassMethods
def find_for_userbin_authentication(attributes={}, password)
begin
user = ::Userbin::User.authenticate(
'credentials[email]' => attributes[:email],
'credentials[password]' => password
)
rescue ::Userbin::Error => error
return
end
to_adapter.find_first(
devise_parameter_filter.filter({userbin_id: user.id}))
end
end
end
end
end
|
require "delegate"
require "did_you_mean/levenshtein"
require "did_you_mean/jaro_winkler"
module DidYouMean
module BaseFinder
AT = "@".freeze
EMPTY = "".freeze
def suggestions
@suggestions ||= searches.flat_map do |input, candidates|
input = MemoizingString.new(normalize(input))
threshold = input.length > 3 ? 0.834 : 0.77
seed = candidates.select {|candidate| JaroWinkler.distance(normalize(candidate), input) >= threshold }
.sort_by! {|candidate| JaroWinkler.distance(candidate.to_s, input) }
.reverse!
# Correct mistypes
threshold = (input.length * 0.25).ceil
corrections = seed.select {|c| Levenshtein.distance(normalize(c), input) <= threshold }
# Correct misspells
if corrections.empty?
corrections = seed.select do |candidate|
candidate = normalize(candidate)
length = input.length < candidate.length ? input.length : candidate.length
Levenshtein.distance(candidate, input) < length
end.first(1)
end
corrections
end
end
def searches
raise NotImplementedError
end
private
def normalize(str_or_symbol) #:nodoc:
str = if str_or_symbol.is_a?(String)
str_or_symbol.downcase
else
str = str_or_symbol.to_s
str.downcase!
str
end
str.tr!(AT, EMPTY)
str
end
class MemoizingString < SimpleDelegator #:nodoc:
def length; @length ||= super; end
def codepoints; @codepoints ||= super; end
end
private_constant :MemoizingString
end
class NullFinder
def initialize(*); end
def suggestions; [] end
end
end
require 'did_you_mean/finders/name_error_finders'
require 'did_you_mean/finders/method_finder'
Remove MemoizingString
The jaro_winkler gem doesn't like it and it just impacts
performance. The memory usage will increase, but let's just focus on
speed for now.
require "did_you_mean/levenshtein"
require "did_you_mean/jaro_winkler"
module DidYouMean
module BaseFinder
AT = "@".freeze
EMPTY = "".freeze
def suggestions
@suggestions ||= searches.flat_map do |input, candidates|
input = normalize(input)
threshold = input.length > 3 ? 0.834 : 0.77
seed = candidates.select {|candidate| JaroWinkler.distance(normalize(candidate), input) >= threshold }
.sort_by! {|candidate| JaroWinkler.distance(candidate.to_s, input) }
.reverse!
# Correct mistypes
threshold = (input.length * 0.25).ceil
corrections = seed.select {|c| Levenshtein.distance(normalize(c), input) <= threshold }
# Correct misspells
if corrections.empty?
corrections = seed.select do |candidate|
candidate = normalize(candidate)
length = input.length < candidate.length ? input.length : candidate.length
Levenshtein.distance(candidate, input) < length
end.first(1)
end
corrections
end
end
def searches
raise NotImplementedError
end
private
def normalize(str_or_symbol) #:nodoc:
str = if str_or_symbol.is_a?(String)
str_or_symbol.downcase
else
str = str_or_symbol.to_s
str.downcase!
str
end
str.tr!(AT, EMPTY)
str
end
end
class NullFinder
def initialize(*); end
def suggestions; [] end
end
end
require 'did_you_mean/finders/name_error_finders'
require 'did_you_mean/finders/method_finder'
|
module DidYouMean
VERSION = "0.10.0"
end
Version bump to 1.0.0.alpha
module DidYouMean
VERSION = "1.0.0.alpha"
end
|
module Diffy
class HtmlFormatter
def initialize(diff, options = {})
@diff = diff
@options = options
end
def to_s
if @options[:highlight_words]
wrap_lines(highlighted_words)
else
wrap_lines(@diff.map{|line| wrap_line(ERB::Util.h(line))})
end
end
private
def wrap_line(line)
cleaned = clean_line(line)
case line
when /^(---|\+\+\+|\\\\)/
' <li class="diff-comment"><span>' + line.chomp + '</span></li>'
when /^\+/
' <li class="ins"><ins>' + cleaned + '</ins></li>'
when /^-/
' <li class="del"><del>' + cleaned + '</del></li>'
when /^ /
' <li class="unchanged"><span>' + cleaned + '</span></li>'
when /^@@/
' <li class="diff-block-info"><span>' + line.chomp + '</span></li>'
end
end
# remove +/- or wrap in html
def clean_line(line)
if @options[:include_plus_and_minus_in_html]
line.sub(/^(.)/, '<span class="symbol">\1</span>')
else
line.sub(/^./, '')
end.chomp
end
def wrap_lines(lines)
if lines.empty?
%'<div class="diff"></div>'
else
%'<div class="diff">\n <ul>\n#{lines.join("\n")}\n </ul>\n</div>\n'
end
end
def highlighted_words
chunks = @diff.each_chunk.
reject{|c| c == '\ No newline at end of file'"\n"}
processed = []
lines = chunks.each_with_index.map do |chunk1, index|
next if processed.include? index
processed << index
chunk1 = chunk1
chunk2 = chunks[index + 1]
if not chunk2
next ERB::Util.h(chunk1)
end
dir1 = chunk1.each_char.first
dir2 = chunk2.each_char.first
case [dir1, dir2]
when ['-', '+']
if chunk1.each_char.take(3).join("") =~ /^(---|\+\+\+|\\\\)/ and
chunk2.each_char.take(3).join("") =~ /^(---|\+\+\+|\\\\)/
ERB::Util.h(chunk1)
else
line_diff = Diffy::Diff.new(
split_characters(chunk1),
split_characters(chunk2)
)
hi1 = reconstruct_characters(line_diff, '-')
hi2 = reconstruct_characters(line_diff, '+')
processed << (index + 1)
[hi1, hi2]
end
else
ERB::Util.h(chunk1)
end
end.flatten
lines.map{|line| line.each_line.map(&:chomp).to_a if line }.flatten.compact.
map{|line|wrap_line(line) }.compact
end
def split_characters(chunk)
chunk.gsub(/^./, '').each_line.map do |line|
chars = line.sub(/([\r\n]$)/, '').split('')
# add escaped newlines
chars += [($1 || "\n").gsub("\r", '\r').gsub("\n", '\n')]
chars.map{|chr| ERB::Util.h(chr) }
end.flatten.join("\n") + "\n"
end
def reconstruct_characters(line_diff, type)
enum = line_diff.each_chunk
enum.each_with_index.map do |l, i|
re = /(^|\\n)#{Regexp.escape(type)}/
case l
when re
highlight(l)
when /^ /
if i > 1 and enum.to_a[i+1] and l.each_line.to_a.size < 4
highlight(l)
else
l.gsub(/^./, '').gsub("\n", '').
gsub('\r', "\r").gsub('\n', "\n")
end
end
end.join('').split("\n").map do |l|
type + l.gsub('</strong><strong>' , '')
end
end
def highlight(lines)
"<strong>" +
lines.
# strip diff tokens (e.g. +,-,etc.)
gsub(/(^|\\n)./, '').
# mark line boundaries from higher level line diff
# html is all escaped so using brackets should make this safe.
gsub('\n', '<LINE_BOUNDARY>').
# join characters back by stripping out newlines
gsub("\n", '').
# close and reopen strong tags. we don't want inline elements
# spanning block elements which get added later.
gsub('<LINE_BOUNDARY>',"</strong>\n<strong>") + "</strong>"
end
end
end
Show differences in windows and unix newlines in html format
This resolves an issue in rubinius due to it's different handling of the
$1 regexp match variable. This hadn't been working like I'd thought it
was.
module Diffy
class HtmlFormatter
def initialize(diff, options = {})
@diff = diff
@options = options
end
def to_s
if @options[:highlight_words]
wrap_lines(highlighted_words)
else
wrap_lines(@diff.map{|line| wrap_line(ERB::Util.h(line))})
end
end
private
def wrap_line(line)
cleaned = clean_line(line)
case line
when /^(---|\+\+\+|\\\\)/
' <li class="diff-comment"><span>' + line.chomp + '</span></li>'
when /^\+/
' <li class="ins"><ins>' + cleaned + '</ins></li>'
when /^-/
' <li class="del"><del>' + cleaned + '</del></li>'
when /^ /
' <li class="unchanged"><span>' + cleaned + '</span></li>'
when /^@@/
' <li class="diff-block-info"><span>' + line.chomp + '</span></li>'
end
end
# remove +/- or wrap in html
def clean_line(line)
if @options[:include_plus_and_minus_in_html]
line.sub(/^(.)/, '<span class="symbol">\1</span>')
else
line.sub(/^./, '')
end.chomp
end
def wrap_lines(lines)
if lines.empty?
%'<div class="diff"></div>'
else
%'<div class="diff">\n <ul>\n#{lines.join("\n")}\n </ul>\n</div>\n'
end
end
def highlighted_words
chunks = @diff.each_chunk.
reject{|c| c == '\ No newline at end of file'"\n"}
processed = []
lines = chunks.each_with_index.map do |chunk1, index|
next if processed.include? index
processed << index
chunk1 = chunk1
chunk2 = chunks[index + 1]
if not chunk2
next ERB::Util.h(chunk1)
end
dir1 = chunk1.each_char.first
dir2 = chunk2.each_char.first
case [dir1, dir2]
when ['-', '+']
if chunk1.each_char.take(3).join("") =~ /^(---|\+\+\+|\\\\)/ and
chunk2.each_char.take(3).join("") =~ /^(---|\+\+\+|\\\\)/
ERB::Util.h(chunk1)
else
line_diff = Diffy::Diff.new(
split_characters(chunk1),
split_characters(chunk2)
)
hi1 = reconstruct_characters(line_diff, '-')
hi2 = reconstruct_characters(line_diff, '+')
processed << (index + 1)
[hi1, hi2]
end
else
ERB::Util.h(chunk1)
end
end.flatten
lines.map{|line| line.each_line.map(&:chomp).to_a if line }.flatten.compact.
map{|line|wrap_line(line) }.compact
end
def split_characters(chunk)
chunk.gsub(/^./, '').each_line.map do |line|
chars = line.sub(/([\r\n]$)/, '').split('')
# add escaped newlines
chars << '\n'
chars.map{|chr| ERB::Util.h(chr) }
end.flatten.join("\n") + "\n"
end
def reconstruct_characters(line_diff, type)
enum = line_diff.each_chunk
enum.each_with_index.map do |l, i|
re = /(^|\\n)#{Regexp.escape(type)}/
case l
when re
highlight(l)
when /^ /
if i > 1 and enum.to_a[i+1] and l.each_line.to_a.size < 4
highlight(l)
else
l.gsub(/^./, '').gsub("\n", '').
gsub('\r', "\r").gsub('\n', "\n")
end
end
end.join('').split("\n").map do |l|
type + l.gsub('</strong><strong>' , '')
end
end
def highlight(lines)
"<strong>" +
lines.
# strip diff tokens (e.g. +,-,etc.)
gsub(/(^|\\n)./, '').
# mark line boundaries from higher level line diff
# html is all escaped so using brackets should make this safe.
gsub('\n', '<LINE_BOUNDARY>').
# join characters back by stripping out newlines
gsub("\n", '').
# close and reopen strong tags. we don't want inline elements
# spanning block elements which get added later.
gsub('<LINE_BOUNDARY>',"</strong>\n<strong>") + "</strong>"
end
end
end
|
module Dingtalk
module Api
class Message < Base
def send_with(params)
http_post('send', params)
end
private
def base_url
'message'
end
end
end
end
Add access_token to message send with url
module Dingtalk
module Api
class Message < Base
def send_with(params)
http_post("send?access_token=#{access_token}", params)
end
private
def base_url
'message'
end
end
end
end
|
module DataMapper
module Associations
include Extlib::Assertions
extend Chainable
class UnsavedParentError < RuntimeError; end
# Initializes relationships hash for extended model
# class.
#
# When model calls has n, has 1 or belongs_to, relationships
# are stored in that hash: keys are repository names and
# values are relationship sets.
#
# @api private
def self.extended(model)
model.instance_variable_set(:@relationships, {})
end
chainable do
# When DataMapper model is inherited, relationships
# of parent are duplicated and copied to subclass model
#
# @api private
def inherited(target)
# TODO: Create a RelationshipSet class, and then add a method that allows copying the relationships to the supplied repository and model
duped_relationships = {}
@relationships.each do |repository_name, relationships|
duped_relationship = duped_relationships[repository_name] ||= Mash.new
relationships.each do |name, relationship|
dup = relationship.dup
[ :@child_model, :@parent_mode ].each do |ivar|
if dup.instance_variable_defined?(ivar) && dup.instance_variable_get(ivar) == self
dup.instance_variable_set(ivar, target)
end
end
duped_relationship[name] = dup
end
end
target.instance_variable_set(:@relationships, duped_relationships)
super
end
end
##
# Returns all relationships that are many-to-one for this model.
#
# Used to find the relationships that require properties in any Repository.
#
# class Plur
# include DataMapper::Resource
#
# def self.default_repository_name
# :plur_db
# end
#
# repository(:plupp_db) do
# has 1, :plupp
# end
# end
#
# This resource has a many-to-one to the Plupp resource residing in the :plupp_db repository,
# but the Plur resource needs the plupp_id property no matter what repository itself lives in,
# ie we need to create that property when we migrate etc.
#
# Used in Model.properties_with_subclasses
#
# @api private
def many_to_one_relationships
@relationships.values.collect { |r| r.values }.flatten.select { |r| r.child_model == self }
end
# Returns copy of relationships set in given repository.
#
# @param [Symbol] repository_name
# Name of the repository for which relationships set is returned
# @return [Mash] relationships set for given repository
#
# @api semipublic
def relationships(repository_name = default_repository_name)
assert_kind_of 'repository_name', repository_name, Symbol
# TODO: create RelationshipSet#copy that will copy the relationships, but assign the
# new Relationship objects to a supplied repository and model. dup does not really
# do what is needed
@relationships[repository_name] ||= if repository_name == default_repository_name
Mash.new
else
relationships(default_repository_name).dup
end
end
# Used to express unlimited cardinality of association,
# see +has+
def n
1.0/0
end
##
# A shorthand, clear syntax for defining one-to-one, one-to-many and
# many-to-many resource relationships.
#
# * has 1, :friend # one friend
# * has n, :friends # many friends
# * has 1..3, :friends # many friends (at least 1, at most 3)
# * has 3, :friends # many friends (exactly 3)
# * has 1, :friend, :model => 'User' # one friend with the class User
# * has 3, :friends, :through => :friendships # many friends through the friendships relationship
#
# @param cardinality [Integer, Range, Infinity]
# cardinality that defines the association type and constraints
# @param name <Symbol> the name that the association will be referenced by
# @param opts <Hash> an options hash
#
# @option :through[Symbol] A association that this join should go through to form
# a many-to-many association
# @option :model[Model,String] The name of the class to associate with, if omitted
# then the association name is assumed to match the class name
# @option :repository[Symbol]
# name of child model repository
#
# @return [Association::Relationship] the relationship that was
# created to reflect either a one-to-one, one-to-many or many-to-many
# relationship
# @raise [ArgumentError] if the cardinality was not understood. Should be a
# Integer, Range or Infinity(n)
#
# @api public
def has(cardinality, name, options = {})
assert_kind_of 'cardinality', cardinality, Integer, Range, n.class
assert_kind_of 'name', name, Symbol
assert_kind_of 'options', options, Hash
min, max = extract_min_max(cardinality)
options = options.merge(:min => min, :max => max)
assert_valid_options(options)
parent_repository_name = repository.name
options[:child_repository_name] = options.delete(:repository)
options[:parent_repository_name] = parent_repository_name
klass = if options.key?(:through)
ManyToMany::Relationship
elsif options[:max] > 1
OneToMany::Relationship
else
OneToOne::Relationship
end
relationships(parent_repository_name)[name] = klass.new(name, options.delete(:model), self, options)
end
##
# A shorthand, clear syntax for defining many-to-one resource relationships.
#
# * belongs_to :user # many to one user
# * belongs_to :friend, :model => 'User' # many to one friend
# * belongs_to :reference, :repository => :pubmed # association for repository other than default
#
# @param name [Symbol] The name that the association will be referenced by
# @see #has
#
# @option :model[Model,String] The name of the class to associate with, if omitted
# then the association name is assumed to match the class name
#
# @option :repository[Symbol]
# name of child model repository
#
# @return [Association::Relationship] The association created
# should not be accessed directly
#
# @api public
def belongs_to(name, options = {})
assert_kind_of 'name', name, Symbol
assert_kind_of 'options', options, Hash
options = options.dup
assert_valid_options(options)
@_valid_relations = false
child_repository_name = repository.name
options[:child_repository_name] = child_repository_name
options[:parent_repository_name] = options.delete(:repository)
relationships(child_repository_name)[name] = ManyToOne::Relationship.new(name, self, options.delete(:model), options)
end
private
##
# A support method for converting Integer, Range or Infinity values into two
# values representing the minimum and maximum cardinality of the association
#
# @return [Array] A pair of integers, min and max
#
# @api private
def extract_min_max(cardinality)
case cardinality
when Integer then [ cardinality, cardinality ]
when Range then [ cardinality.first, cardinality.last ]
when n then [ 0, n ]
end
end
# Validates options of association method like belongs_to or has:
# verifies types of cardinality bounds, repository, association class,
# keys and possible values of :through option.
#
# @api private
def assert_valid_options(options)
# TODO: update to match Query#assert_valid_options
# - perform options normalization elsewhere
if options.key?(:min) && options.key?(:max)
assert_kind_of 'options[:min]', options[:min], Integer
assert_kind_of 'options[:max]', options[:max], Integer, n.class
if options[:min] == n && options[:max] == n
raise ArgumentError, 'Cardinality may not be n..n. The cardinality specifies the min/max number of results from the association'
elsif options[:min] > options[:max]
raise ArgumentError, "Cardinality min (#{options[:min]}) cannot be larger than the max (#{options[:max]})"
elsif options[:min] < 0
raise ArgumentError, "Cardinality min much be greater than or equal to 0, but was #{options[:min]}"
elsif options[:max] < 1
raise ArgumentError, "Cardinality max much be greater than or equal to 1, but was #{options[:max]}"
end
end
if options.key?(:repository)
assert_kind_of 'options[:repository]', options[:repository], Repository, Symbol
if options[:repository].kind_of?(Repository)
options[:repository] = options[:repository].name
end
end
if options.key?(:class_name)
assert_kind_of 'options[:class_name]', options[:class_name], String
warn '+options[:class_name]+ is deprecated, use :model instead'
options[:model] = options.delete(:class_name)
end
if options.key?(:child_key)
assert_kind_of 'options[:child_key]', options[:child_key], Enumerable
end
if options.key?(:parent_key)
assert_kind_of 'options[:parent_key]', options[:parent_key], Enumerable
end
if options.key?(:through) && options[:through] != Resource
assert_kind_of 'options[:through]', options[:through], Relationship, Symbol, Module
if (through = options[:through]).kind_of?(Symbol)
unless options[:through] = relationships(repository.name)[through]
raise ArgumentError, "through refers to an unknown relationship #{through} in #{self} within the #{repository.name} repository"
end
end
end
if options.key?(:limit)
raise ArgumentError, '+options[:limit]+ should not be specified on a relationship'
end
end
Model.append_extensions self
end # module Associations
end # module DataMapper
Briefly explain how UnsavedParentError is used
module DataMapper
module Associations
include Extlib::Assertions
extend Chainable
# Raised on attempt to operate on collection of child objects
# when parent object is not yet saved.
# For instance, if your article object is not saved,
# but you try to fetch or scope down comments (1:n case), or
# publications (n:m case), operation cannot be completed
# because parent object's keys are not yet persisted,
# and thus there is no FK value to use in the query.
class UnsavedParentError < RuntimeError; end
# Initializes relationships hash for extended model
# class.
#
# When model calls has n, has 1 or belongs_to, relationships
# are stored in that hash: keys are repository names and
# values are relationship sets.
#
# @api private
def self.extended(model)
model.instance_variable_set(:@relationships, {})
end
chainable do
# When DataMapper model is inherited, relationships
# of parent are duplicated and copied to subclass model
#
# @api private
def inherited(target)
# TODO: Create a RelationshipSet class, and then add a method that allows copying the relationships to the supplied repository and model
duped_relationships = {}
@relationships.each do |repository_name, relationships|
duped_relationship = duped_relationships[repository_name] ||= Mash.new
relationships.each do |name, relationship|
dup = relationship.dup
[ :@child_model, :@parent_mode ].each do |ivar|
if dup.instance_variable_defined?(ivar) && dup.instance_variable_get(ivar) == self
dup.instance_variable_set(ivar, target)
end
end
duped_relationship[name] = dup
end
end
target.instance_variable_set(:@relationships, duped_relationships)
super
end
end
##
# Returns all relationships that are many-to-one for this model.
#
# Used to find the relationships that require properties in any Repository.
#
# class Plur
# include DataMapper::Resource
#
# def self.default_repository_name
# :plur_db
# end
#
# repository(:plupp_db) do
# has 1, :plupp
# end
# end
#
# This resource has a many-to-one to the Plupp resource residing in the :plupp_db repository,
# but the Plur resource needs the plupp_id property no matter what repository itself lives in,
# ie we need to create that property when we migrate etc.
#
# Used in Model.properties_with_subclasses
#
# @api private
def many_to_one_relationships
@relationships.values.collect { |r| r.values }.flatten.select { |r| r.child_model == self }
end
# Returns copy of relationships set in given repository.
#
# @param [Symbol] repository_name
# Name of the repository for which relationships set is returned
# @return [Mash] relationships set for given repository
#
# @api semipublic
def relationships(repository_name = default_repository_name)
assert_kind_of 'repository_name', repository_name, Symbol
# TODO: create RelationshipSet#copy that will copy the relationships, but assign the
# new Relationship objects to a supplied repository and model. dup does not really
# do what is needed
@relationships[repository_name] ||= if repository_name == default_repository_name
Mash.new
else
relationships(default_repository_name).dup
end
end
# Used to express unlimited cardinality of association,
# see +has+
def n
1.0/0
end
##
# A shorthand, clear syntax for defining one-to-one, one-to-many and
# many-to-many resource relationships.
#
# * has 1, :friend # one friend
# * has n, :friends # many friends
# * has 1..3, :friends # many friends (at least 1, at most 3)
# * has 3, :friends # many friends (exactly 3)
# * has 1, :friend, :model => 'User' # one friend with the class User
# * has 3, :friends, :through => :friendships # many friends through the friendships relationship
#
# @param cardinality [Integer, Range, Infinity]
# cardinality that defines the association type and constraints
# @param name <Symbol> the name that the association will be referenced by
# @param opts <Hash> an options hash
#
# @option :through[Symbol] A association that this join should go through to form
# a many-to-many association
# @option :model[Model,String] The name of the class to associate with, if omitted
# then the association name is assumed to match the class name
# @option :repository[Symbol]
# name of child model repository
#
# @return [Association::Relationship] the relationship that was
# created to reflect either a one-to-one, one-to-many or many-to-many
# relationship
# @raise [ArgumentError] if the cardinality was not understood. Should be a
# Integer, Range or Infinity(n)
#
# @api public
def has(cardinality, name, options = {})
assert_kind_of 'cardinality', cardinality, Integer, Range, n.class
assert_kind_of 'name', name, Symbol
assert_kind_of 'options', options, Hash
min, max = extract_min_max(cardinality)
options = options.merge(:min => min, :max => max)
assert_valid_options(options)
parent_repository_name = repository.name
options[:child_repository_name] = options.delete(:repository)
options[:parent_repository_name] = parent_repository_name
klass = if options.key?(:through)
ManyToMany::Relationship
elsif options[:max] > 1
OneToMany::Relationship
else
OneToOne::Relationship
end
relationships(parent_repository_name)[name] = klass.new(name, options.delete(:model), self, options)
end
##
# A shorthand, clear syntax for defining many-to-one resource relationships.
#
# * belongs_to :user # many to one user
# * belongs_to :friend, :model => 'User' # many to one friend
# * belongs_to :reference, :repository => :pubmed # association for repository other than default
#
# @param name [Symbol] The name that the association will be referenced by
# @see #has
#
# @option :model[Model,String] The name of the class to associate with, if omitted
# then the association name is assumed to match the class name
#
# @option :repository[Symbol]
# name of child model repository
#
# @return [Association::Relationship] The association created
# should not be accessed directly
#
# @api public
def belongs_to(name, options = {})
assert_kind_of 'name', name, Symbol
assert_kind_of 'options', options, Hash
options = options.dup
assert_valid_options(options)
@_valid_relations = false
child_repository_name = repository.name
options[:child_repository_name] = child_repository_name
options[:parent_repository_name] = options.delete(:repository)
relationships(child_repository_name)[name] = ManyToOne::Relationship.new(name, self, options.delete(:model), options)
end
private
##
# A support method for converting Integer, Range or Infinity values into two
# values representing the minimum and maximum cardinality of the association
#
# @return [Array] A pair of integers, min and max
#
# @api private
def extract_min_max(cardinality)
case cardinality
when Integer then [ cardinality, cardinality ]
when Range then [ cardinality.first, cardinality.last ]
when n then [ 0, n ]
end
end
# Validates options of association method like belongs_to or has:
# verifies types of cardinality bounds, repository, association class,
# keys and possible values of :through option.
#
# @api private
def assert_valid_options(options)
# TODO: update to match Query#assert_valid_options
# - perform options normalization elsewhere
if options.key?(:min) && options.key?(:max)
assert_kind_of 'options[:min]', options[:min], Integer
assert_kind_of 'options[:max]', options[:max], Integer, n.class
if options[:min] == n && options[:max] == n
raise ArgumentError, 'Cardinality may not be n..n. The cardinality specifies the min/max number of results from the association'
elsif options[:min] > options[:max]
raise ArgumentError, "Cardinality min (#{options[:min]}) cannot be larger than the max (#{options[:max]})"
elsif options[:min] < 0
raise ArgumentError, "Cardinality min much be greater than or equal to 0, but was #{options[:min]}"
elsif options[:max] < 1
raise ArgumentError, "Cardinality max much be greater than or equal to 1, but was #{options[:max]}"
end
end
if options.key?(:repository)
assert_kind_of 'options[:repository]', options[:repository], Repository, Symbol
if options[:repository].kind_of?(Repository)
options[:repository] = options[:repository].name
end
end
if options.key?(:class_name)
assert_kind_of 'options[:class_name]', options[:class_name], String
warn '+options[:class_name]+ is deprecated, use :model instead'
options[:model] = options.delete(:class_name)
end
if options.key?(:child_key)
assert_kind_of 'options[:child_key]', options[:child_key], Enumerable
end
if options.key?(:parent_key)
assert_kind_of 'options[:parent_key]', options[:parent_key], Enumerable
end
if options.key?(:through) && options[:through] != Resource
assert_kind_of 'options[:through]', options[:through], Relationship, Symbol, Module
if (through = options[:through]).kind_of?(Symbol)
unless options[:through] = relationships(repository.name)[through]
raise ArgumentError, "through refers to an unknown relationship #{through} in #{self} within the #{repository.name} repository"
end
end
end
if options.key?(:limit)
raise ArgumentError, '+options[:limit]+ should not be specified on a relationship'
end
end
Model.append_extensions self
end # module Associations
end # module DataMapper
|
# -*- encoding : utf-8 -*-
require File.expand_path('../test_helper', __FILE__)
require 'rack/test'
class SimplisticApp < Sinatra::Base
helpers Sinatra::UrlForHelper, PeijiSan::ViewHelper
include Mocha::API
enable :raise_errors
get '/' do
collection = stub('Artists paginated collection')
collection.stubs(:current_page?).with(1).returns(false)
collection.stubs(:current_page?).with(2).returns(false)
collection.stubs(:page_count).returns(125)
link_to_page(2, collection)
end
end
ENV['RACK_ENV'] = 'test'
describe "A Sinatra app that uses Peiji-San" do
include Rack::Test::Methods
def app
SimplisticApp
end
it "has it's helper module put in place" do
get '/'
last_response.status.must_equal 200
last_response.body.must_equal '<a href="/?page=2&anchor=">2</a>'
end
end
Reword the assertion
# -*- encoding : utf-8 -*-
require File.expand_path('../test_helper', __FILE__)
require 'rack/test'
class SimplisticApp < Sinatra::Base
helpers Sinatra::UrlForHelper, PeijiSan::ViewHelper
include Mocha::API
enable :raise_errors
get '/' do
collection = stub('Artists paginated collection')
collection.stubs(:current_page?).with(1).returns(false)
collection.stubs(:current_page?).with(2).returns(false)
collection.stubs(:page_count).returns(125)
link_to_page(2, collection)
end
end
ENV['RACK_ENV'] = 'test'
describe "A Sinatra app that uses Peiji-San" do
include Rack::Test::Methods
def app
SimplisticApp
end
it "has it's link_to_page method put in place and operational" do
get '/'
last_response.status.must_equal 200
last_response.body.must_equal '<a href="/?page=2&anchor=">2</a>'
end
end
|
module DockerTools
VERSION = "0.0.22"
end
Bump gem version
module DockerTools
VERSION = "0.0.24"
end
|
require 'openssl'
module DocusignRest
class Client
# Define the same set of accessors as the DocusignRest module
attr_accessor *Configuration::VALID_CONFIG_KEYS
attr_accessor :docusign_authentication_headers, :acct_id
def initialize(options={})
# Merge the config values from the module and those passed to the client.
merged_options = DocusignRest.options.merge(options)
# Copy the merged values to this client and ignore those not part
# of our configuration
Configuration::VALID_CONFIG_KEYS.each do |key|
send("#{key}=", merged_options[key])
end
# Set up the DocuSign Authentication headers with the values passed from
# our config block
if access_token.nil?
@docusign_authentication_headers = {
'X-DocuSign-Authentication' => {
'Username' => username,
'Password' => password,
'IntegratorKey' => integrator_key
}.to_json
}
else
@docusign_authentication_headers = {
'Authorization' => "Bearer #{access_token}"
}
end
# Set the account_id from the configure block if present, but can't call
# the instance var @account_id because that'll override the attr_accessor
# that is automatically configured for the configure block
@acct_id = account_id
end
# Internal: sets the default request headers allowing for user overrides
# via options[:headers] from within other requests. Additionally injects
# the X-DocuSign-Authentication header to authorize the request.
#
# Client can pass in header options to any given request:
# headers: {'Some-Key' => 'some/value', 'Another-Key' => 'another/value'}
#
# Then we pass them on to this method to merge them with the other
# required headers
#
# Example:
#
# headers(options[:headers])
#
# Returns a merged hash of headers overriding the default Accept header if
# the user passes in a new 'Accept' header key and adds any other
# user-defined headers along with the X-DocuSign-Authentication headers
def headers(user_defined_headers={})
default = {
'Accept' => 'json' #this seems to get added automatically, so I can probably remove this
}
default.merge!(user_defined_headers) if user_defined_headers
@docusign_authentication_headers.merge(default)
end
# Internal: builds a URI based on the configurable endpoint, api_version,
# and the passed in relative url
#
# url - a relative url requiring a leading forward slash
#
# Example:
#
# build_uri('/login_information')
#
# Returns a parsed URI object
def build_uri(url)
URI.parse("#{endpoint}/#{api_version}#{url}")
end
# Internal: configures Net:HTTP with some default values that are required
# for every request to the DocuSign API
#
# Returns a configured Net::HTTP object into which a request can be passed
def initialize_net_http_ssl(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
if defined?(Rails) && Rails.env.test?
in_rails_test_env = true
else
in_rails_test_env = false
end
if http.use_ssl? && !in_rails_test_env
if ca_file
if File.exists?(ca_file)
http.ca_file = ca_file
else
raise 'Certificate path not found.'
end
end
# Explicitly verifies that the certificate matches the domain.
# Requires that we use www when calling the production DocuSign API
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.verify_depth = 5
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http
end
# Public: creates an OAuth2 authorization server token endpoint.
#
# email - email of user authenticating
# password - password of user authenticating
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.get_token('someone@example.com', 'p@ssw0rd01')
#
# Returns:
# access_token - Access token information
# scope - This should always be "api"
# token_type - This should always be "bearer"
def get_token(account_id, email, password)
content_type = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' }
uri = build_uri('/oauth2/token')
request = Net::HTTP::Post.new(uri.request_uri, content_type)
request.body = "grant_type=password&client_id=#{integrator_key}&username=#{email}&password=#{password}&scope=api"
http = initialize_net_http_ssl(uri)
response = http.request(request)
JSON.parse(response.body)
end
# Public: gets info necessary to make additional requests to the DocuSign API
#
# options - hash of headers if the client wants to override something
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.login_information
# puts response.body
#
# Returns:
# accountId - For the username, password, and integrator_key specified
# baseUrl - The base URL for all future DocuSign requests
# email - The email used when signing up for DocuSign
# isDefault - # TODO identify what this is
# name - The account name provided when signing up for DocuSign
# userId - # TODO determine what this is used for, if anything
# userName - Full name provided when signing up for DocuSign
def get_login_information(options={})
uri = build_uri('/login_information')
request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers]))
http = initialize_net_http_ssl(uri)
http.request(request)
end
# Internal: uses the get_login_information method to determine the client's
# accountId and then caches that value into an instance variable so we
# don't end up hitting the API for login_information more than once per
# request.
#
# This is used by the rake task in lib/tasks/docusign_task.rake to add
# the config/initialzers/docusign_rest.rb file with the proper config block
# which includes the account_id in it. That way we don't require hitting
# the /login_information URI in normal requests
#
# Returns the accountId string
def get_account_id
unless acct_id
response = get_login_information.body
hashed_response = JSON.parse(response)
login_accounts = hashed_response['loginAccounts']
acct_id ||= login_accounts.first['accountId']
end
acct_id
end
# Internal: takes in an array of hashes of signers and concatenates all the
# hashes with commas
#
# embedded - Tells DocuSign if this is an embedded signer which determines
# weather or not to deliver emails. Also lets us authenticate
# them when they go to do embedded signing. Behind the scenes
# this is setting the clientUserId value to the signer's email.
# name - The name of the signer
# email - The email of the signer
# role_name - The role name of the signer ('Attorney', 'Client', etc.).
# tabs - Array of tab pairs grouped by type (Example type: 'textTabs')
# { textTabs: [ { tabLabel: "label", name: "name", value: "value" } ] }
#
# NOTE: The 'tabs' option is NOT supported in 'v1' of the REST API
#
# Returns a hash of users that need to be embedded in the template to
# create an envelope
def get_template_roles(signers)
template_roles = []
signers.each_with_index do |signer, index|
template_role = {
name: signer[:name],
email: signer[:email],
roleName: signer[:role_name],
tabs: {
textTabs: get_signer_tabs(signer[:text_tabs]),
checkboxTabs: get_signer_tabs(signer[:checkbox_tabs]),
numberTabs: get_signer_tabs(signer[:number_tabs]),
fullNameTabs: get_signer_tabs(signer[:fullname_tabs]),
dateTabs: get_signer_tabs(signer[:date_tabs])
}
}
if signer[:email_notification]
template_role[:emailNotification] = signer[:email_notification]
end
template_role['clientUserId'] = (signer[:client_id] || signer[:email]).to_s if signer[:embedded] == true
template_roles << template_role
end
template_roles
end
# TODO (2014-02-03) jonk => document
def get_signer_tabs(tabs)
Array(tabs).map do |tab|
{
'tabLabel' => tab[:label],
'name' => tab[:name],
'value' => tab[:value],
'documentId' => tab[:document_id],
'selected' => tab[:selected]
}
end
end
# TODO (2014-02-03) jonk => document
def get_event_notification(event_notification)
return {} unless event_notification
{
useSoapInterface: event_notification[:use_soap_interface] || false,
includeCertificatWithSoap: event_notification[:include_certificate_with_soap] || false,
url: event_notification[:url],
loggingEnabled: event_notification[:logging],
'EnvelopeEvents' => Array(event_notification[:envelope_events]).map do |envelope_event|
{
includeDocuments: envelope_event[:include_documents] || false,
envelopeEventStatusCode: envelope_event[:envelope_event_status_code]
}
end
}
end
# Internal: takes an array of hashes of signers required to complete a
# document and allows for setting several options. Not all options are
# currently dynamic but that's easy to change/add which I (and I'm
# sure others) will be doing in the future.
#
# template - Includes other optional fields only used when
# being called from a template
# email - The signer's email
# name - The signer's name
# embedded - Tells DocuSign if this is an embedded signer which
# determines weather or not to deliver emails. Also
# lets us authenticate them when they go to do
# embedded signing. Behind the scenes this is setting
# the clientUserId value to the signer's email.
# email_notification - Send an email or not
# role_name - The signer's role, like 'Attorney' or 'Client', etc.
# template_locked - Doesn't seem to work/do anything
# template_required - Doesn't seem to work/do anything
# anchor_string - The string of text to anchor the 'sign here' tab to
# document_id - If the doc you want signed isn't the first doc in
# the files options hash
# page_number - Page number of the sign here tab
# x_position - Distance horizontally from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# y_position - Distance vertically from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# sign_here_tab_text - Instead of 'sign here'. Note: doesn't work
# tab_label - TODO: figure out what this is
def get_signers(signers, options={})
doc_signers = []
signers.each_with_index do |signer, index|
doc_signer = {
email: signer[:email],
name: signer[:name],
accessCode: '',
addAccessCodeToEmail: false,
customFields: nil,
iDCheckConfigurationName: nil,
iDCheckInformationInput: nil,
inheritEmailNotificationConfiguration: false,
note: '',
phoneAuthentication: nil,
recipientAttachment: nil,
recipientId: "#{index + 1}",
requireIdLookup: false,
roleName: signer[:role_name],
routingOrder: index + 1,
socialAuthentications: nil
}
if signer[:email_notification]
doc_signer[:emailNotification] = signer[:email_notification]
end
if signer[:embedded]
doc_signer[:clientUserId] = signer[:client_id] || signer[:email]
end
if options[:template] == true
doc_signer[:templateAccessCodeRequired] = false
doc_signer[:templateLocked] = signer[:template_locked].nil? ? true : signer[:template_locked]
doc_signer[:templateRequired] = signer[:template_required].nil? ? true : signer[:template_required]
end
doc_signer[:autoNavigation] = false
doc_signer[:defaultRecipient] = false
doc_signer[:signatureInfo] = nil
doc_signer[:tabs] = {
approveTabs: nil,
checkboxTabs: get_tabs(signer[:checkbox_tabs], options, index),
companyTabs: nil,
dateSignedTabs: get_tabs(signer[:date_signed_tabs], options, index),
dateTabs: nil,
declineTabs: nil,
emailTabs: get_tabs(signer[:email_tabs], options, index),
envelopeIdTabs: nil,
fullNameTabs: get_tabs(signer[:full_name_tabs], options, index),
listTabs: get_tabs(signer[:list_tabs], options, index),
noteTabs: nil,
numberTabs: nil,
radioGroupTabs: nil,
initialHereTabs: get_tabs(signer[:initial_here_tabs], options.merge!(initial_here_tab: true), index),
signHereTabs: get_tabs(signer[:sign_here_tabs], options.merge!(sign_here_tab: true), index),
signerAttachmentTabs: nil,
ssnTabs: nil,
textTabs: get_tabs(signer[:text_tabs], options, index),
titleTabs: get_tabs(signer[:title_tabs], options, index),
zipTabs: nil
}
# append the fully build string to the array
doc_signers << doc_signer
end
doc_signers
end
# TODO (2014-02-03) jonk => document
def get_tabs(tabs, options, index)
tab_array = []
Array(tabs).map do |tab|
tab_hash = {}
if tab[:anchor_string]
tab_hash[:anchorString] = tab[:anchor_string]
tab_hash[:anchorXOffset] = tab[:anchor_x_offset] || '0'
tab_hash[:anchorYOffset] = tab[:anchor_y_offset] || '0'
tab_hash[:anchorIgnoreIfNotPresent] = tab[:ignore_anchor_if_not_present] || false
tab_hash[:anchorUnits] = 'pixels'
end
tab_hash[:conditionalParentLabel] = nil
tab_hash[:conditionalParentValue] = nil
tab_hash[:documentId] = tab[:document_id] || '1'
tab_hash[:pageNumber] = tab[:page_number] || '1'
tab_hash[:recipientId] = index + 1
tab_hash[:required] = tab[:required] || false
if options[:template] == true
tab_hash[:templateLocked] = tab[:template_locked].nil? ? true : tab[:template_locked]
tab_hash[:templateRequired] = tab[:template_required].nil? ? true : tab[:template_required]
end
if options[:sign_here_tab] == true || options[:initial_here_tab] == true
tab_hash[:scaleValue] = tab_hash[:scaleValue] || 1
end
tab_hash[:xPosition] = tab[:x_position] || '0'
tab_hash[:yPosition] = tab[:y_position] || '0'
tab_hash[:name] = tab[:name] if tab[:name]
tab_hash[:optional] = false
tab_hash[:tabLabel] = tab[:label] || 'Signature 1'
tab_hash[:width] = tab[:width] if tab[:width]
tab_hash[:height] = tab[:height] if tab[:width]
tab_hash[:value] = tab[:value] if tab[:value]
tab_hash[:locked] = tab[:locked] || false
tab_hash[:list_items] = tab[:list_items] if tab[:list_items]
tab_array << tab_hash
end
tab_array
end
# Internal: sets up the file ios array
#
# files - a hash of file params
#
# Returns the properly formatted ios used to build the file_params hash
def create_file_ios(files)
# UploadIO is from the multipart-post gem's lib/composite_io.rb:57
# where it has this documentation:
#
# ********************************************************************
# Create an upload IO suitable for including in the params hash of a
# Net::HTTP::Post::Multipart.
#
# Can take two forms. The first accepts a filename and content type, and
# opens the file for reading (to be closed by finalizer).
#
# The second accepts an already-open IO, but also requires a third argument,
# the filename from which it was opened (particularly useful/recommended if
# uploading directly from a form in a framework, which often save the file to
# an arbitrarily named RackMultipart file in /tmp).
#
# Usage:
#
# UploadIO.new('file.txt', 'text/plain')
# UploadIO.new(file_io, 'text/plain', 'file.txt')
# ********************************************************************
#
# There is also a 4th undocumented argument, opts={}, which allows us
# to send in not only the Content-Disposition of 'file' as required by
# DocuSign, but also the documentId parameter which is required as well
#
ios = []
files.each_with_index do |file, index|
ios << UploadIO.new(
file[:io] || file[:path],
file[:content_type] || 'application/pdf',
file[:name],
'Content-Disposition' => "file; documentid=#{index + 1}"
)
end
ios
end
# Internal: sets up the file_params for inclusion in a multipart post request
#
# ios - An array of UploadIO formatted file objects
#
# Returns a hash of files params suitable for inclusion in a multipart
# post request
def create_file_params(ios)
# multi-doc uploading capabilities, each doc needs to be it's own param
file_params = {}
ios.each_with_index do |io,index|
file_params.merge!("file#{index + 1}" => io)
end
file_params
end
# Internal: takes in an array of hashes of documents and calculates the
# documentId
#
# Returns a hash of documents that are to be uploaded
def get_documents(ios)
ios.each_with_index.map do |io, index|
{
documentId: "#{index + 1}",
name: io.original_filename
}
end
end
# Internal: takes in an array of server template ids and an array of the signers
# and sets up the composite template
#
# Returns an array of server template hashes
def get_composite_template(server_template_ids, signers)
composite_array = []
index = 0
server_template_ids.each do |template_id|
server_template_hash = Hash[:sequence, index += 1, \
:templateId, template_id]
templates_hash = Hash[:serverTemplates, [server_template_hash], \
:inlineTemplates, get_inline_signers(signers, index += 1)]
composite_array << templates_hash
end
composite_array
end
# Internal: takes signer info and the inline template sequence number
# and sets up the inline template
#
# Returns an array of signers
def get_inline_signers(signers, sequence)
signers_array = []
signers.each do |signer|
signers_hash = Hash[:email, signer[:email], :name, signer[:name], \
:recipientId, signer[:recipient_id], :roleName, signer[:role_name], \
:clientUserId, signer[:email]]
signers_array << signers_hash
end
template_hash = Hash[:sequence, sequence, :recipients, { signers: signers_array }]
[template_hash]
end
# Internal sets up the Net::HTTP request
#
# uri - The fully qualified final URI
# post_body - The custom post body including the signers, etc
# file_params - Formatted hash of ios to merge into the post body
# headers - Allows for passing in custom headers
#
# Returns a request object suitable for embedding in a request
def initialize_net_http_multipart_post_request(uri, post_body, file_params, headers)
# Net::HTTP::Post::Multipart is from the multipart-post gem's lib/multipartable.rb
#
# path - The fully qualified URI for the request
# params - A hash of params (including files for uploading and a
# customized request body)
# headers={} - The fully merged, final request headers
# boundary - Optional: you can give the request a custom boundary
#
request = Net::HTTP::Post::Multipart.new(
uri.request_uri,
{ post_body: post_body }.merge(file_params),
headers
)
# DocuSign requires that we embed the document data in the body of the
# JSON request directly so we need to call '.read' on the multipart-post
# provided body_stream in order to serialize all the files into a
# compatible JSON string.
request.body = request.body_stream.read
request
end
# Public: creates an envelope from a document directly without a template
#
# file_io - Optional: an opened file stream of data (if you don't
# want to save the file to the file system as an incremental
# step)
# file_path - Required if you don't provide a file_io stream, this is
# the local path of the file you wish to upload. Absolute
# paths recommended.
# file_name - The name you want to give to the file you are uploading
# content_type - (for the request body) application/json is what DocuSign
# is expecting
# email_subject - (Optional) short subject line for the email
# email_body - (Optional) custom text that will be injected into the
# DocuSign generated email
# signers - A hash of users who should receive the document and need
# to sign it. More info about the options available for
# this method are documented above it's method definition.
# status - Options include: 'sent', 'created', 'voided' and determine
# if the envelope is sent out immediately or stored for
# sending at a later time
# headers - Allows a client to pass in some
#
# Returns a JSON parsed response object containing:
# envelopeId - The envelope's ID
# status - Sent, created, or voided
# statusDateTime - The date/time the envelope was created
# uri - The relative envelope uri
def create_envelope_from_document(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers])
},
status: "#{options[:status]}"
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# Public: allows a template to be dynamically created with several options.
#
# files - An array of hashes of file parameters which will be used
# to create actual files suitable for upload in a multipart
# request.
#
# Options: io, path, name. The io is optional and would
# require creating a file_io object to embed as the first
# argument of any given file hash. See the create_file_ios
# method definition above for more details.
#
# email/body - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# email/subject - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# signers - An array of hashes of signers. See the
# get_signers method definition for options.
# description - The template description
# name - The template name
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the template's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_template(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers], template: true)
},
envelopeTemplateDefinition: {
description: options[:description],
name: options[:name],
pageCount: 1,
password: '',
shared: false
}
}.to_json
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def get_template(template_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/templates/#{template_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', 'created', 'voided' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_id - The id of the template upon which we want to base this
# envelope
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the envelope's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_envelope_from_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
emailBlurb: options[:email][:body],
emailSubject: options[:email][:subject],
templateId: options[:template_id],
eventNotification: get_event_notification(options[:event_notification]),
templateRoles: get_template_roles(options[:signers])
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a composite template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', or 'created' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
# server_template_ids - Array of ids for templates uploaded to DocuSign. Templates
# will be added in the order they appear in the array.
#
# Returns a JSON parsed response body containing the envelope's:
# envelopeId - autogenerated ID provided by Docusign
# uri - the URI where the template is located on the DocuSign servers
# statusDateTime - The date/time the envelope was created
# status - Sent, created, or voided
def create_envelope_from_composite_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
compositeTemplates: get_composite_template(options[:server_template_ids], options[:signers])
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the names specified for a given email address (existing docusign user)
#
# email - the email of the recipient
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the list of names
def get_recipient_names(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/recipient_names?email=#{options[:email]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded signing
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# name - the name of the signer
# email - the email of the recipient
# return_url - the URL you want the user to be directed to after he or she
# completes the document signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded signing (can be put in an iFrame)
def get_recipient_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
authenticationMethod: 'email',
clientUserId: options[:client_id] || options[:email],
email: options[:email],
returnUrl: options[:return_url],
userName: options[:name]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded console
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded console (can be put in an iFrame)
def get_console_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeId: options[:envelope_id]
}.to_json
uri = build_uri("/accounts/#{acct_id}/views/console")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
parsed_response = JSON.parse(response.body)
parsed_response['url']
end
# Public returns the envelope recipients for a given envelope
#
# include_tabs - boolean, determines if the tabs for each signer will be
# returned in the response, defaults to false.
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a hash of detailed info about the envelope including the signer
# hash and status of each signer
def get_envelope_recipients(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
include_tabs = options[:include_tabs] || false
include_extended = options[:include_extended] || false
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope status
#
# envelope_id - ID of the envelope from which the doc will be retrieved
def get_envelope_status(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the statuses of envelopes matching the given query
#
# from_date - Docusign formatted Date/DateTime. Only return items after this date.
#
# to_date - Docusign formatted Date/DateTime. Only return items up to this date.
# Defaults to the time of the call.
#
# from_to_status - The status of the envelope checked for in the from_date - to_date period.
# Defaults to 'changed'
#
# status - The current status of the envelope. Defaults to any status.
#
# Returns an array of hashes containing envelope statuses, ids, and similar information.
def get_envelope_statuses(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
query_params = options.slice(:from_date, :to_date, :from_to_status, :status)
uri = build_uri("/accounts/#{acct_id}/envelopes?#{query_params.to_query}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the attached file from a given envelope
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# document_id - ID of the document to retrieve
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# document_id: 1,
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public retrieves the document infos from a given envelope
#
# envelope_id - ID of the envelope from which document infos are to be retrieved
#
# Returns a hash containing the envelopeId and the envelopeDocuments array
def get_documents_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves a PDF containing the combined content of all
# documents and the certificate for the given envelope.
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_combined_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_combined_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/combined")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public moves the specified envelopes to the given folder
#
# envelope_ids - IDs of the envelopes to be moved
# folder_id - ID of the folder to move the envelopes to
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.move_envelope_to_folder(
# envelope_ids: ["xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"]
# folder_id: "xxxxx-2222xxxxx",
# )
#
# Returns the response.
def move_envelope_to_folder(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeIds: options[:envelope_ids]
}.to_json
uri = build_uri("/accounts/#{acct_id}/folders/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
# Public returns a hash of audit events for a given envelope
#
# envelope_id - ID of the envelope to get audit events from
#
#
# Example
# client.get_envelope_audit_events(
# envelope_id: "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
# )
# Returns a hash of the events that have happened to the envelope.
def get_envelope_audit_events(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/audit_events")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope(s) from a specific folder based on search params.
#
# Option Query Terms(none are required):
# query_params:
# start_position: Integer The position of the folder items to return. This is used for repeated calls, when the number of envelopes returned is too much for one return (calls return 100 envelopes at a time). The default value is 0.
# from_date: date/Time Only return items on or after this date. If no value is provided, the default search is the previous 30 days.
# to_date: date/Time Only return items up to this date. If no value is provided, the default search is to the current date.
# search_text: String The search text used to search the items of the envelope. The search looks at recipient names and emails, envelope custom fields, sender name, and subject.
# status: Status The current status of the envelope. If no value is provided, the default search is all/any status.
# owner_name: username The name of the folder owner.
# owner_email: email The email of the folder owner.
#
# Example
#
# client.search_folder_for_envelopes(
# folder_id: xxxxx-2222xxxxx,
# query_params: {
# search_text: "John Appleseed",
# from_date: '7-1-2011+11:00:00+AM',
# to_date: '7-1-2011+11:00:00+AM',
# status: "completed"
# }
# )
#
def search_folder_for_envelopes(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
q ||= []
options[:query_params].each do |key, val|
q << "#{key}=#{val}"
end
uri = build_uri("/accounts/#{@acct_id}/folders/#{options[:folder_id]}/?#{q.join('&')}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def create_account(options)
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri('/accounts')
post_body = convert_hash_keys(options).to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [k.to_s.camelize(:lower), convert_hash_keys(v)] }]
else
value
end
end
# TODO (2014-02-03) jonk => document
def delete_account(account_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{account_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
response = http.request(request)
json = response.body
json = '{}' if json.nil? || json == ''
JSON.parse(json)
end
# Public: Retrieves a list of available templates
#
# Example
#
# client.get_templates()
#
# Returns a list of the available templates.
def get_templates
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Public: Retrieves a list of templates used in an envelope
#
# Returns templateId, name and uri for each template found.
#
# envelope_id - DS id of envelope with templates.
def get_templates_in_envelope(envelope_id)
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Grabs envelope data.
# Equivalent to the following call in the API explorer:
# Get Envelopev2/accounts/:accountId/envelopes/:envelopeId
#
# envelope_id- DS id of envelope to be retrieved.
def get_envelope(envelope_id)
content_type = { 'Content-Type' => 'application/json' }
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public deletes a recipient for a given envelope
#
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# recipient_id - ID of the recipient to delete
#
# Returns a hash of recipients with an error code for any recipients that
# were not successfully deleted.
def delete_envelope_recipient(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients")
post_body = "{
\"signers\" : [{\"recipientId\" : \"#{options[:recipient_id]}\"}]
}"
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public voids an in-process envelope
#
# envelope_id - ID of the envelope to be voided
# voided_reason - Optional reason for the envelope being voided
#
# Returns the response (success or failure).
def void_envelope(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
"status" =>"voided",
"voidedReason" => options[:voided_reason] || "No reason provided."
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
end
end
JIRA 1973: add custom fields
require 'openssl'
module DocusignRest
class Client
# Define the same set of accessors as the DocusignRest module
attr_accessor *Configuration::VALID_CONFIG_KEYS
attr_accessor :docusign_authentication_headers, :acct_id
def initialize(options={})
# Merge the config values from the module and those passed to the client.
merged_options = DocusignRest.options.merge(options)
# Copy the merged values to this client and ignore those not part
# of our configuration
Configuration::VALID_CONFIG_KEYS.each do |key|
send("#{key}=", merged_options[key])
end
# Set up the DocuSign Authentication headers with the values passed from
# our config block
if access_token.nil?
@docusign_authentication_headers = {
'X-DocuSign-Authentication' => {
'Username' => username,
'Password' => password,
'IntegratorKey' => integrator_key
}.to_json
}
else
@docusign_authentication_headers = {
'Authorization' => "Bearer #{access_token}"
}
end
# Set the account_id from the configure block if present, but can't call
# the instance var @account_id because that'll override the attr_accessor
# that is automatically configured for the configure block
@acct_id = account_id
end
# Internal: sets the default request headers allowing for user overrides
# via options[:headers] from within other requests. Additionally injects
# the X-DocuSign-Authentication header to authorize the request.
#
# Client can pass in header options to any given request:
# headers: {'Some-Key' => 'some/value', 'Another-Key' => 'another/value'}
#
# Then we pass them on to this method to merge them with the other
# required headers
#
# Example:
#
# headers(options[:headers])
#
# Returns a merged hash of headers overriding the default Accept header if
# the user passes in a new 'Accept' header key and adds any other
# user-defined headers along with the X-DocuSign-Authentication headers
def headers(user_defined_headers={})
default = {
'Accept' => 'json' #this seems to get added automatically, so I can probably remove this
}
default.merge!(user_defined_headers) if user_defined_headers
@docusign_authentication_headers.merge(default)
end
# Internal: builds a URI based on the configurable endpoint, api_version,
# and the passed in relative url
#
# url - a relative url requiring a leading forward slash
#
# Example:
#
# build_uri('/login_information')
#
# Returns a parsed URI object
def build_uri(url)
URI.parse("#{endpoint}/#{api_version}#{url}")
end
# Internal: configures Net:HTTP with some default values that are required
# for every request to the DocuSign API
#
# Returns a configured Net::HTTP object into which a request can be passed
def initialize_net_http_ssl(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
if defined?(Rails) && Rails.env.test?
in_rails_test_env = true
else
in_rails_test_env = false
end
if http.use_ssl? && !in_rails_test_env
if ca_file
if File.exists?(ca_file)
http.ca_file = ca_file
else
raise 'Certificate path not found.'
end
end
# Explicitly verifies that the certificate matches the domain.
# Requires that we use www when calling the production DocuSign API
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.verify_depth = 5
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http
end
# Public: creates an OAuth2 authorization server token endpoint.
#
# email - email of user authenticating
# password - password of user authenticating
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.get_token('someone@example.com', 'p@ssw0rd01')
#
# Returns:
# access_token - Access token information
# scope - This should always be "api"
# token_type - This should always be "bearer"
def get_token(account_id, email, password)
content_type = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' }
uri = build_uri('/oauth2/token')
request = Net::HTTP::Post.new(uri.request_uri, content_type)
request.body = "grant_type=password&client_id=#{integrator_key}&username=#{email}&password=#{password}&scope=api"
http = initialize_net_http_ssl(uri)
response = http.request(request)
JSON.parse(response.body)
end
# Public: gets info necessary to make additional requests to the DocuSign API
#
# options - hash of headers if the client wants to override something
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.login_information
# puts response.body
#
# Returns:
# accountId - For the username, password, and integrator_key specified
# baseUrl - The base URL for all future DocuSign requests
# email - The email used when signing up for DocuSign
# isDefault - # TODO identify what this is
# name - The account name provided when signing up for DocuSign
# userId - # TODO determine what this is used for, if anything
# userName - Full name provided when signing up for DocuSign
def get_login_information(options={})
uri = build_uri('/login_information')
request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers]))
http = initialize_net_http_ssl(uri)
http.request(request)
end
# Internal: uses the get_login_information method to determine the client's
# accountId and then caches that value into an instance variable so we
# don't end up hitting the API for login_information more than once per
# request.
#
# This is used by the rake task in lib/tasks/docusign_task.rake to add
# the config/initialzers/docusign_rest.rb file with the proper config block
# which includes the account_id in it. That way we don't require hitting
# the /login_information URI in normal requests
#
# Returns the accountId string
def get_account_id
unless acct_id
response = get_login_information.body
hashed_response = JSON.parse(response)
login_accounts = hashed_response['loginAccounts']
acct_id ||= login_accounts.first['accountId']
end
acct_id
end
# Internal: takes in an array of hashes of signers and concatenates all the
# hashes with commas
#
# embedded - Tells DocuSign if this is an embedded signer which determines
# weather or not to deliver emails. Also lets us authenticate
# them when they go to do embedded signing. Behind the scenes
# this is setting the clientUserId value to the signer's email.
# name - The name of the signer
# email - The email of the signer
# role_name - The role name of the signer ('Attorney', 'Client', etc.).
# tabs - Array of tab pairs grouped by type (Example type: 'textTabs')
# { textTabs: [ { tabLabel: "label", name: "name", value: "value" } ] }
#
# NOTE: The 'tabs' option is NOT supported in 'v1' of the REST API
#
# Returns a hash of users that need to be embedded in the template to
# create an envelope
def get_template_roles(signers)
template_roles = []
signers.each_with_index do |signer, index|
template_role = {
name: signer[:name],
email: signer[:email],
roleName: signer[:role_name],
tabs: {
textTabs: get_signer_tabs(signer[:text_tabs]),
checkboxTabs: get_signer_tabs(signer[:checkbox_tabs]),
numberTabs: get_signer_tabs(signer[:number_tabs]),
fullNameTabs: get_signer_tabs(signer[:fullname_tabs]),
dateTabs: get_signer_tabs(signer[:date_tabs])
}
}
if signer[:email_notification]
template_role[:emailNotification] = signer[:email_notification]
end
template_role['clientUserId'] = (signer[:client_id] || signer[:email]).to_s if signer[:embedded] == true
template_roles << template_role
end
template_roles
end
# TODO (2014-02-03) jonk => document
def get_signer_tabs(tabs)
Array(tabs).map do |tab|
{
'tabLabel' => tab[:label],
'name' => tab[:name],
'value' => tab[:value],
'documentId' => tab[:document_id],
'selected' => tab[:selected]
}
end
end
# TODO (2014-02-03) jonk => document
def get_event_notification(event_notification)
return {} unless event_notification
{
useSoapInterface: event_notification[:use_soap_interface] || false,
includeCertificatWithSoap: event_notification[:include_certificate_with_soap] || false,
url: event_notification[:url],
loggingEnabled: event_notification[:logging],
'EnvelopeEvents' => Array(event_notification[:envelope_events]).map do |envelope_event|
{
includeDocuments: envelope_event[:include_documents] || false,
envelopeEventStatusCode: envelope_event[:envelope_event_status_code]
}
end
}
end
# Internal: takes an array of hashes of signers required to complete a
# document and allows for setting several options. Not all options are
# currently dynamic but that's easy to change/add which I (and I'm
# sure others) will be doing in the future.
#
# template - Includes other optional fields only used when
# being called from a template
# email - The signer's email
# name - The signer's name
# embedded - Tells DocuSign if this is an embedded signer which
# determines weather or not to deliver emails. Also
# lets us authenticate them when they go to do
# embedded signing. Behind the scenes this is setting
# the clientUserId value to the signer's email.
# email_notification - Send an email or not
# role_name - The signer's role, like 'Attorney' or 'Client', etc.
# template_locked - Doesn't seem to work/do anything
# template_required - Doesn't seem to work/do anything
# anchor_string - The string of text to anchor the 'sign here' tab to
# document_id - If the doc you want signed isn't the first doc in
# the files options hash
# page_number - Page number of the sign here tab
# x_position - Distance horizontally from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# y_position - Distance vertically from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# sign_here_tab_text - Instead of 'sign here'. Note: doesn't work
# tab_label - TODO: figure out what this is
def get_signers(signers, options={})
doc_signers = []
signers.each_with_index do |signer, index|
doc_signer = {
email: signer[:email],
name: signer[:name],
accessCode: '',
addAccessCodeToEmail: false,
customFields: nil,
iDCheckConfigurationName: nil,
iDCheckInformationInput: nil,
inheritEmailNotificationConfiguration: false,
note: '',
phoneAuthentication: nil,
recipientAttachment: nil,
recipientId: "#{index + 1}",
requireIdLookup: false,
roleName: signer[:role_name],
routingOrder: index + 1,
socialAuthentications: nil
}
if signer[:email_notification]
doc_signer[:emailNotification] = signer[:email_notification]
end
if signer[:embedded]
doc_signer[:clientUserId] = signer[:client_id] || signer[:email]
end
if options[:template] == true
doc_signer[:templateAccessCodeRequired] = false
doc_signer[:templateLocked] = signer[:template_locked].nil? ? true : signer[:template_locked]
doc_signer[:templateRequired] = signer[:template_required].nil? ? true : signer[:template_required]
end
doc_signer[:autoNavigation] = false
doc_signer[:defaultRecipient] = false
doc_signer[:signatureInfo] = nil
doc_signer[:tabs] = {
approveTabs: nil,
checkboxTabs: get_tabs(signer[:checkbox_tabs], options, index),
companyTabs: nil,
dateSignedTabs: get_tabs(signer[:date_signed_tabs], options, index),
dateTabs: nil,
declineTabs: nil,
emailTabs: get_tabs(signer[:email_tabs], options, index),
envelopeIdTabs: nil,
fullNameTabs: get_tabs(signer[:full_name_tabs], options, index),
listTabs: get_tabs(signer[:list_tabs], options, index),
noteTabs: nil,
numberTabs: nil,
radioGroupTabs: nil,
initialHereTabs: get_tabs(signer[:initial_here_tabs], options.merge!(initial_here_tab: true), index),
signHereTabs: get_tabs(signer[:sign_here_tabs], options.merge!(sign_here_tab: true), index),
signerAttachmentTabs: nil,
ssnTabs: nil,
textTabs: get_tabs(signer[:text_tabs], options, index),
titleTabs: get_tabs(signer[:title_tabs], options, index),
zipTabs: nil
}
# append the fully build string to the array
doc_signers << doc_signer
end
doc_signers
end
# TODO (2014-02-03) jonk => document
def get_tabs(tabs, options, index)
tab_array = []
Array(tabs).map do |tab|
tab_hash = {}
if tab[:anchor_string]
tab_hash[:anchorString] = tab[:anchor_string]
tab_hash[:anchorXOffset] = tab[:anchor_x_offset] || '0'
tab_hash[:anchorYOffset] = tab[:anchor_y_offset] || '0'
tab_hash[:anchorIgnoreIfNotPresent] = tab[:ignore_anchor_if_not_present] || false
tab_hash[:anchorUnits] = 'pixels'
end
tab_hash[:conditionalParentLabel] = nil
tab_hash[:conditionalParentValue] = nil
tab_hash[:documentId] = tab[:document_id] || '1'
tab_hash[:pageNumber] = tab[:page_number] || '1'
tab_hash[:recipientId] = index + 1
tab_hash[:required] = tab[:required] || false
if options[:template] == true
tab_hash[:templateLocked] = tab[:template_locked].nil? ? true : tab[:template_locked]
tab_hash[:templateRequired] = tab[:template_required].nil? ? true : tab[:template_required]
end
if options[:sign_here_tab] == true || options[:initial_here_tab] == true
tab_hash[:scaleValue] = tab_hash[:scaleValue] || 1
end
tab_hash[:xPosition] = tab[:x_position] || '0'
tab_hash[:yPosition] = tab[:y_position] || '0'
tab_hash[:name] = tab[:name] if tab[:name]
tab_hash[:optional] = false
tab_hash[:tabLabel] = tab[:label] || 'Signature 1'
tab_hash[:width] = tab[:width] if tab[:width]
tab_hash[:height] = tab[:height] if tab[:width]
tab_hash[:value] = tab[:value] if tab[:value]
tab_hash[:locked] = tab[:locked] || false
tab_hash[:list_items] = tab[:list_items] if tab[:list_items]
tab_array << tab_hash
end
tab_array
end
# Internal: sets up the file ios array
#
# files - a hash of file params
#
# Returns the properly formatted ios used to build the file_params hash
def create_file_ios(files)
# UploadIO is from the multipart-post gem's lib/composite_io.rb:57
# where it has this documentation:
#
# ********************************************************************
# Create an upload IO suitable for including in the params hash of a
# Net::HTTP::Post::Multipart.
#
# Can take two forms. The first accepts a filename and content type, and
# opens the file for reading (to be closed by finalizer).
#
# The second accepts an already-open IO, but also requires a third argument,
# the filename from which it was opened (particularly useful/recommended if
# uploading directly from a form in a framework, which often save the file to
# an arbitrarily named RackMultipart file in /tmp).
#
# Usage:
#
# UploadIO.new('file.txt', 'text/plain')
# UploadIO.new(file_io, 'text/plain', 'file.txt')
# ********************************************************************
#
# There is also a 4th undocumented argument, opts={}, which allows us
# to send in not only the Content-Disposition of 'file' as required by
# DocuSign, but also the documentId parameter which is required as well
#
ios = []
files.each_with_index do |file, index|
ios << UploadIO.new(
file[:io] || file[:path],
file[:content_type] || 'application/pdf',
file[:name],
'Content-Disposition' => "file; documentid=#{index + 1}"
)
end
ios
end
# Internal: sets up the file_params for inclusion in a multipart post request
#
# ios - An array of UploadIO formatted file objects
#
# Returns a hash of files params suitable for inclusion in a multipart
# post request
def create_file_params(ios)
# multi-doc uploading capabilities, each doc needs to be it's own param
file_params = {}
ios.each_with_index do |io,index|
file_params.merge!("file#{index + 1}" => io)
end
file_params
end
# Internal: takes in an array of hashes of documents and calculates the
# documentId
#
# Returns a hash of documents that are to be uploaded
def get_documents(ios)
ios.each_with_index.map do |io, index|
{
documentId: "#{index + 1}",
name: io.original_filename
}
end
end
# Internal: takes in an array of server template ids and an array of the signers
# and sets up the composite template
#
# Returns an array of server template hashes
def get_composite_template(server_template_ids, signers)
composite_array = []
index = 0
server_template_ids.each do |template_id|
server_template_hash = Hash[:sequence, index += 1, \
:templateId, template_id]
templates_hash = Hash[:serverTemplates, [server_template_hash], \
:inlineTemplates, get_inline_signers(signers, index += 1)]
composite_array << templates_hash
end
composite_array
end
# Internal: takes signer info and the inline template sequence number
# and sets up the inline template
#
# Returns an array of signers
def get_inline_signers(signers, sequence)
signers_array = []
signers.each do |signer|
signers_hash = Hash[:email, signer[:email], :name, signer[:name], \
:recipientId, signer[:recipient_id], :roleName, signer[:role_name], \
:clientUserId, signer[:email]]
signers_array << signers_hash
end
template_hash = Hash[:sequence, sequence, :recipients, { signers: signers_array }]
[template_hash]
end
# Internal sets up the Net::HTTP request
#
# uri - The fully qualified final URI
# post_body - The custom post body including the signers, etc
# file_params - Formatted hash of ios to merge into the post body
# headers - Allows for passing in custom headers
#
# Returns a request object suitable for embedding in a request
def initialize_net_http_multipart_post_request(uri, post_body, file_params, headers)
# Net::HTTP::Post::Multipart is from the multipart-post gem's lib/multipartable.rb
#
# path - The fully qualified URI for the request
# params - A hash of params (including files for uploading and a
# customized request body)
# headers={} - The fully merged, final request headers
# boundary - Optional: you can give the request a custom boundary
#
request = Net::HTTP::Post::Multipart.new(
uri.request_uri,
{ post_body: post_body }.merge(file_params),
headers
)
# DocuSign requires that we embed the document data in the body of the
# JSON request directly so we need to call '.read' on the multipart-post
# provided body_stream in order to serialize all the files into a
# compatible JSON string.
request.body = request.body_stream.read
request
end
# Public: creates an envelope from a document directly without a template
#
# file_io - Optional: an opened file stream of data (if you don't
# want to save the file to the file system as an incremental
# step)
# file_path - Required if you don't provide a file_io stream, this is
# the local path of the file you wish to upload. Absolute
# paths recommended.
# file_name - The name you want to give to the file you are uploading
# content_type - (for the request body) application/json is what DocuSign
# is expecting
# email_subject - (Optional) short subject line for the email
# email_body - (Optional) custom text that will be injected into the
# DocuSign generated email
# signers - A hash of users who should receive the document and need
# to sign it. More info about the options available for
# this method are documented above it's method definition.
# status - Options include: 'sent', 'created', 'voided' and determine
# if the envelope is sent out immediately or stored for
# sending at a later time
# headers - Allows a client to pass in some
#
# Returns a JSON parsed response object containing:
# envelopeId - The envelope's ID
# status - Sent, created, or voided
# statusDateTime - The date/time the envelope was created
# uri - The relative envelope uri
def create_envelope_from_document(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers])
},
status: "#{options[:status]}"
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# Public: allows a template to be dynamically created with several options.
#
# files - An array of hashes of file parameters which will be used
# to create actual files suitable for upload in a multipart
# request.
#
# Options: io, path, name. The io is optional and would
# require creating a file_io object to embed as the first
# argument of any given file hash. See the create_file_ios
# method definition above for more details.
#
# email/body - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# email/subject - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# signers - An array of hashes of signers. See the
# get_signers method definition for options.
# description - The template description
# name - The template name
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the template's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_template(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers], template: true)
},
envelopeTemplateDefinition: {
description: options[:description],
name: options[:name],
pageCount: 1,
password: '',
shared: false
}
}.to_json
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def get_template(template_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/templates/#{template_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', 'created', 'voided' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_id - The id of the template upon which we want to base this
# envelope
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the envelope's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_envelope_from_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
emailBlurb: options[:email][:body],
emailSubject: options[:email][:subject],
templateId: options[:template_id],
eventNotification: get_event_notification(options[:event_notification]),
templateRoles: get_template_roles(options[:signers]),
customFields: options[:custom_fields]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a composite template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', or 'created' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
# server_template_ids - Array of ids for templates uploaded to DocuSign. Templates
# will be added in the order they appear in the array.
#
# Returns a JSON parsed response body containing the envelope's:
# envelopeId - autogenerated ID provided by Docusign
# uri - the URI where the template is located on the DocuSign servers
# statusDateTime - The date/time the envelope was created
# status - Sent, created, or voided
def create_envelope_from_composite_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
compositeTemplates: get_composite_template(options[:server_template_ids], options[:signers])
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the names specified for a given email address (existing docusign user)
#
# email - the email of the recipient
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the list of names
def get_recipient_names(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/recipient_names?email=#{options[:email]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded signing
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# name - the name of the signer
# email - the email of the recipient
# return_url - the URL you want the user to be directed to after he or she
# completes the document signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded signing (can be put in an iFrame)
def get_recipient_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
authenticationMethod: 'email',
clientUserId: options[:client_id] || options[:email],
email: options[:email],
returnUrl: options[:return_url],
userName: options[:name]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded console
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded console (can be put in an iFrame)
def get_console_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeId: options[:envelope_id]
}.to_json
uri = build_uri("/accounts/#{acct_id}/views/console")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
parsed_response = JSON.parse(response.body)
parsed_response['url']
end
# Public returns the envelope recipients for a given envelope
#
# include_tabs - boolean, determines if the tabs for each signer will be
# returned in the response, defaults to false.
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a hash of detailed info about the envelope including the signer
# hash and status of each signer
def get_envelope_recipients(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
include_tabs = options[:include_tabs] || false
include_extended = options[:include_extended] || false
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope status
#
# envelope_id - ID of the envelope from which the doc will be retrieved
def get_envelope_status(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the statuses of envelopes matching the given query
#
# from_date - Docusign formatted Date/DateTime. Only return items after this date.
#
# to_date - Docusign formatted Date/DateTime. Only return items up to this date.
# Defaults to the time of the call.
#
# from_to_status - The status of the envelope checked for in the from_date - to_date period.
# Defaults to 'changed'
#
# status - The current status of the envelope. Defaults to any status.
#
# Returns an array of hashes containing envelope statuses, ids, and similar information.
def get_envelope_statuses(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
query_params = options.slice(:from_date, :to_date, :from_to_status, :status)
uri = build_uri("/accounts/#{acct_id}/envelopes?#{query_params.to_query}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the attached file from a given envelope
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# document_id - ID of the document to retrieve
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# document_id: 1,
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public retrieves the document infos from a given envelope
#
# envelope_id - ID of the envelope from which document infos are to be retrieved
#
# Returns a hash containing the envelopeId and the envelopeDocuments array
def get_documents_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves a PDF containing the combined content of all
# documents and the certificate for the given envelope.
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_combined_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_combined_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/combined")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public moves the specified envelopes to the given folder
#
# envelope_ids - IDs of the envelopes to be moved
# folder_id - ID of the folder to move the envelopes to
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.move_envelope_to_folder(
# envelope_ids: ["xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"]
# folder_id: "xxxxx-2222xxxxx",
# )
#
# Returns the response.
def move_envelope_to_folder(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeIds: options[:envelope_ids]
}.to_json
uri = build_uri("/accounts/#{acct_id}/folders/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
# Public returns a hash of audit events for a given envelope
#
# envelope_id - ID of the envelope to get audit events from
#
#
# Example
# client.get_envelope_audit_events(
# envelope_id: "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
# )
# Returns a hash of the events that have happened to the envelope.
def get_envelope_audit_events(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/audit_events")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope(s) from a specific folder based on search params.
#
# Option Query Terms(none are required):
# query_params:
# start_position: Integer The position of the folder items to return. This is used for repeated calls, when the number of envelopes returned is too much for one return (calls return 100 envelopes at a time). The default value is 0.
# from_date: date/Time Only return items on or after this date. If no value is provided, the default search is the previous 30 days.
# to_date: date/Time Only return items up to this date. If no value is provided, the default search is to the current date.
# search_text: String The search text used to search the items of the envelope. The search looks at recipient names and emails, envelope custom fields, sender name, and subject.
# status: Status The current status of the envelope. If no value is provided, the default search is all/any status.
# owner_name: username The name of the folder owner.
# owner_email: email The email of the folder owner.
#
# Example
#
# client.search_folder_for_envelopes(
# folder_id: xxxxx-2222xxxxx,
# query_params: {
# search_text: "John Appleseed",
# from_date: '7-1-2011+11:00:00+AM',
# to_date: '7-1-2011+11:00:00+AM',
# status: "completed"
# }
# )
#
def search_folder_for_envelopes(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
q ||= []
options[:query_params].each do |key, val|
q << "#{key}=#{val}"
end
uri = build_uri("/accounts/#{@acct_id}/folders/#{options[:folder_id]}/?#{q.join('&')}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def create_account(options)
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri('/accounts')
post_body = convert_hash_keys(options).to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [k.to_s.camelize(:lower), convert_hash_keys(v)] }]
else
value
end
end
# TODO (2014-02-03) jonk => document
def delete_account(account_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{account_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
response = http.request(request)
json = response.body
json = '{}' if json.nil? || json == ''
JSON.parse(json)
end
# Public: Retrieves a list of available templates
#
# Example
#
# client.get_templates()
#
# Returns a list of the available templates.
def get_templates
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Public: Retrieves a list of templates used in an envelope
#
# Returns templateId, name and uri for each template found.
#
# envelope_id - DS id of envelope with templates.
def get_templates_in_envelope(envelope_id)
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Grabs envelope data.
# Equivalent to the following call in the API explorer:
# Get Envelopev2/accounts/:accountId/envelopes/:envelopeId
#
# envelope_id- DS id of envelope to be retrieved.
def get_envelope(envelope_id)
content_type = { 'Content-Type' => 'application/json' }
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public deletes a recipient for a given envelope
#
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# recipient_id - ID of the recipient to delete
#
# Returns a hash of recipients with an error code for any recipients that
# were not successfully deleted.
def delete_envelope_recipient(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients")
post_body = "{
\"signers\" : [{\"recipientId\" : \"#{options[:recipient_id]}\"}]
}"
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public voids an in-process envelope
#
# envelope_id - ID of the envelope to be voided
# voided_reason - Optional reason for the envelope being voided
#
# Returns the response (success or failure).
def void_envelope(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
"status" =>"voided",
"voidedReason" => options[:voided_reason] || "No reason provided."
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
end
end
|
require 'openssl'
require 'open-uri'
module DocusignRest
class Client
# Define the same set of accessors as the DocusignRest module
attr_accessor *Configuration::VALID_CONFIG_KEYS
attr_accessor :docusign_authentication_headers, :acct_id
def initialize(options={})
# Merge the config values from the module and those passed to the client.
merged_options = DocusignRest.options.merge(options)
# Copy the merged values to this client and ignore those not part
# of our configuration
Configuration::VALID_CONFIG_KEYS.each do |key|
send("#{key}=", merged_options[key])
end
# Set up the DocuSign Authentication headers with the values passed from
# our config block
if access_token.nil?
@docusign_authentication_headers = {
'X-DocuSign-Authentication' => {
'Username' => username,
'Password' => password,
'IntegratorKey' => integrator_key
}.to_json
}
else
@docusign_authentication_headers = {
'Authorization' => "Bearer #{access_token}"
}
end
# Set the account_id from the configure block if present, but can't call
# the instance var @account_id because that'll override the attr_accessor
# that is automatically configured for the configure block
@acct_id = account_id
end
# Internal: sets the default request headers allowing for user overrides
# via options[:headers] from within other requests. Additionally injects
# the X-DocuSign-Authentication header to authorize the request.
#
# Client can pass in header options to any given request:
# headers: {'Some-Key' => 'some/value', 'Another-Key' => 'another/value'}
#
# Then we pass them on to this method to merge them with the other
# required headers
#
# Example:
#
# headers(options[:headers])
#
# Returns a merged hash of headers overriding the default Accept header if
# the user passes in a new 'Accept' header key and adds any other
# user-defined headers along with the X-DocuSign-Authentication headers
def headers(user_defined_headers={})
default = {
'Accept' => 'json' #this seems to get added automatically, so I can probably remove this
}
default.merge!(user_defined_headers) if user_defined_headers
@docusign_authentication_headers.merge(default)
end
# Internal: builds a URI based on the configurable endpoint, api_version,
# and the passed in relative url
#
# url - a relative url requiring a leading forward slash
#
# Example:
#
# build_uri('/login_information')
#
# Returns a parsed URI object
def build_uri(url)
URI.parse("#{endpoint}/#{api_version}#{url}")
end
# Internal: configures Net:HTTP with some default values that are required
# for every request to the DocuSign API
#
# Returns a configured Net::HTTP object into which a request can be passed
def initialize_net_http_ssl(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
if defined?(Rails) && Rails.env.test?
in_rails_test_env = true
else
in_rails_test_env = false
end
if http.use_ssl? && !in_rails_test_env
if ca_file
if File.exists?(ca_file)
http.ca_file = ca_file
else
raise 'Certificate path not found.'
end
end
# Explicitly verifies that the certificate matches the domain.
# Requires that we use www when calling the production DocuSign API
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.verify_depth = 5
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http
end
# Public: creates an OAuth2 authorization server token endpoint.
#
# email - email of user authenticating
# password - password of user authenticating
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.get_token('someone@example.com', 'p@ssw0rd01')
#
# Returns:
# access_token - Access token information
# scope - This should always be "api"
# token_type - This should always be "bearer"
def get_token(account_id, email, password)
content_type = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' }
uri = build_uri('/oauth2/token')
request = Net::HTTP::Post.new(uri.request_uri, content_type)
request.body = "grant_type=password&client_id=#{integrator_key}&username=#{email}&password=#{password}&scope=api"
http = initialize_net_http_ssl(uri)
response = http.request(request)
JSON.parse(response.body)
end
# Public: gets info necessary to make additional requests to the DocuSign API
#
# options - hash of headers if the client wants to override something
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.login_information
# puts response.body
#
# Returns:
# accountId - For the username, password, and integrator_key specified
# baseUrl - The base URL for all future DocuSign requests
# email - The email used when signing up for DocuSign
# isDefault - # TODO identify what this is
# name - The account name provided when signing up for DocuSign
# userId - # TODO determine what this is used for, if anything
# userName - Full name provided when signing up for DocuSign
def get_login_information(options={})
uri = build_uri('/login_information')
request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers]))
http = initialize_net_http_ssl(uri)
http.request(request)
end
# Internal: uses the get_login_information method to determine the client's
# accountId and then caches that value into an instance variable so we
# don't end up hitting the API for login_information more than once per
# request.
#
# This is used by the rake task in lib/tasks/docusign_task.rake to add
# the config/initialzers/docusign_rest.rb file with the proper config block
# which includes the account_id in it. That way we don't require hitting
# the /login_information URI in normal requests
#
# Returns the accountId string
def get_account_id
unless acct_id
response = get_login_information.body
hashed_response = JSON.parse(response)
login_accounts = hashed_response['loginAccounts']
acct_id ||= login_accounts.first['accountId']
end
acct_id
end
# Internal: takes in an array of hashes of signers and concatenates all the
# hashes with commas
#
# embedded - Tells DocuSign if this is an embedded signer which determines
# weather or not to deliver emails. Also lets us authenticate
# them when they go to do embedded signing. Behind the scenes
# this is setting the clientUserId value to the signer's email.
# name - The name of the signer
# email - The email of the signer
# role_name - The role name of the signer ('Attorney', 'Client', etc.).
# tabs - Array of tab pairs grouped by type (Example type: 'textTabs')
# { textTabs: [ { tabLabel: "label", name: "name", value: "value" } ] }
#
# NOTE: The 'tabs' option is NOT supported in 'v1' of the REST API
#
# Returns a hash of users that need to be embedded in the template to
# create an envelope
def get_template_roles(signers)
template_roles = []
signers.each_with_index do |signer, index|
template_role = {
name: signer[:name],
email: signer[:email],
roleName: signer[:role_name],
tabs: {
textTabs: get_signer_tabs(signer[:text_tabs]),
checkboxTabs: get_signer_tabs(signer[:checkbox_tabs]),
numberTabs: get_signer_tabs(signer[:number_tabs]),
fullNameTabs: get_signer_tabs(signer[:fullname_tabs]),
dateTabs: get_signer_tabs(signer[:date_tabs])
}
}
if signer[:email_notification]
template_role[:emailNotification] = signer[:email_notification]
end
template_role['clientUserId'] = (signer[:client_id] || signer[:email]).to_s if signer[:embedded] == true
template_roles << template_role
end
template_roles
end
# TODO (2014-02-03) jonk => document
def get_signer_tabs(tabs)
Array(tabs).map do |tab|
{
'tabLabel' => tab[:label],
'name' => tab[:name],
'value' => tab[:value],
'documentId' => tab[:document_id],
'selected' => tab[:selected],
'locked' => tab[:locked]
}
end
end
# TODO (2014-02-03) jonk => document
def get_event_notification(event_notification)
return {} unless event_notification
{
useSoapInterface: event_notification[:use_soap_interface] || false,
includeCertificatWithSoap: event_notification[:include_certificate_with_soap] || false,
url: event_notification[:url],
loggingEnabled: event_notification[:logging],
'EnvelopeEvents' => Array(event_notification[:envelope_events]).map do |envelope_event|
{
includeDocuments: envelope_event[:include_documents] || false,
envelopeEventStatusCode: envelope_event[:envelope_event_status_code]
}
end
}
end
# Internal: takes an array of hashes of signers required to complete a
# document and allows for setting several options. Not all options are
# currently dynamic but that's easy to change/add which I (and I'm
# sure others) will be doing in the future.
#
# template - Includes other optional fields only used when
# being called from a template
# email - The signer's email
# name - The signer's name
# embedded - Tells DocuSign if this is an embedded signer which
# determines weather or not to deliver emails. Also
# lets us authenticate them when they go to do
# embedded signing. Behind the scenes this is setting
# the clientUserId value to the signer's email.
# email_notification - Send an email or not
# role_name - The signer's role, like 'Attorney' or 'Client', etc.
# template_locked - Doesn't seem to work/do anything
# template_required - Doesn't seem to work/do anything
# anchor_string - The string of text to anchor the 'sign here' tab to
# document_id - If the doc you want signed isn't the first doc in
# the files options hash
# page_number - Page number of the sign here tab
# x_position - Distance horizontally from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# y_position - Distance vertically from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# sign_here_tab_text - Instead of 'sign here'. Note: doesn't work
# tab_label - TODO: figure out what this is
def get_signers(signers, options={})
doc_signers = []
signers.each_with_index do |signer, index|
doc_signer = {
email: signer[:email],
name: signer[:name],
accessCode: '',
addAccessCodeToEmail: false,
customFields: nil,
iDCheckConfigurationName: nil,
iDCheckInformationInput: nil,
inheritEmailNotificationConfiguration: false,
note: '',
phoneAuthentication: nil,
recipientAttachment: nil,
recipientId: "#{index + 1}",
requireIdLookup: false,
roleName: signer[:role_name],
routingOrder: index + 1,
socialAuthentications: nil
}
if signer[:email_notification]
doc_signer[:emailNotification] = signer[:email_notification]
end
if signer[:embedded]
doc_signer[:clientUserId] = signer[:client_id] || signer[:email]
end
if options[:template] == true
doc_signer[:templateAccessCodeRequired] = false
doc_signer[:templateLocked] = signer[:template_locked].nil? ? true : signer[:template_locked]
doc_signer[:templateRequired] = signer[:template_required].nil? ? true : signer[:template_required]
end
doc_signer[:autoNavigation] = false
doc_signer[:defaultRecipient] = false
doc_signer[:signatureInfo] = nil
doc_signer[:tabs] = {
approveTabs: nil,
checkboxTabs: get_tabs(signer[:checkbox_tabs], options, index),
companyTabs: nil,
dateSignedTabs: get_tabs(signer[:date_signed_tabs], options, index),
dateTabs: nil,
declineTabs: nil,
emailTabs: get_tabs(signer[:email_tabs], options, index),
envelopeIdTabs: nil,
fullNameTabs: get_tabs(signer[:full_name_tabs], options, index),
listTabs: get_tabs(signer[:list_tabs], options, index),
noteTabs: nil,
numberTabs: nil,
radioGroupTabs: get_tabs(signer[:radio_group_tabs], options, index),
initialHereTabs: get_tabs(signer[:initial_here_tabs], options.merge!(initial_here_tab: true), index),
signHereTabs: get_tabs(signer[:sign_here_tabs], options.merge!(sign_here_tab: true), index),
signerAttachmentTabs: nil,
ssnTabs: nil,
textTabs: get_tabs(signer[:text_tabs], options, index),
titleTabs: get_tabs(signer[:title_tabs], options, index),
zipTabs: nil
}
# append the fully build string to the array
doc_signers << doc_signer
end
doc_signers
end
# TODO (2014-02-03) jonk => document
def get_tabs(tabs, options, index)
tab_array = []
Array(tabs).map do |tab|
tab_hash = {}
if tab[:anchor_string]
tab_hash[:anchorString] = tab[:anchor_string]
tab_hash[:anchorXOffset] = tab[:anchor_x_offset] || '0'
tab_hash[:anchorYOffset] = tab[:anchor_y_offset] || '0'
tab_hash[:anchorIgnoreIfNotPresent] = tab[:ignore_anchor_if_not_present] || false
tab_hash[:anchorUnits] = 'pixels'
end
tab_hash[:conditionalParentLabel] = tab[:conditional_parent_label] if tab.key?(:conditional_parent_label)
tab_hash[:conditionalParentValue] = tab[:conditional_parent_value] if tab.key?(:conditional_parent_value)
tab_hash[:documentId] = tab[:document_id] || '1'
tab_hash[:pageNumber] = tab[:page_number] || '1'
tab_hash[:recipientId] = index + 1
tab_hash[:required] = tab[:required] || false
if options[:template] == true
tab_hash[:templateLocked] = tab[:template_locked].nil? ? true : tab[:template_locked]
tab_hash[:templateRequired] = tab[:template_required].nil? ? true : tab[:template_required]
end
if options[:sign_here_tab] == true || options[:initial_here_tab] == true
tab_hash[:scaleValue] = tab[:scale_value] || 1
end
tab_hash[:xPosition] = tab[:x_position] || '0'
tab_hash[:yPosition] = tab[:y_position] || '0'
tab_hash[:name] = tab[:name] if tab[:name]
tab_hash[:optional] = tab[:optional] || false
tab_hash[:tabLabel] = tab[:label] || 'Signature 1'
tab_hash[:width] = tab[:width] if tab[:width]
tab_hash[:height] = tab[:height] if tab[:width]
tab_hash[:value] = tab[:value] if tab[:value]
tab_hash[:locked] = tab[:locked] || false
tab_hash[:list_items] = tab[:list_items] if tab[:list_items]
tab_hash[:groupName] = tab[:group_name] if tab.key?(:group_name)
tab_hash[:radios] = get_tabs(tab[:radios], options, index) if tab.key?(:radios)
tab_array << tab_hash
end
tab_array
end
# Internal: sets up the file ios array
#
# files - a hash of file params
#
# Returns the properly formatted ios used to build the file_params hash
def create_file_ios(files)
# UploadIO is from the multipart-post gem's lib/composite_io.rb:57
# where it has this documentation:
#
# ********************************************************************
# Create an upload IO suitable for including in the params hash of a
# Net::HTTP::Post::Multipart.
#
# Can take two forms. The first accepts a filename and content type, and
# opens the file for reading (to be closed by finalizer).
#
# The second accepts an already-open IO, but also requires a third argument,
# the filename from which it was opened (particularly useful/recommended if
# uploading directly from a form in a framework, which often save the file to
# an arbitrarily named RackMultipart file in /tmp).
#
# Usage:
#
# UploadIO.new('file.txt', 'text/plain')
# UploadIO.new(file_io, 'text/plain', 'file.txt')
# ********************************************************************
#
# There is also a 4th undocumented argument, opts={}, which allows us
# to send in not only the Content-Disposition of 'file' as required by
# DocuSign, but also the documentId parameter which is required as well
#
ios = []
files.each_with_index do |file, index|
ios << UploadIO.new(
file[:io] || file[:path],
file[:content_type] || 'application/pdf',
file[:name],
'Content-Disposition' => "file; documentid=#{index + 1}"
)
end
ios
end
# Internal: sets up the file_params for inclusion in a multipart post request
#
# ios - An array of UploadIO formatted file objects
#
# Returns a hash of files params suitable for inclusion in a multipart
# post request
def create_file_params(ios)
# multi-doc uploading capabilities, each doc needs to be it's own param
file_params = {}
ios.each_with_index do |io,index|
file_params.merge!("file#{index + 1}" => io)
end
file_params
end
# Internal: takes in an array of hashes of documents and calculates the
# documentId
#
# Returns a hash of documents that are to be uploaded
def get_documents(ios)
ios.each_with_index.map do |io, index|
{
documentId: "#{index + 1}",
name: io.original_filename
}
end
end
# Internal: takes in an array of server template ids and an array of the signers
# and sets up the composite template
#
# Returns an array of server template hashes
def get_composite_template(server_template_ids, signers)
composite_array = []
index = 0
server_template_ids.each do |template_id|
server_template_hash = Hash[:sequence, index += 1, \
:templateId, template_id]
templates_hash = Hash[:serverTemplates, [server_template_hash], \
:inlineTemplates, get_inline_signers(signers, index += 1)]
composite_array << templates_hash
end
composite_array
end
# Internal: takes signer info and the inline template sequence number
# and sets up the inline template
#
# Returns an array of signers
def get_inline_signers(signers, sequence)
signers_array = []
signers.each do |signer|
signers_hash = Hash[:email, signer[:email], :name, signer[:name], \
:recipientId, signer[:recipient_id], :roleName, signer[:role_name], \
:clientUserId, signer[:client_id] || signer[:email]]
signers_array << signers_hash
end
template_hash = Hash[:sequence, sequence, :recipients, { signers: signers_array }]
[template_hash]
end
# Internal sets up the Net::HTTP request
#
# uri - The fully qualified final URI
# post_body - The custom post body including the signers, etc
# file_params - Formatted hash of ios to merge into the post body
# headers - Allows for passing in custom headers
#
# Returns a request object suitable for embedding in a request
def initialize_net_http_multipart_post_request(uri, post_body, file_params, headers)
# Net::HTTP::Post::Multipart is from the multipart-post gem's lib/multipartable.rb
#
# path - The fully qualified URI for the request
# params - A hash of params (including files for uploading and a
# customized request body)
# headers={} - The fully merged, final request headers
# boundary - Optional: you can give the request a custom boundary
#
request = Net::HTTP::Post::Multipart.new(
uri.request_uri,
{ post_body: post_body }.merge(file_params),
headers
)
# DocuSign requires that we embed the document data in the body of the
# JSON request directly so we need to call '.read' on the multipart-post
# provided body_stream in order to serialize all the files into a
# compatible JSON string.
request.body = request.body_stream.read
request
end
# Public: creates an envelope from a document directly without a template
#
# file_io - Optional: an opened file stream of data (if you don't
# want to save the file to the file system as an incremental
# step)
# file_path - Required if you don't provide a file_io stream, this is
# the local path of the file you wish to upload. Absolute
# paths recommended.
# file_name - The name you want to give to the file you are uploading
# content_type - (for the request body) application/json is what DocuSign
# is expecting
# email_subject - (Optional) short subject line for the email
# email_body - (Optional) custom text that will be injected into the
# DocuSign generated email
# signers - A hash of users who should receive the document and need
# to sign it. More info about the options available for
# this method are documented above it's method definition.
# status - Options include: 'sent', 'created', 'voided' and determine
# if the envelope is sent out immediately or stored for
# sending at a later time
# customFields - (Optional) A hash of listCustomFields and textCustomFields.
# Each contains an array of corresponding customField hashes.
# For details, please see: http://bit.ly/1FnmRJx
# headers - Allows a client to pass in some
#
# Returns a JSON parsed response object containing:
# envelopeId - The envelope's ID
# status - Sent, created, or voided
# statusDateTime - The date/time the envelope was created
# uri - The relative envelope uri
def create_envelope_from_document(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers])
},
status: "#{options[:status]}",
customFields: options[:custom_fields]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# Public: allows a template to be dynamically created with several options.
#
# files - An array of hashes of file parameters which will be used
# to create actual files suitable for upload in a multipart
# request.
#
# Options: io, path, name. The io is optional and would
# require creating a file_io object to embed as the first
# argument of any given file hash. See the create_file_ios
# method definition above for more details.
#
# email/body - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# email/subject - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# signers - An array of hashes of signers. See the
# get_signers method definition for options.
# description - The template description
# name - The template name
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the template's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_template(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers], template: true)
},
envelopeTemplateDefinition: {
description: options[:description],
name: options[:name],
pageCount: 1,
password: '',
shared: false
}
}.to_json
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def get_template(template_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/templates/#{template_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', 'created', 'voided' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_id - The id of the template upon which we want to base this
# envelope
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the envelope's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_envelope_from_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
emailBlurb: options[:email][:body],
emailSubject: options[:email][:subject],
templateId: options[:template_id],
eventNotification: get_event_notification(options[:event_notification]),
templateRoles: get_template_roles(options[:signers]),
customFields: options[:custom_fields]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a composite template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', or 'created' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
# server_template_ids - Array of ids for templates uploaded to DocuSign. Templates
# will be added in the order they appear in the array.
#
# Returns a JSON parsed response body containing the envelope's:
# envelopeId - autogenerated ID provided by Docusign
# uri - the URI where the template is located on the DocuSign servers
# statusDateTime - The date/time the envelope was created
# status - Sent, created, or voided
def create_envelope_from_composite_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
compositeTemplates: get_composite_template(options[:server_template_ids], options[:signers])
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the names specified for a given email address (existing docusign user)
#
# email - the email of the recipient
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the list of names
def get_recipient_names(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/recipient_names?email=#{options[:email]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded signing
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# name - the name of the signer
# email - the email of the recipient
# return_url - the URL you want the user to be directed to after he or she
# completes the document signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded signing (can be put in an iFrame)
def get_recipient_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
authenticationMethod: 'email',
clientUserId: options[:client_id] || options[:email],
email: options[:email],
returnUrl: options[:return_url],
userName: options[:name]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded console
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded console (can be put in an iFrame)
def get_console_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeId: options[:envelope_id]
}.to_json
uri = build_uri("/accounts/#{acct_id}/views/console")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
parsed_response = JSON.parse(response.body)
parsed_response['url']
end
# Public returns the envelope recipients for a given envelope
#
# include_tabs - boolean, determines if the tabs for each signer will be
# returned in the response, defaults to false.
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a hash of detailed info about the envelope including the signer
# hash and status of each signer
def get_envelope_recipients(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
include_tabs = options[:include_tabs] || false
include_extended = options[:include_extended] || false
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope status
#
# envelope_id - ID of the envelope from which the doc will be retrieved
def get_envelope_status(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the statuses of envelopes matching the given query
#
# from_date - Docusign formatted Date/DateTime. Only return items after this date.
#
# to_date - Docusign formatted Date/DateTime. Only return items up to this date.
# Defaults to the time of the call.
#
# from_to_status - The status of the envelope checked for in the from_date - to_date period.
# Defaults to 'changed'
#
# status - The current status of the envelope. Defaults to any status.
#
# Returns an array of hashes containing envelope statuses, ids, and similar information.
def get_envelope_statuses(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
query_params = options.slice(:from_date, :to_date, :from_to_status, :status)
uri = build_uri("/accounts/#{acct_id}/envelopes?#{query_params.to_query}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the attached file from a given envelope
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# document_id - ID of the document to retrieve
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# document_id: 1,
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public retrieves the document infos from a given envelope
#
# envelope_id - ID of the envelope from which document infos are to be retrieved
#
# Returns a hash containing the envelopeId and the envelopeDocuments array
def get_documents_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves a PDF containing the combined content of all
# documents and the certificate for the given envelope.
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_combined_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_combined_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/combined")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public moves the specified envelopes to the given folder
#
# envelope_ids - IDs of the envelopes to be moved
# folder_id - ID of the folder to move the envelopes to
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.move_envelope_to_folder(
# envelope_ids: ["xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"]
# folder_id: "xxxxx-2222xxxxx",
# )
#
# Returns the response.
def move_envelope_to_folder(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeIds: options[:envelope_ids]
}.to_json
uri = build_uri("/accounts/#{acct_id}/folders/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
# Public returns a hash of audit events for a given envelope
#
# envelope_id - ID of the envelope to get audit events from
#
#
# Example
# client.get_envelope_audit_events(
# envelope_id: "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
# )
# Returns a hash of the events that have happened to the envelope.
def get_envelope_audit_events(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/audit_events")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope(s) from a specific folder based on search params.
#
# Option Query Terms(none are required):
# query_params:
# start_position: Integer The position of the folder items to return. This is used for repeated calls, when the number of envelopes returned is too much for one return (calls return 100 envelopes at a time). The default value is 0.
# from_date: date/Time Only return items on or after this date. If no value is provided, the default search is the previous 30 days.
# to_date: date/Time Only return items up to this date. If no value is provided, the default search is to the current date.
# search_text: String The search text used to search the items of the envelope. The search looks at recipient names and emails, envelope custom fields, sender name, and subject.
# status: Status The current status of the envelope. If no value is provided, the default search is all/any status.
# owner_name: username The name of the folder owner.
# owner_email: email The email of the folder owner.
#
# Example
#
# client.search_folder_for_envelopes(
# folder_id: xxxxx-2222xxxxx,
# query_params: {
# search_text: "John Appleseed",
# from_date: '7-1-2011+11:00:00+AM',
# to_date: '7-1-2011+11:00:00+AM',
# status: "completed"
# }
# )
#
def search_folder_for_envelopes(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
q ||= []
options[:query_params].each do |key, val|
q << "#{key}=#{val}"
end
uri = build_uri("/accounts/#{@acct_id}/folders/#{options[:folder_id]}/?#{q.join('&')}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def create_account(options)
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri('/accounts')
post_body = convert_hash_keys(options).to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [k.to_s.camelize(:lower), convert_hash_keys(v)] }]
else
value
end
end
# TODO (2014-02-03) jonk => document
def delete_account(account_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{account_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
response = http.request(request)
json = response.body
json = '{}' if json.nil? || json == ''
JSON.parse(json)
end
# Public: Retrieves a list of available templates
#
# Example
#
# client.get_templates()
#
# Returns a list of the available templates.
def get_templates
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Public: Retrieves a list of templates used in an envelope
#
# Returns templateId, name and uri for each template found.
#
# envelope_id - DS id of envelope with templates.
def get_templates_in_envelope(envelope_id)
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Grabs envelope data.
# Equivalent to the following call in the API explorer:
# Get Envelopev2/accounts/:accountId/envelopes/:envelopeId
#
# envelope_id- DS id of envelope to be retrieved.
def get_envelope(envelope_id)
content_type = { 'Content-Type' => 'application/json' }
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public deletes a recipient for a given envelope
#
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# recipient_id - ID of the recipient to delete
#
# Returns a hash of recipients with an error code for any recipients that
# were not successfully deleted.
def delete_envelope_recipient(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients")
post_body = "{
\"signers\" : [{\"recipientId\" : \"#{options[:recipient_id]}\"}]
}"
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public voids an in-process envelope
#
# envelope_id - ID of the envelope to be voided
# voided_reason - Optional reason for the envelope being voided
#
# Returns the response (success or failure).
def void_envelope(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
"status" =>"voided",
"voidedReason" => options[:voided_reason] || "No reason provided."
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
# Public deletes a document for a given envelope
# See https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST API References/Remove Documents from a Draft Envelope.htm%3FTocPath%3DREST%2520API%2520References%7C_____54
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# document_id - ID of the document to delete
#
# Returns the success or failure of each document being added to the envelope and
# the envelope ID. Failed operations on array elements will add the "errorDetails"
# structure containing an error code and message. If "errorDetails" is null, then
# the operation was successful for that item.
def delete_envelope_document(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/documents")
post_body = {
documents: [
{ documentId: options[:document_id] }
]
}.to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public adds a document to a given envelope
# See https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST API References/Add Document.htm%3FTocPath%3DREST%2520API%2520References%7C_____56
#
# envelope_id - ID of the envelope from which the doc will be added
# document_id - ID of the document to add
# file_path - Local or remote path to file
# content_type - optional content type for file. Defaults to application/pdf.
# file_name - optional name for file. Defaults to basename of file_path.
# file_extension - optional extension for file. Defaults to extname of file_name.
#
# The response only returns a success or failure.
def add_envelope_document(options={})
options[:content_type] ||= 'application/pdf'
options[:file_name] ||= File.basename(options[:file_path])
options[:file_extension] ||= File.extname(options[:file_name])[1..-1]
headers = {
'Content-Type' => options[:content_type],
'Content-Disposition' => "file; filename=\"#{options[:file_name]}\"; documentid=#{options[:document_id]}; fileExtension=\"#{options[:file_extension]}\""
}
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}")
post_body = open(options[:file_path]).read
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(headers))
request.body = post_body
response = http.request(request)
end
# Public adds recipient tabs to a given envelope
# See https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST API References/Add Tabs for a Recipient.htm%3FTocPath%3DREST%2520API%2520References%7C_____86
#
# envelope_id - ID of the envelope from which the doc will be added
# recipient - ID of the recipient to add tabs to
# tabs - hash of tab (see example below)
# {
# signHereTabs: [
# {
# anchorString: '/s1/',
# anchorXOffset: '5',
# anchorYOffset: '8',
# anchorIgnoreIfNotPresent: 'true',
# documentId: '1',
# pageNumber: '1',
# recipientId: '1'
# }
# ],
# initialHereTabs: [
# {
# anchorString: '/i1/',
# anchorXOffset: '5',
# anchorYOffset: '8',
# anchorIgnoreIfNotPresent: 'true',
# documentId: '1',
# pageNumber: '1',
# recipientId: '1'
# }
# ]
# }
#
# The response returns the success or failure of each document being added
# to the envelope and the envelope ID. Failed operations on array elements
# will add the "errorDetails" structure containing an error code and message.
# If "errorDetails" is null, then the operation was successful for that item.
def add_recipient_tabs(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients/#{options[:recipient_id]}/tabs")
post_body = options[:tabs].to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
end
end
add add_recipients method to client class
require 'openssl'
require 'open-uri'
module DocusignRest
class Client
# Define the same set of accessors as the DocusignRest module
attr_accessor *Configuration::VALID_CONFIG_KEYS
attr_accessor :docusign_authentication_headers, :acct_id
def initialize(options={})
# Merge the config values from the module and those passed to the client.
merged_options = DocusignRest.options.merge(options)
# Copy the merged values to this client and ignore those not part
# of our configuration
Configuration::VALID_CONFIG_KEYS.each do |key|
send("#{key}=", merged_options[key])
end
# Set up the DocuSign Authentication headers with the values passed from
# our config block
if access_token.nil?
@docusign_authentication_headers = {
'X-DocuSign-Authentication' => {
'Username' => username,
'Password' => password,
'IntegratorKey' => integrator_key
}.to_json
}
else
@docusign_authentication_headers = {
'Authorization' => "Bearer #{access_token}"
}
end
# Set the account_id from the configure block if present, but can't call
# the instance var @account_id because that'll override the attr_accessor
# that is automatically configured for the configure block
@acct_id = account_id
end
# Internal: sets the default request headers allowing for user overrides
# via options[:headers] from within other requests. Additionally injects
# the X-DocuSign-Authentication header to authorize the request.
#
# Client can pass in header options to any given request:
# headers: {'Some-Key' => 'some/value', 'Another-Key' => 'another/value'}
#
# Then we pass them on to this method to merge them with the other
# required headers
#
# Example:
#
# headers(options[:headers])
#
# Returns a merged hash of headers overriding the default Accept header if
# the user passes in a new 'Accept' header key and adds any other
# user-defined headers along with the X-DocuSign-Authentication headers
def headers(user_defined_headers={})
default = {
'Accept' => 'json' #this seems to get added automatically, so I can probably remove this
}
default.merge!(user_defined_headers) if user_defined_headers
@docusign_authentication_headers.merge(default)
end
# Internal: builds a URI based on the configurable endpoint, api_version,
# and the passed in relative url
#
# url - a relative url requiring a leading forward slash
#
# Example:
#
# build_uri('/login_information')
#
# Returns a parsed URI object
def build_uri(url)
URI.parse("#{endpoint}/#{api_version}#{url}")
end
# Internal: configures Net:HTTP with some default values that are required
# for every request to the DocuSign API
#
# Returns a configured Net::HTTP object into which a request can be passed
def initialize_net_http_ssl(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
if defined?(Rails) && Rails.env.test?
in_rails_test_env = true
else
in_rails_test_env = false
end
if http.use_ssl? && !in_rails_test_env
if ca_file
if File.exists?(ca_file)
http.ca_file = ca_file
else
raise 'Certificate path not found.'
end
end
# Explicitly verifies that the certificate matches the domain.
# Requires that we use www when calling the production DocuSign API
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.verify_depth = 5
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http
end
# Public: creates an OAuth2 authorization server token endpoint.
#
# email - email of user authenticating
# password - password of user authenticating
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.get_token('someone@example.com', 'p@ssw0rd01')
#
# Returns:
# access_token - Access token information
# scope - This should always be "api"
# token_type - This should always be "bearer"
def get_token(account_id, email, password)
content_type = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' }
uri = build_uri('/oauth2/token')
request = Net::HTTP::Post.new(uri.request_uri, content_type)
request.body = "grant_type=password&client_id=#{integrator_key}&username=#{email}&password=#{password}&scope=api"
http = initialize_net_http_ssl(uri)
response = http.request(request)
JSON.parse(response.body)
end
# Public: gets info necessary to make additional requests to the DocuSign API
#
# options - hash of headers if the client wants to override something
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.login_information
# puts response.body
#
# Returns:
# accountId - For the username, password, and integrator_key specified
# baseUrl - The base URL for all future DocuSign requests
# email - The email used when signing up for DocuSign
# isDefault - # TODO identify what this is
# name - The account name provided when signing up for DocuSign
# userId - # TODO determine what this is used for, if anything
# userName - Full name provided when signing up for DocuSign
def get_login_information(options={})
uri = build_uri('/login_information')
request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers]))
http = initialize_net_http_ssl(uri)
http.request(request)
end
# Internal: uses the get_login_information method to determine the client's
# accountId and then caches that value into an instance variable so we
# don't end up hitting the API for login_information more than once per
# request.
#
# This is used by the rake task in lib/tasks/docusign_task.rake to add
# the config/initialzers/docusign_rest.rb file with the proper config block
# which includes the account_id in it. That way we don't require hitting
# the /login_information URI in normal requests
#
# Returns the accountId string
def get_account_id
unless acct_id
response = get_login_information.body
hashed_response = JSON.parse(response)
login_accounts = hashed_response['loginAccounts']
acct_id ||= login_accounts.first['accountId']
end
acct_id
end
# Internal: takes in an array of hashes of signers and concatenates all the
# hashes with commas
#
# embedded - Tells DocuSign if this is an embedded signer which determines
# weather or not to deliver emails. Also lets us authenticate
# them when they go to do embedded signing. Behind the scenes
# this is setting the clientUserId value to the signer's email.
# name - The name of the signer
# email - The email of the signer
# role_name - The role name of the signer ('Attorney', 'Client', etc.).
# tabs - Array of tab pairs grouped by type (Example type: 'textTabs')
# { textTabs: [ { tabLabel: "label", name: "name", value: "value" } ] }
#
# NOTE: The 'tabs' option is NOT supported in 'v1' of the REST API
#
# Returns a hash of users that need to be embedded in the template to
# create an envelope
def get_template_roles(signers)
template_roles = []
signers.each_with_index do |signer, index|
template_role = {
name: signer[:name],
email: signer[:email],
roleName: signer[:role_name],
tabs: {
textTabs: get_signer_tabs(signer[:text_tabs]),
checkboxTabs: get_signer_tabs(signer[:checkbox_tabs]),
numberTabs: get_signer_tabs(signer[:number_tabs]),
fullNameTabs: get_signer_tabs(signer[:fullname_tabs]),
dateTabs: get_signer_tabs(signer[:date_tabs])
}
}
if signer[:email_notification]
template_role[:emailNotification] = signer[:email_notification]
end
template_role['clientUserId'] = (signer[:client_id] || signer[:email]).to_s if signer[:embedded] == true
template_roles << template_role
end
template_roles
end
# TODO (2014-02-03) jonk => document
def get_signer_tabs(tabs)
Array(tabs).map do |tab|
{
'tabLabel' => tab[:label],
'name' => tab[:name],
'value' => tab[:value],
'documentId' => tab[:document_id],
'selected' => tab[:selected],
'locked' => tab[:locked]
}
end
end
# TODO (2014-02-03) jonk => document
def get_event_notification(event_notification)
return {} unless event_notification
{
useSoapInterface: event_notification[:use_soap_interface] || false,
includeCertificatWithSoap: event_notification[:include_certificate_with_soap] || false,
url: event_notification[:url],
loggingEnabled: event_notification[:logging],
'EnvelopeEvents' => Array(event_notification[:envelope_events]).map do |envelope_event|
{
includeDocuments: envelope_event[:include_documents] || false,
envelopeEventStatusCode: envelope_event[:envelope_event_status_code]
}
end
}
end
# Internal: takes an array of hashes of signers required to complete a
# document and allows for setting several options. Not all options are
# currently dynamic but that's easy to change/add which I (and I'm
# sure others) will be doing in the future.
#
# template - Includes other optional fields only used when
# being called from a template
# email - The signer's email
# name - The signer's name
# embedded - Tells DocuSign if this is an embedded signer which
# determines weather or not to deliver emails. Also
# lets us authenticate them when they go to do
# embedded signing. Behind the scenes this is setting
# the clientUserId value to the signer's email.
# email_notification - Send an email or not
# role_name - The signer's role, like 'Attorney' or 'Client', etc.
# template_locked - Doesn't seem to work/do anything
# template_required - Doesn't seem to work/do anything
# anchor_string - The string of text to anchor the 'sign here' tab to
# document_id - If the doc you want signed isn't the first doc in
# the files options hash
# page_number - Page number of the sign here tab
# x_position - Distance horizontally from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# y_position - Distance vertically from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# sign_here_tab_text - Instead of 'sign here'. Note: doesn't work
# tab_label - TODO: figure out what this is
def get_signers(signers, options={})
doc_signers = []
signers.each_with_index do |signer, index|
doc_signer = {
email: signer[:email],
name: signer[:name],
accessCode: '',
addAccessCodeToEmail: false,
customFields: nil,
iDCheckConfigurationName: nil,
iDCheckInformationInput: nil,
inheritEmailNotificationConfiguration: false,
note: '',
phoneAuthentication: nil,
recipientAttachment: nil,
recipientId: "#{index + 1}",
requireIdLookup: false,
roleName: signer[:role_name],
routingOrder: index + 1,
socialAuthentications: nil
}
if signer[:email_notification]
doc_signer[:emailNotification] = signer[:email_notification]
end
if signer[:embedded]
doc_signer[:clientUserId] = signer[:client_id] || signer[:email]
end
if options[:template] == true
doc_signer[:templateAccessCodeRequired] = false
doc_signer[:templateLocked] = signer[:template_locked].nil? ? true : signer[:template_locked]
doc_signer[:templateRequired] = signer[:template_required].nil? ? true : signer[:template_required]
end
doc_signer[:autoNavigation] = false
doc_signer[:defaultRecipient] = false
doc_signer[:signatureInfo] = nil
doc_signer[:tabs] = {
approveTabs: nil,
checkboxTabs: get_tabs(signer[:checkbox_tabs], options, index),
companyTabs: nil,
dateSignedTabs: get_tabs(signer[:date_signed_tabs], options, index),
dateTabs: nil,
declineTabs: nil,
emailTabs: get_tabs(signer[:email_tabs], options, index),
envelopeIdTabs: nil,
fullNameTabs: get_tabs(signer[:full_name_tabs], options, index),
listTabs: get_tabs(signer[:list_tabs], options, index),
noteTabs: nil,
numberTabs: nil,
radioGroupTabs: get_tabs(signer[:radio_group_tabs], options, index),
initialHereTabs: get_tabs(signer[:initial_here_tabs], options.merge!(initial_here_tab: true), index),
signHereTabs: get_tabs(signer[:sign_here_tabs], options.merge!(sign_here_tab: true), index),
signerAttachmentTabs: nil,
ssnTabs: nil,
textTabs: get_tabs(signer[:text_tabs], options, index),
titleTabs: get_tabs(signer[:title_tabs], options, index),
zipTabs: nil
}
# append the fully build string to the array
doc_signers << doc_signer
end
doc_signers
end
# TODO (2014-02-03) jonk => document
def get_tabs(tabs, options, index)
tab_array = []
Array(tabs).map do |tab|
tab_hash = {}
if tab[:anchor_string]
tab_hash[:anchorString] = tab[:anchor_string]
tab_hash[:anchorXOffset] = tab[:anchor_x_offset] || '0'
tab_hash[:anchorYOffset] = tab[:anchor_y_offset] || '0'
tab_hash[:anchorIgnoreIfNotPresent] = tab[:ignore_anchor_if_not_present] || false
tab_hash[:anchorUnits] = 'pixels'
end
tab_hash[:conditionalParentLabel] = tab[:conditional_parent_label] if tab.key?(:conditional_parent_label)
tab_hash[:conditionalParentValue] = tab[:conditional_parent_value] if tab.key?(:conditional_parent_value)
tab_hash[:documentId] = tab[:document_id] || '1'
tab_hash[:pageNumber] = tab[:page_number] || '1'
tab_hash[:recipientId] = index + 1
tab_hash[:required] = tab[:required] || false
if options[:template] == true
tab_hash[:templateLocked] = tab[:template_locked].nil? ? true : tab[:template_locked]
tab_hash[:templateRequired] = tab[:template_required].nil? ? true : tab[:template_required]
end
if options[:sign_here_tab] == true || options[:initial_here_tab] == true
tab_hash[:scaleValue] = tab[:scale_value] || 1
end
tab_hash[:xPosition] = tab[:x_position] || '0'
tab_hash[:yPosition] = tab[:y_position] || '0'
tab_hash[:name] = tab[:name] if tab[:name]
tab_hash[:optional] = tab[:optional] || false
tab_hash[:tabLabel] = tab[:label] || 'Signature 1'
tab_hash[:width] = tab[:width] if tab[:width]
tab_hash[:height] = tab[:height] if tab[:width]
tab_hash[:value] = tab[:value] if tab[:value]
tab_hash[:locked] = tab[:locked] || false
tab_hash[:list_items] = tab[:list_items] if tab[:list_items]
tab_hash[:groupName] = tab[:group_name] if tab.key?(:group_name)
tab_hash[:radios] = get_tabs(tab[:radios], options, index) if tab.key?(:radios)
tab_array << tab_hash
end
tab_array
end
# Internal: sets up the file ios array
#
# files - a hash of file params
#
# Returns the properly formatted ios used to build the file_params hash
def create_file_ios(files)
# UploadIO is from the multipart-post gem's lib/composite_io.rb:57
# where it has this documentation:
#
# ********************************************************************
# Create an upload IO suitable for including in the params hash of a
# Net::HTTP::Post::Multipart.
#
# Can take two forms. The first accepts a filename and content type, and
# opens the file for reading (to be closed by finalizer).
#
# The second accepts an already-open IO, but also requires a third argument,
# the filename from which it was opened (particularly useful/recommended if
# uploading directly from a form in a framework, which often save the file to
# an arbitrarily named RackMultipart file in /tmp).
#
# Usage:
#
# UploadIO.new('file.txt', 'text/plain')
# UploadIO.new(file_io, 'text/plain', 'file.txt')
# ********************************************************************
#
# There is also a 4th undocumented argument, opts={}, which allows us
# to send in not only the Content-Disposition of 'file' as required by
# DocuSign, but also the documentId parameter which is required as well
#
ios = []
files.each_with_index do |file, index|
ios << UploadIO.new(
file[:io] || file[:path],
file[:content_type] || 'application/pdf',
file[:name],
'Content-Disposition' => "file; documentid=#{index + 1}"
)
end
ios
end
# Internal: sets up the file_params for inclusion in a multipart post request
#
# ios - An array of UploadIO formatted file objects
#
# Returns a hash of files params suitable for inclusion in a multipart
# post request
def create_file_params(ios)
# multi-doc uploading capabilities, each doc needs to be it's own param
file_params = {}
ios.each_with_index do |io,index|
file_params.merge!("file#{index + 1}" => io)
end
file_params
end
# Internal: takes in an array of hashes of documents and calculates the
# documentId
#
# Returns a hash of documents that are to be uploaded
def get_documents(ios)
ios.each_with_index.map do |io, index|
{
documentId: "#{index + 1}",
name: io.original_filename
}
end
end
# Internal: takes in an array of server template ids and an array of the signers
# and sets up the composite template
#
# Returns an array of server template hashes
def get_composite_template(server_template_ids, signers)
composite_array = []
index = 0
server_template_ids.each do |template_id|
server_template_hash = Hash[:sequence, index += 1, \
:templateId, template_id]
templates_hash = Hash[:serverTemplates, [server_template_hash], \
:inlineTemplates, get_inline_signers(signers, index += 1)]
composite_array << templates_hash
end
composite_array
end
# Internal: takes signer info and the inline template sequence number
# and sets up the inline template
#
# Returns an array of signers
def get_inline_signers(signers, sequence)
signers_array = []
signers.each do |signer|
signers_hash = Hash[:email, signer[:email], :name, signer[:name], \
:recipientId, signer[:recipient_id], :roleName, signer[:role_name], \
:clientUserId, signer[:client_id] || signer[:email]]
signers_array << signers_hash
end
template_hash = Hash[:sequence, sequence, :recipients, { signers: signers_array }]
[template_hash]
end
# Internal sets up the Net::HTTP request
#
# uri - The fully qualified final URI
# post_body - The custom post body including the signers, etc
# file_params - Formatted hash of ios to merge into the post body
# headers - Allows for passing in custom headers
#
# Returns a request object suitable for embedding in a request
def initialize_net_http_multipart_post_request(uri, post_body, file_params, headers)
# Net::HTTP::Post::Multipart is from the multipart-post gem's lib/multipartable.rb
#
# path - The fully qualified URI for the request
# params - A hash of params (including files for uploading and a
# customized request body)
# headers={} - The fully merged, final request headers
# boundary - Optional: you can give the request a custom boundary
#
request = Net::HTTP::Post::Multipart.new(
uri.request_uri,
{ post_body: post_body }.merge(file_params),
headers
)
# DocuSign requires that we embed the document data in the body of the
# JSON request directly so we need to call '.read' on the multipart-post
# provided body_stream in order to serialize all the files into a
# compatible JSON string.
request.body = request.body_stream.read
request
end
# Public: creates an envelope from a document directly without a template
#
# file_io - Optional: an opened file stream of data (if you don't
# want to save the file to the file system as an incremental
# step)
# file_path - Required if you don't provide a file_io stream, this is
# the local path of the file you wish to upload. Absolute
# paths recommended.
# file_name - The name you want to give to the file you are uploading
# content_type - (for the request body) application/json is what DocuSign
# is expecting
# email_subject - (Optional) short subject line for the email
# email_body - (Optional) custom text that will be injected into the
# DocuSign generated email
# signers - A hash of users who should receive the document and need
# to sign it. More info about the options available for
# this method are documented above it's method definition.
# status - Options include: 'sent', 'created', 'voided' and determine
# if the envelope is sent out immediately or stored for
# sending at a later time
# customFields - (Optional) A hash of listCustomFields and textCustomFields.
# Each contains an array of corresponding customField hashes.
# For details, please see: http://bit.ly/1FnmRJx
# headers - Allows a client to pass in some
#
# Returns a JSON parsed response object containing:
# envelopeId - The envelope's ID
# status - Sent, created, or voided
# statusDateTime - The date/time the envelope was created
# uri - The relative envelope uri
def create_envelope_from_document(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers])
},
status: "#{options[:status]}",
customFields: options[:custom_fields]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# Public: allows a template to be dynamically created with several options.
#
# files - An array of hashes of file parameters which will be used
# to create actual files suitable for upload in a multipart
# request.
#
# Options: io, path, name. The io is optional and would
# require creating a file_io object to embed as the first
# argument of any given file hash. See the create_file_ios
# method definition above for more details.
#
# email/body - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# email/subject - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# signers - An array of hashes of signers. See the
# get_signers method definition for options.
# description - The template description
# name - The template name
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the template's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_template(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers], template: true)
},
envelopeTemplateDefinition: {
description: options[:description],
name: options[:name],
pageCount: 1,
password: '',
shared: false
}
}.to_json
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def get_template(template_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/templates/#{template_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', 'created', 'voided' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_id - The id of the template upon which we want to base this
# envelope
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the envelope's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_envelope_from_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
emailBlurb: options[:email][:body],
emailSubject: options[:email][:subject],
templateId: options[:template_id],
eventNotification: get_event_notification(options[:event_notification]),
templateRoles: get_template_roles(options[:signers]),
customFields: options[:custom_fields]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a composite template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', or 'created' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
# server_template_ids - Array of ids for templates uploaded to DocuSign. Templates
# will be added in the order they appear in the array.
#
# Returns a JSON parsed response body containing the envelope's:
# envelopeId - autogenerated ID provided by Docusign
# uri - the URI where the template is located on the DocuSign servers
# statusDateTime - The date/time the envelope was created
# status - Sent, created, or voided
def create_envelope_from_composite_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
compositeTemplates: get_composite_template(options[:server_template_ids], options[:signers])
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the names specified for a given email address (existing docusign user)
#
# email - the email of the recipient
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the list of names
def get_recipient_names(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/recipient_names?email=#{options[:email]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded signing
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# name - the name of the signer
# email - the email of the recipient
# return_url - the URL you want the user to be directed to after he or she
# completes the document signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded signing (can be put in an iFrame)
def get_recipient_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
authenticationMethod: 'email',
clientUserId: options[:client_id] || options[:email],
email: options[:email],
returnUrl: options[:return_url],
userName: options[:name]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/views/recipient")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public returns the URL for embedded console
#
# envelope_id - the ID of the envelope you wish to use for embedded signing
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns the URL string for embedded console (can be put in an iFrame)
def get_console_view(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeId: options[:envelope_id]
}.to_json
uri = build_uri("/accounts/#{acct_id}/views/console")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
parsed_response = JSON.parse(response.body)
parsed_response['url']
end
# Public returns the envelope recipients for a given envelope
#
# include_tabs - boolean, determines if the tabs for each signer will be
# returned in the response, defaults to false.
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# headers - optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a hash of detailed info about the envelope including the signer
# hash and status of each signer
def get_envelope_recipients(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
include_tabs = options[:include_tabs] || false
include_extended = options[:include_extended] || false
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/recipients?include_tabs=#{include_tabs}&include_extended=#{include_extended}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope status
#
# envelope_id - ID of the envelope from which the doc will be retrieved
def get_envelope_status(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the statuses of envelopes matching the given query
#
# from_date - Docusign formatted Date/DateTime. Only return items after this date.
#
# to_date - Docusign formatted Date/DateTime. Only return items up to this date.
# Defaults to the time of the call.
#
# from_to_status - The status of the envelope checked for in the from_date - to_date period.
# Defaults to 'changed'
#
# status - The current status of the envelope. Defaults to any status.
#
# Returns an array of hashes containing envelope statuses, ids, and similar information.
def get_envelope_statuses(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
query_params = options.slice(:from_date, :to_date, :from_to_status, :status)
uri = build_uri("/accounts/#{acct_id}/envelopes?#{query_params.to_query}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the attached file from a given envelope
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# document_id - ID of the document to retrieve
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# document_id: 1,
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public retrieves the document infos from a given envelope
#
# envelope_id - ID of the envelope from which document infos are to be retrieved
#
# Returns a hash containing the envelopeId and the envelopeDocuments array
def get_documents_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves a PDF containing the combined content of all
# documents and the certificate for the given envelope.
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# local_save_path - Local absolute path to save the doc to including the
# filename itself
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.get_combined_document_from_envelope(
# envelope_id: @envelope_response['envelopeId'],
# local_save_path: 'docusign_docs/file_name.pdf',
# return_stream: true/false # will return the bytestream instead of saving doc to file system.
# )
#
# Returns the PDF document as a byte stream.
def get_combined_document_from_envelope(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/combined")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
return response.body if options[:return_stream]
split_path = options[:local_save_path].split('/')
split_path.pop #removes the document name and extension from the array
path = split_path.join("/") #rejoins the array to form path to the folder that will contain the file
FileUtils.mkdir_p(path)
File.open(options[:local_save_path], 'wb') do |output|
output << response.body
end
end
# Public moves the specified envelopes to the given folder
#
# envelope_ids - IDs of the envelopes to be moved
# folder_id - ID of the folder to move the envelopes to
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Example
#
# client.move_envelope_to_folder(
# envelope_ids: ["xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"]
# folder_id: "xxxxx-2222xxxxx",
# )
#
# Returns the response.
def move_envelope_to_folder(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
envelopeIds: options[:envelope_ids]
}.to_json
uri = build_uri("/accounts/#{acct_id}/folders/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
# Public returns a hash of audit events for a given envelope
#
# envelope_id - ID of the envelope to get audit events from
#
#
# Example
# client.get_envelope_audit_events(
# envelope_id: "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx"
# )
# Returns a hash of the events that have happened to the envelope.
def get_envelope_audit_events(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/audit_events")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public retrieves the envelope(s) from a specific folder based on search params.
#
# Option Query Terms(none are required):
# query_params:
# start_position: Integer The position of the folder items to return. This is used for repeated calls, when the number of envelopes returned is too much for one return (calls return 100 envelopes at a time). The default value is 0.
# from_date: date/Time Only return items on or after this date. If no value is provided, the default search is the previous 30 days.
# to_date: date/Time Only return items up to this date. If no value is provided, the default search is to the current date.
# search_text: String The search text used to search the items of the envelope. The search looks at recipient names and emails, envelope custom fields, sender name, and subject.
# status: Status The current status of the envelope. If no value is provided, the default search is all/any status.
# owner_name: username The name of the folder owner.
# owner_email: email The email of the folder owner.
#
# Example
#
# client.search_folder_for_envelopes(
# folder_id: xxxxx-2222xxxxx,
# query_params: {
# search_text: "John Appleseed",
# from_date: '7-1-2011+11:00:00+AM',
# to_date: '7-1-2011+11:00:00+AM',
# status: "completed"
# }
# )
#
def search_folder_for_envelopes(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
q ||= []
options[:query_params].each do |key, val|
q << "#{key}=#{val}"
end
uri = build_uri("/accounts/#{@acct_id}/folders/#{options[:folder_id]}/?#{q.join('&')}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def create_account(options)
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri('/accounts')
post_body = convert_hash_keys(options).to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [k.to_s.camelize(:lower), convert_hash_keys(v)] }]
else
value
end
end
# TODO (2014-02-03) jonk => document
def delete_account(account_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{account_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
response = http.request(request)
json = response.body
json = '{}' if json.nil? || json == ''
JSON.parse(json)
end
# Public: Retrieves a list of available templates
#
# Example
#
# client.get_templates()
#
# Returns a list of the available templates.
def get_templates
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Public: Retrieves a list of templates used in an envelope
#
# Returns templateId, name and uri for each template found.
#
# envelope_id - DS id of envelope with templates.
def get_templates_in_envelope(envelope_id)
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}/templates")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers({ 'Content-Type' => 'application/json' }))
JSON.parse(http.request(request).body)
end
# Grabs envelope data.
# Equivalent to the following call in the API explorer:
# Get Envelopev2/accounts/:accountId/envelopes/:envelopeId
#
# envelope_id- DS id of envelope to be retrieved.
def get_envelope(envelope_id)
content_type = { 'Content-Type' => 'application/json' }
uri = build_uri("/accounts/#{acct_id}/envelopes/#{envelope_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
JSON.parse(response.body)
end
# Public deletes a recipient for a given envelope
#
# envelope_id - ID of the envelope for which you want to retrieve the
# signer info
# recipient_id - ID of the recipient to delete
#
# Returns a hash of recipients with an error code for any recipients that
# were not successfully deleted.
def delete_envelope_recipient(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients")
post_body = "{
\"signers\" : [{\"recipientId\" : \"#{options[:recipient_id]}\"}]
}"
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public voids an in-process envelope
#
# envelope_id - ID of the envelope to be voided
# voided_reason - Optional reason for the envelope being voided
#
# Returns the response (success or failure).
def void_envelope(options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
"status" =>"voided",
"voidedReason" => options[:voided_reason] || "No reason provided."
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:folder_id]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
response
end
# Public deletes a document for a given envelope
# See https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST API References/Remove Documents from a Draft Envelope.htm%3FTocPath%3DREST%2520API%2520References%7C_____54
#
# envelope_id - ID of the envelope from which the doc will be retrieved
# document_id - ID of the document to delete
#
# Returns the success or failure of each document being added to the envelope and
# the envelope ID. Failed operations on array elements will add the "errorDetails"
# structure containing an error code and message. If "errorDetails" is null, then
# the operation was successful for that item.
def delete_envelope_document(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/documents")
post_body = {
documents: [
{ documentId: options[:document_id] }
]
}.to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Delete.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public adds a document to a given envelope
# See https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST API References/Add Document.htm%3FTocPath%3DREST%2520API%2520References%7C_____56
#
# envelope_id - ID of the envelope from which the doc will be added
# document_id - ID of the document to add
# file_path - Local or remote path to file
# content_type - optional content type for file. Defaults to application/pdf.
# file_name - optional name for file. Defaults to basename of file_path.
# file_extension - optional extension for file. Defaults to extname of file_name.
#
# The response only returns a success or failure.
def add_envelope_document(options={})
options[:content_type] ||= 'application/pdf'
options[:file_name] ||= File.basename(options[:file_path])
options[:file_extension] ||= File.extname(options[:file_name])[1..-1]
headers = {
'Content-Type' => options[:content_type],
'Content-Disposition' => "file; filename=\"#{options[:file_name]}\"; documentid=#{options[:document_id]}; fileExtension=\"#{options[:file_extension]}\""
}
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}")
post_body = open(options[:file_path]).read
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Put.new(uri.request_uri, headers(headers))
request.body = post_body
response = http.request(request)
end
# Public adds recipient tabs to a given envelope
# See https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST API References/Add Tabs for a Recipient.htm%3FTocPath%3DREST%2520API%2520References%7C_____86
#
# envelope_id - ID of the envelope from which the doc will be added
# recipient - ID of the recipient to add tabs to
# tabs - hash of tab (see example below)
# {
# signHereTabs: [
# {
# anchorString: '/s1/',
# anchorXOffset: '5',
# anchorYOffset: '8',
# anchorIgnoreIfNotPresent: 'true',
# documentId: '1',
# pageNumber: '1',
# recipientId: '1'
# }
# ],
# initialHereTabs: [
# {
# anchorString: '/i1/',
# anchorXOffset: '5',
# anchorYOffset: '8',
# anchorIgnoreIfNotPresent: 'true',
# documentId: '1',
# pageNumber: '1',
# recipientId: '1'
# }
# ]
# }
#
# The response returns the success or failure of each document being added
# to the envelope and the envelope ID. Failed operations on array elements
# will add the "errorDetails" structure containing an error code and message.
# If "errorDetails" is null, then the operation was successful for that item.
def add_recipient_tabs(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients/#{options[:recipient_id]}/tabs")
post_body = options[:tabs].to_json
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
# Public adds recipients to a given envelope
# See https://www.docusign.com/p/RESTAPIGuide/RESTAPIGuide.htm#REST API References/Add Recipients to an Envelope.htm?Highlight=add recipient to envelope
#
# envelope_id - ID of the envelope from which the doc will be added
# signers - array of hash of signer (see example below)
# signers: [{
# email: 'String content',
# name: 'String content',
# signHereTabs: [
# {
# anchorString: '/s1/',
# anchorXOffset: '5',
# anchorYOffset: '8',
# anchorIgnoreIfNotPresent: 'true',
# documentId: '1',
# pageNumber: '1',
# recipientId: '1'
# }
# ]
# }]
#
# The response returns the success or failure of each document being added
# to the envelope and the envelope ID. Failed operations on array elements
# will add the "errorDetails" structure containing an error code and message.
# If "errorDetails" is null, then the operation was successful for that item.
def add_recipients(options={})
content_type = {'Content-Type' => 'application/json'}
content_type.merge(options[:headers]) if options[:headers]
options[:resend_envelope] ||= false
post_body = {
signers: get_signers(options[:signers])
}.to_json
uri = build_uri("/accounts/#{@acct_id}/envelopes/#{options[:envelope_id]}/recipients?resend_envelope=#{options[:resend_envelope]}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
JSON.parse(response.body)
end
end
end
|
require 'helper'
require 'action_controller'
require 'rails/observers/activerecord/active_record'
require 'rails/observers/action_controller/caching'
SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
class AppSweeper < ActionController::Caching::Sweeper; end
class SweeperTestController < ActionController::Base
include SharedTestRoutes.url_helpers
cache_sweeper :app_sweeper
def show
if Rails.version_matches?('>= 5.0.0.beta1')
render plain: 'hello world'
else
render text: 'hello world'
end
end
def error
raise StandardError.new
end
end
class SweeperTest < ActionController::TestCase
def setup
@routes = SharedTestRoutes
@routes.draw do
get 'sweeper_test/show'
end
super
end
def test_sweeper_should_not_ignore_no_method_error
sweeper = ActionController::Caching::Sweeper.send(:new)
assert_raise NoMethodError do
sweeper.send_not_defined
end
end
def test_sweeper_should_not_block_rendering
response = test_process(SweeperTestController)
assert_equal 'hello world', response.body
end
def test_sweeper_should_clean_up_if_exception_is_raised
assert_raise StandardError do
test_process(SweeperTestController, 'error')
end
assert_nil AppSweeper.instance.controller
end
def test_before_method_of_sweeper_should_always_return_true
sweeper = ActionController::Caching::Sweeper.send(:new)
assert sweeper.before(SweeperTestController.new)
end
def test_after_method_of_sweeper_should_always_return_nil
sweeper = ActionController::Caching::Sweeper.send(:new)
assert_nil sweeper.after(SweeperTestController.new)
end
def test_sweeper_should_not_ignore_unknown_method_calls
sweeper = ActionController::Caching::Sweeper.send(:new)
assert_raise NameError do
sweeper.instance_eval do
some_method_that_doesnt_exist
end
end
end
private
def test_process(controller, action = "show")
@controller = controller.is_a?(Class) ? controller.new : controller
if ActionController::TestRequest.respond_to?(:create)
if ActionController::TestRequest.method(:create).arity == 0
@request = ActionController::TestRequest.create
else
@request = ActionController::TestRequest.create @controller.class
end
else
@request = ActionController::TestRequest.new
end
if ActionController.constants.include?(:TestResponse)
@response = ActionController::TestResponse.new
else
@response = ActionDispatch::TestResponse.new
end
process(action)
end
end
Add back error route.
require 'helper'
require 'action_controller'
require 'rails/observers/activerecord/active_record'
require 'rails/observers/action_controller/caching'
SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
class AppSweeper < ActionController::Caching::Sweeper; end
class SweeperTestController < ActionController::Base
include SharedTestRoutes.url_helpers
cache_sweeper :app_sweeper
def show
if Rails.version_matches?('>= 5.0.0.beta1')
render plain: 'hello world'
else
render text: 'hello world'
end
end
def error
raise StandardError.new
end
end
class SweeperTest < ActionController::TestCase
def setup
@routes = SharedTestRoutes
@routes.draw do
get 'sweeper_test/show'
get 'sweeper_test/error'
end
super
end
def test_sweeper_should_not_ignore_no_method_error
sweeper = ActionController::Caching::Sweeper.send(:new)
assert_raise NoMethodError do
sweeper.send_not_defined
end
end
def test_sweeper_should_not_block_rendering
response = test_process(SweeperTestController)
assert_equal 'hello world', response.body
end
def test_sweeper_should_clean_up_if_exception_is_raised
assert_raise StandardError do
test_process(SweeperTestController, 'error')
end
assert_nil AppSweeper.instance.controller
end
def test_before_method_of_sweeper_should_always_return_true
sweeper = ActionController::Caching::Sweeper.send(:new)
assert sweeper.before(SweeperTestController.new)
end
def test_after_method_of_sweeper_should_always_return_nil
sweeper = ActionController::Caching::Sweeper.send(:new)
assert_nil sweeper.after(SweeperTestController.new)
end
def test_sweeper_should_not_ignore_unknown_method_calls
sweeper = ActionController::Caching::Sweeper.send(:new)
assert_raise NameError do
sweeper.instance_eval do
some_method_that_doesnt_exist
end
end
end
private
def test_process(controller, action = "show")
@controller = controller.is_a?(Class) ? controller.new : controller
if ActionController::TestRequest.respond_to?(:create)
if ActionController::TestRequest.method(:create).arity == 0
@request = ActionController::TestRequest.create
else
@request = ActionController::TestRequest.create @controller.class
end
else
@request = ActionController::TestRequest.new
end
if ActionController.constants.include?(:TestResponse)
@response = ActionController::TestResponse.new
else
@response = ActionDispatch::TestResponse.new
end
process(action)
end
end
|
# Thanks to Jim Weirich for the concepts in this class.
# Extracted from https://github.com/jimweirich/wyriki
# domain_driven would not be possible without this critical part.
require 'delegate'
module DomainDriven
class Entity < SimpleDelegator
include BlockActiveRecord
def _data
datum = self
while datum.entity?
datum = datum.__getobj__
end
datum
end
def ==(other)
if other.respond_to?(:_data)
_data == other._data
else
_data == other
end
end
def entity?
true
end
def class
_data.class
end
def self.wrap(entity)
entity ? new(entity) : nil
end
def self.wraps(entities)
return entities unless entities
entities.map { |entity| wrap(entity) }
end
end
end
smarter wrapping of a collection-ish
# Thanks to Jim Weirich for the concepts in this class.
# Extracted from https://github.com/jimweirich/wyriki
# domain_driven would not be possible without this critical part.
require 'delegate'
module DomainDriven
class Entity < SimpleDelegator
include BlockActiveRecord
def _data
datum = self
while datum.entity?
datum = datum.__getobj__
end
datum
end
def ==(other)
if other.respond_to?(:_data)
_data == other._data
else
_data == other
end
end
def entity?
true
end
def class
_data.class
end
def self.wrap(entity)
entity ? new(entity) : nil
end
def self.wraps(entities)
return nil unless entities
wrap(entities.extend Model).extend Collection
end
end
module Collection
def each
_data.each do |_item|
yield wrap(_item)
end
end
def include?(other)
if other.respond_to?(:_data)
_data.include?(other._data)
else
_data.include?(other)
end
end
end
end
|
require "shogi_koma/painter"
require "cairo"
class PainterTest < Test::Unit::TestCase
def setup
@painter = ShogiKoma::Painter.new
end
class DrawTest < self
def test_nothing_raised
width = 200
height = 200
assert_nothing_raised do
Cairo::ImageSurface.new(:argb32, width, height) do |surface|
Cairo::Context.new(surface) do |context|
context.scale(width, height)
@painter.draw(context, "A")
end
end
end
end
end
end
test: indent
require "shogi_koma/painter"
require "cairo"
class PainterTest < Test::Unit::TestCase
def setup
@painter = ShogiKoma::Painter.new
end
class DrawTest < self
def test_nothing_raised
width = 200
height = 200
assert_nothing_raised do
Cairo::ImageSurface.new(:argb32, width, height) do |surface|
Cairo::Context.new(surface) do |context|
context.scale(width, height)
@painter.draw(context, "A")
end
end
end
end
end
end
|
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
Domgen::Generator.define([:jpa],
"#{File.dirname(__FILE__)}/templates",
[Domgen::JPA::Helper, Domgen::Java::Helper, Domgen::JAXB::Helper]) do |g|
g.template_set(:jpa_model) do |template_set|
template_set.erb_template(:repository,
'unit_descriptor.java.erb',
'main/java/#{repository.jpa.qualified_unit_descriptor_name.gsub(".","/")}.java',
:guard => 'repository.jpa.include_default_unit? || repository.jpa.standalone_persistence_units?')
template_set.erb_template(:entity,
'entity.java.erb',
'main/java/#{entity.jpa.qualified_name.gsub(".","/")}.java')
template_set.erb_template(:entity,
'metamodel.java.erb',
'main/java/#{entity.jpa.qualified_metamodel_name.gsub(".","/")}.java')
template_set.erb_template(:data_module,
'entity_package_info.java.erb',
'main/java/#{data_module.jpa.server_entity_package.gsub(".","/")}/package-info.java',
:guard => 'data_module.entities.any?{|e|e.jpa?}')
end
%w(main test).each do |type|
g.template_set(:"jpa_#{type}_qa_external") do |template_set|
template_set.erb_template(:repository,
'persistent_test_module.java.erb',
type + '/java/#{repository.jpa.qualified_persistent_test_module_name.gsub(".","/")}.java',
:guard => 'repository.jpa.include_default_unit?')
template_set.erb_template('jpa.persistence_unit',
'raw_test_module.java.erb',
type + '/java/#{persistence_unit.qualified_raw_test_module_name.gsub(".","/")}.java',
:guard => 'persistence_unit.raw_test_mode?')
template_set.erb_template(:repository,
'dao_module.java.erb',
type + '/java/#{repository.jpa.qualified_dao_module_name.gsub(".","/")}.java')
template_set.erb_template(:repository,
'test_factory_set.java.erb',
type + '/java/#{repository.jpa.qualified_test_factory_set_name.gsub(".","/")}.java')
template_set.erb_template(:data_module,
'abstract_test_factory.java.erb',
type + '/java/#{data_module.jpa.qualified_abstract_test_factory_name.gsub(".","/")}.java')
end
g.template_set(:"jpa_#{type}_qa") do |template_set|
template_set.erb_template(:repository,
'abstract_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_abstract_entity_test_name.gsub(".","/")}.java')
template_set.erb_template(:repository,
'base_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_base_entity_test_name.gsub(".","/")}.java',
:guard => 'repository.jpa.custom_base_entity_test?')
template_set.erb_template(:repository,
'standalone_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_standalone_entity_test_name.gsub(".","/")}.java')
end
g.template_set(:"jpa_#{type}_qa_aggregate") do |template_set|
template_set.erb_template(:repository,
'aggregate_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_aggregate_entity_test_name.gsub(".","/")}.java')
end
end
g.template_set(:jpa_dao_test) do |template_set|
template_set.erb_template(:dao,
'dao_test.java.erb',
'test/java/#{dao.jpa.qualified_dao_test_name.gsub(".","/")}.java',
:guard => 'dao.queries.any?{|q|!q.jpa.standard_query?}')
end
g.template_set(:jpa_ejb_dao) do |template_set|
template_set.erb_template(:dao,
'dao.java.erb',
'main/java/#{dao.jpa.qualified_dao_name.gsub(".","/")}.java',
:guard => '!dao.repository? || dao.entity.jpa?')
template_set.erb_template(:dao,
'dao_service.java.erb',
'main/java/#{dao.jpa.qualified_dao_service_name.gsub(".","/")}.java',
:guard => '!dao.repository? || dao.entity.jpa?')
template_set.erb_template(:data_module,
'dao_package_info.java.erb',
'main/java/#{data_module.jpa.server_dao_entity_package.gsub(".","/")}/package-info.java',
:guard => 'data_module.entities.any?{|e|e.jpa?}')
end
g.template_set(:jpa_application_persistence_xml) do |template_set|
template_set.erb_template(:repository,
'application_persistence.xml.erb',
'main/resources/META-INF/persistence.xml',
:guard => 'repository.jpa.application_xmls?')
end
g.template_set(:jpa_application_orm_xml) do |template_set|
template_set.erb_template(:repository,
'application_orm.xml.erb',
'main/resources/META-INF/orm.xml',
:guard => 'repository.jpa.application_xmls?')
end
g.template_set(:jpa_template_persistence_xml) do |template_set|
template_set.erb_template(:repository,
'template_persistence.xml.erb',
'main/resources/META-INF/domgen/templates/persistence.xml',
:guard => 'repository.jpa.template_xmls?')
end
g.template_set(:jpa_template_orm_xml) do |template_set|
template_set.erb_template(:repository,
'template_orm.xml.erb',
'main/resources/META-INF/domgen/templates/orm.xml',
:guard => 'repository.jpa.template_xmls?')
end
g.template_set(:jpa_test_persistence_xml) do |template_set|
template_set.erb_template(:repository,
'test_persistence.xml.erb',
'test/resources/META-INF/persistence.xml',
:guard => 'repository.jpa.test_xmls?')
end
g.template_set(:jpa_test_orm_xml) do |template_set|
template_set.erb_template(:repository,
'test_orm.xml.erb',
'test/resources/META-INF/orm.xml',
:guard => 'repository.jpa.test_xmls?')
end
g.template_set(:jpa => [:jpa_application_orm_xml, :jpa_application_persistence_xml, :jpa_model])
end
Fix guard for base entity class
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
Domgen::Generator.define([:jpa],
"#{File.dirname(__FILE__)}/templates",
[Domgen::JPA::Helper, Domgen::Java::Helper, Domgen::JAXB::Helper]) do |g|
g.template_set(:jpa_model) do |template_set|
template_set.erb_template(:repository,
'unit_descriptor.java.erb',
'main/java/#{repository.jpa.qualified_unit_descriptor_name.gsub(".","/")}.java',
:guard => 'repository.jpa.include_default_unit? || repository.jpa.standalone_persistence_units?')
template_set.erb_template(:entity,
'entity.java.erb',
'main/java/#{entity.jpa.qualified_name.gsub(".","/")}.java')
template_set.erb_template(:entity,
'metamodel.java.erb',
'main/java/#{entity.jpa.qualified_metamodel_name.gsub(".","/")}.java')
template_set.erb_template(:data_module,
'entity_package_info.java.erb',
'main/java/#{data_module.jpa.server_entity_package.gsub(".","/")}/package-info.java',
:guard => 'data_module.entities.any?{|e|e.jpa?}')
end
%w(main test).each do |type|
g.template_set(:"jpa_#{type}_qa_external") do |template_set|
template_set.erb_template(:repository,
'persistent_test_module.java.erb',
type + '/java/#{repository.jpa.qualified_persistent_test_module_name.gsub(".","/")}.java',
:guard => 'repository.jpa.include_default_unit?')
template_set.erb_template('jpa.persistence_unit',
'raw_test_module.java.erb',
type + '/java/#{persistence_unit.qualified_raw_test_module_name.gsub(".","/")}.java',
:guard => 'persistence_unit.raw_test_mode?')
template_set.erb_template(:repository,
'dao_module.java.erb',
type + '/java/#{repository.jpa.qualified_dao_module_name.gsub(".","/")}.java')
template_set.erb_template(:repository,
'test_factory_set.java.erb',
type + '/java/#{repository.jpa.qualified_test_factory_set_name.gsub(".","/")}.java')
template_set.erb_template(:data_module,
'abstract_test_factory.java.erb',
type + '/java/#{data_module.jpa.qualified_abstract_test_factory_name.gsub(".","/")}.java')
end
g.template_set(:"jpa_#{type}_qa") do |template_set|
template_set.erb_template(:repository,
'abstract_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_abstract_entity_test_name.gsub(".","/")}.java')
template_set.erb_template(:repository,
'base_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_base_entity_test_name.gsub(".","/")}.java',
:guard => '!repository.jpa.custom_base_entity_test?')
template_set.erb_template(:repository,
'standalone_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_standalone_entity_test_name.gsub(".","/")}.java')
end
g.template_set(:"jpa_#{type}_qa_aggregate") do |template_set|
template_set.erb_template(:repository,
'aggregate_entity_test.java.erb',
type + '/java/#{repository.jpa.qualified_aggregate_entity_test_name.gsub(".","/")}.java')
end
end
g.template_set(:jpa_dao_test) do |template_set|
template_set.erb_template(:dao,
'dao_test.java.erb',
'test/java/#{dao.jpa.qualified_dao_test_name.gsub(".","/")}.java',
:guard => 'dao.queries.any?{|q|!q.jpa.standard_query?}')
end
g.template_set(:jpa_ejb_dao) do |template_set|
template_set.erb_template(:dao,
'dao.java.erb',
'main/java/#{dao.jpa.qualified_dao_name.gsub(".","/")}.java',
:guard => '!dao.repository? || dao.entity.jpa?')
template_set.erb_template(:dao,
'dao_service.java.erb',
'main/java/#{dao.jpa.qualified_dao_service_name.gsub(".","/")}.java',
:guard => '!dao.repository? || dao.entity.jpa?')
template_set.erb_template(:data_module,
'dao_package_info.java.erb',
'main/java/#{data_module.jpa.server_dao_entity_package.gsub(".","/")}/package-info.java',
:guard => 'data_module.entities.any?{|e|e.jpa?}')
end
g.template_set(:jpa_application_persistence_xml) do |template_set|
template_set.erb_template(:repository,
'application_persistence.xml.erb',
'main/resources/META-INF/persistence.xml',
:guard => 'repository.jpa.application_xmls?')
end
g.template_set(:jpa_application_orm_xml) do |template_set|
template_set.erb_template(:repository,
'application_orm.xml.erb',
'main/resources/META-INF/orm.xml',
:guard => 'repository.jpa.application_xmls?')
end
g.template_set(:jpa_template_persistence_xml) do |template_set|
template_set.erb_template(:repository,
'template_persistence.xml.erb',
'main/resources/META-INF/domgen/templates/persistence.xml',
:guard => 'repository.jpa.template_xmls?')
end
g.template_set(:jpa_template_orm_xml) do |template_set|
template_set.erb_template(:repository,
'template_orm.xml.erb',
'main/resources/META-INF/domgen/templates/orm.xml',
:guard => 'repository.jpa.template_xmls?')
end
g.template_set(:jpa_test_persistence_xml) do |template_set|
template_set.erb_template(:repository,
'test_persistence.xml.erb',
'test/resources/META-INF/persistence.xml',
:guard => 'repository.jpa.test_xmls?')
end
g.template_set(:jpa_test_orm_xml) do |template_set|
template_set.erb_template(:repository,
'test_orm.xml.erb',
'test/resources/META-INF/orm.xml',
:guard => 'repository.jpa.test_xmls?')
end
g.template_set(:jpa => [:jpa_application_orm_xml, :jpa_application_persistence_xml, :jpa_model])
end
|
module Dota2
module Static
VERSION = '0.1.104'
end
end
Bump to 0.1.105
module Dota2
module Static
VERSION = '0.1.105'
end
end
|
module DslAccessor
VERSION = "0.2.2"
end
bumped to 0.4.1
module DslAccessor
VERSION = "0.4.1"
end
|
require 'dynabute/util'
require 'dynabute/joins'
require 'dynabute/nested_attributes'
module Dynabute
module Dynabutable
extend ActiveSupport::Concern
included do
include Joins::Dynabutable
include NestedAttributes::API
(Dynabute::Field::TYPES).each do |t|
has_many Util.value_relation_name(t), class_name: Util.value_class_name(t), as: :dynabutable
accepts_nested_attributes_for Util.value_relation_name(t)
end
def self.dynabutes
Dynabute::Field.for(self.to_s)
end
def self.dynabute_relation_names
Util.all_value_relation_names
end
def dynabute_fields
Dynabute::Field.for(self.class.to_s)
end
def dynabute_values
@dynabute_values ||= dynabute_fields
.group_by{|f| f.value_type}
.map { |type, fields|
fields.first.value_class.where(field_id: fields.map(&:id), dynabutable_id: id)
}.flatten.compact
end
def dynabute_value(name: nil, id: nil, field: nil)
field = find_field(name, id, field)
if field.has_many
send(Util.value_relation_name(field.value_type)).where(field_id: field.id)
else
send(Util.value_relation_name(field.value_type)).find_by(field_id: field.id)
end
end
def build_dynabute_value(name: nil, id: nil, field: nil)
field = find_field(name, id, field)
send(Util.value_relation_name(field.value_type)).build(field_id: field.id)
end
def method_missing(*args)
name = args[0]
one = name.to_s.scan(/^dynabute_(.+)_value$/)[0]
many = name.to_s.scan(/^dynabute_(.+)_values$/)[0]
return super if one.nil? && many.nil?
target = one ? one : many
candidates = [target[0], target[0].gsub('_', ' ')]
field = Dynabute::Field.find_by(name: candidates)
return super if field.nil?
dynabute_value(field: field)
end
private
def find_field(name, id, field)
name_or_id = {name: name, id: id}.compact
return nil if name_or_id.blank? && field.blank?
field_obj = field || Dynabute::Field.find_by(name_or_id.merge(target_model: self.class.to_s))
fail Dynabute::FieldNotFound.new(name_or_id, field) if field_obj.nil?
field_obj
end
end
end
end
mod: build_dynabute_value() can take value for arg
require 'dynabute/util'
require 'dynabute/joins'
require 'dynabute/nested_attributes'
module Dynabute
module Dynabutable
extend ActiveSupport::Concern
included do
include Joins::Dynabutable
include NestedAttributes::API
(Dynabute::Field::TYPES).each do |t|
has_many Util.value_relation_name(t), class_name: Util.value_class_name(t), as: :dynabutable
accepts_nested_attributes_for Util.value_relation_name(t)
end
def self.dynabutes
Dynabute::Field.for(self.to_s)
end
def self.dynabute_relation_names
Util.all_value_relation_names
end
def dynabute_fields
Dynabute::Field.for(self.class.to_s)
end
def dynabute_values
@dynabute_values ||= dynabute_fields
.group_by{|f| f.value_type}
.map { |type, fields|
fields.first.value_class.where(field_id: fields.map(&:id), dynabutable_id: id)
}.flatten.compact
end
def dynabute_value(name: nil, id: nil, field: nil)
field = find_field(name, id, field)
if field.has_many
send(Util.value_relation_name(field.value_type)).where(field_id: field.id)
else
send(Util.value_relation_name(field.value_type)).find_by(field_id: field.id)
end
end
def build_dynabute_value(name: nil, id: nil, field: nil, **rest)
field = find_field(name, id, field)
send(Util.value_relation_name(field.value_type)).build(field_id: field.id, **rest)
end
def method_missing(*args)
name = args[0]
one = name.to_s.scan(/^dynabute_(.+)_value$/)[0]
many = name.to_s.scan(/^dynabute_(.+)_values$/)[0]
return super if one.nil? && many.nil?
target = one ? one : many
candidates = [target[0], target[0].gsub('_', ' ')]
field = Dynabute::Field.find_by(name: candidates)
return super if field.nil?
dynabute_value(field: field)
end
private
def find_field(name, id, field)
name_or_id = {name: name, id: id}.compact
return nil if name_or_id.blank? && field.blank?
field_obj = field || Dynabute::Field.find_by(name_or_id.merge(target_model: self.class.to_s))
fail Dynabute::FieldNotFound.new(name_or_id, field) if field_obj.nil?
field_obj
end
end
end
end
|
$VERBOSE = true
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'ansi256'
require 'minitest/autorun'
class TestAnsi256 < MiniTest::Unit::TestCase
def cfmt col
col.to_s.rjust(5).fg(232).bg(col)
end
# TODO: assertions :p
def test_256_color_table
puts (0..7).map { |col| cfmt col }.join
puts (8..15).map { |col| cfmt col }.join
(16..255).each_slice(6) do |slice|
puts slice.map { |col| cfmt col }.join
end
end
def test_nesting
a = ' '
(16..60).each do |i|
a = "<#{a}>".bg(i).fg(i * 2).underline
end
puts a
end
def test_nesting_hello_world
# Nesting
puts world = "World".bg(226).fg(232).underline
puts hello = "Hello #{world} !".fg(230).bg(75)
puts say_hello_world = "Say '#{hello}'".fg(30)
puts say_hello_world.plain.fg(27)
end
def test_nesting_hello_world2
puts world = "World".bg(226).blue.underline
puts hello = "Hello #{world} Hello".white.bold
puts say_hello_world = "Say '#{hello}'".fg(30).underline
puts say_hello_world.plain.fg(27)
end
def test_nesting_hello_world3
puts world = "World".blue.underline
puts hello = "Hello #{world} Hello".blue.bold
puts say_hello_world = "Say '#{hello}'".fg(30).underline
puts say_hello_world.plain.fg(27)
end
def test_named_colors
s = "Colorize me"
puts [ s.black, s.black.bold, s.white.bold.on_black ].join ' '
puts [ s.red, s.red.bold, s.white.bold.on_red ].join ' '
puts [ s.green, s.green.bold, s.white.bold.on_green ].join ' '
puts [ s.yellow, s.yellow.bold, s.white.bold.on_yellow ].join ' '
puts [ s.blue, s.blue.bold, s.white.bold.on_blue ].join ' '
puts [ s.magenta, s.magenta.bold, s.white.bold.on_magenta ].join ' '
puts [ s.cyan, s.cyan.bold, s.white.bold.on_cyan ].join ' '
puts [ s.white, s.white.bold, s.white.bold.on_white ].join ' '
end
def test_named_color_code_with_fg_bg
puts "Colorize me".fg(:green).bg(:red).bold.underline
end
def test_just_code
assert_equal "\e[0m", Ansi256.reset
assert_equal "\e[1m", Ansi256.bold
assert_equal "\e[4m", Ansi256.underline
assert_equal "\e[30m", Ansi256.black
assert_equal "\e[31m", Ansi256.red
assert_equal "\e[32m", Ansi256.green
assert_equal "\e[33m", Ansi256.yellow
assert_equal "\e[34m", Ansi256.blue
assert_equal "\e[35m", Ansi256.magenta
assert_equal "\e[36m", Ansi256.cyan
assert_equal "\e[37m", Ansi256.white
assert_equal "\e[40m", Ansi256.on_black
assert_equal "\e[41m", Ansi256.on_red
assert_equal "\e[42m", Ansi256.on_green
assert_equal "\e[43m", Ansi256.on_yellow
assert_equal "\e[44m", Ansi256.on_blue
assert_equal "\e[45m", Ansi256.on_magenta
assert_equal "\e[46m", Ansi256.on_cyan
assert_equal "\e[47m", Ansi256.on_white
assert_equal "\e[30m", Ansi256.fg(:black)
assert_equal "\e[31m", Ansi256.fg(:red)
assert_equal "\e[32m", Ansi256.fg(:green)
assert_equal "\e[33m", Ansi256.fg(:yellow)
assert_equal "\e[34m", Ansi256.fg(:blue)
assert_equal "\e[35m", Ansi256.fg(:magenta)
assert_equal "\e[36m", Ansi256.fg(:cyan)
assert_equal "\e[37m", Ansi256.fg(:white)
assert_equal "\e[40m", Ansi256.bg(:black)
assert_equal "\e[41m", Ansi256.bg(:red)
assert_equal "\e[42m", Ansi256.bg(:green)
assert_equal "\e[43m", Ansi256.bg(:yellow)
assert_equal "\e[44m", Ansi256.bg(:blue)
assert_equal "\e[45m", Ansi256.bg(:magenta)
assert_equal "\e[46m", Ansi256.bg(:cyan)
assert_equal "\e[47m", Ansi256.bg(:white)
end
def test_invalid_color_code
assert_raises(ArgumentError) { Ansi256.fg(:none) }
assert_raises(ArgumentError) { Ansi256.fg(:on_green) }
assert_raises(ArgumentError) { Ansi256.bg(:none) }
assert_raises(ArgumentError) { Ansi256.bg(:on_green) }
assert_raises(ArgumentError) { Ansi256.fg(-1) }
assert_raises(ArgumentError) { Ansi256.fg(300) }
assert_raises(ArgumentError) { Ansi256.bg(-1) }
assert_raises(ArgumentError) { Ansi256.bg(300) }
end
def test_fg_bg_underline
assert_equal "\e[38;5;100mHello\e[0m", 'Hello'.fg(100)
assert_equal "\e[48;5;100mHello\e[0m", 'Hello'.bg(100)
assert_equal "\e[31mHello\e[0m", 'Hello'.red
assert_equal "\e[41mHello\e[0m", 'Hello'.on_red
assert_equal "\e[38;5;100mHello\e[38;5;200m world\e[0m", "#{'Hello'.fg(100)} world".fg(200)
assert_equal "\e[38;5;200;4mWow \e[38;5;100mhello\e[38;5;200m world\e[0m",
"Wow #{'hello'.fg(100)} world".fg(200).underline
assert_equal "\e[38;5;200mWow \e[38;5;100;4mhello\e[0m\e[38;5;200m world\e[0m",
"Wow #{'hello'.fg(100).underline} world".fg(200)
assert_equal "\e[38;5;200mWow \e[38;5;100;48;5;50;4mhello\e[0m\e[38;5;200m world\e[0m",
"Wow #{'hello'.fg(100).underline.bg(50)} world".fg(200)
assert_equal "\e[38;5;200;48;5;250mWow \e[38;5;100;48;5;50;4mhello\e[0m\e[38;5;200;48;5;250m world\e[0m",
"Wow #{'hello'.fg(100).underline.bg(50)} world".fg(200).bg(250)
assert_equal "Wow hello world",
"Wow #{'hello'.fg(100).underline.bg(50)} world".fg(200).bg(250).plain
end
end
add a tets case for ansi code nesting
$VERBOSE = true
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'ansi256'
require 'minitest/autorun'
class TestAnsi256 < MiniTest::Unit::TestCase
def cfmt col
col.to_s.rjust(5).fg(232).bg(col)
end
# TODO: assertions :p
def test_256_color_table
puts (0..7).map { |col| cfmt col }.join
puts (8..15).map { |col| cfmt col }.join
(16..255).each_slice(6) do |slice|
puts slice.map { |col| cfmt col }.join
end
end
def test_nesting
a = ' '
(16..60).each do |i|
a = "<#{a}>".bg(i).fg(i * 2).underline
end
puts a
end
def test_nesting_hello_world
# Nesting
puts world = "World".bg(226).fg(232).underline
puts hello = "Hello #{world} !".fg(230).bg(75)
puts say_hello_world = "Say '#{hello}'".fg(30)
puts say_hello_world.plain.fg(27)
end
def test_nesting_hello_world2
puts world = "World".bg(226).blue.underline
puts hello = "Hello #{world} Hello".white.bold
puts say_hello_world = "Say '#{hello}'".fg(30).underline
puts say_hello_world.plain.fg(27)
end
def test_nesting_hello_world3
puts world = "World".blue.underline
puts hello = "Hello #{world} Hello".blue.bold
puts say_hello_world = "Say '#{hello}'".fg(30).underline
puts say_hello_world.plain.fg(27)
end
def test_named_colors
s = "Colorize me"
puts [ s.black, s.black.bold, s.white.bold.on_black ].join ' '
puts [ s.red, s.red.bold, s.white.bold.on_red ].join ' '
puts [ s.green, s.green.bold, s.white.bold.on_green ].join ' '
puts [ s.yellow, s.yellow.bold, s.white.bold.on_yellow ].join ' '
puts [ s.blue, s.blue.bold, s.white.bold.on_blue ].join ' '
puts [ s.magenta, s.magenta.bold, s.white.bold.on_magenta ].join ' '
puts [ s.cyan, s.cyan.bold, s.white.bold.on_cyan ].join ' '
puts [ s.white, s.white.bold, s.white.bold.on_white ].join ' '
end
def test_named_color_code_with_fg_bg
puts "Colorize me".fg(:green).bg(:red).bold.underline
end
def test_just_code
assert_equal "\e[0m", Ansi256.reset
assert_equal "\e[1m", Ansi256.bold
assert_equal "\e[4m", Ansi256.underline
assert_equal "\e[30m", Ansi256.black
assert_equal "\e[31m", Ansi256.red
assert_equal "\e[32m", Ansi256.green
assert_equal "\e[33m", Ansi256.yellow
assert_equal "\e[34m", Ansi256.blue
assert_equal "\e[35m", Ansi256.magenta
assert_equal "\e[36m", Ansi256.cyan
assert_equal "\e[37m", Ansi256.white
assert_equal "\e[40m", Ansi256.on_black
assert_equal "\e[41m", Ansi256.on_red
assert_equal "\e[42m", Ansi256.on_green
assert_equal "\e[43m", Ansi256.on_yellow
assert_equal "\e[44m", Ansi256.on_blue
assert_equal "\e[45m", Ansi256.on_magenta
assert_equal "\e[46m", Ansi256.on_cyan
assert_equal "\e[47m", Ansi256.on_white
assert_equal "\e[30m", Ansi256.fg(:black)
assert_equal "\e[31m", Ansi256.fg(:red)
assert_equal "\e[32m", Ansi256.fg(:green)
assert_equal "\e[33m", Ansi256.fg(:yellow)
assert_equal "\e[34m", Ansi256.fg(:blue)
assert_equal "\e[35m", Ansi256.fg(:magenta)
assert_equal "\e[36m", Ansi256.fg(:cyan)
assert_equal "\e[37m", Ansi256.fg(:white)
assert_equal "\e[40m", Ansi256.bg(:black)
assert_equal "\e[41m", Ansi256.bg(:red)
assert_equal "\e[42m", Ansi256.bg(:green)
assert_equal "\e[43m", Ansi256.bg(:yellow)
assert_equal "\e[44m", Ansi256.bg(:blue)
assert_equal "\e[45m", Ansi256.bg(:magenta)
assert_equal "\e[46m", Ansi256.bg(:cyan)
assert_equal "\e[47m", Ansi256.bg(:white)
end
def test_invalid_color_code
assert_raises(ArgumentError) { Ansi256.fg(:none) }
assert_raises(ArgumentError) { Ansi256.fg(:on_green) }
assert_raises(ArgumentError) { Ansi256.bg(:none) }
assert_raises(ArgumentError) { Ansi256.bg(:on_green) }
assert_raises(ArgumentError) { Ansi256.fg(-1) }
assert_raises(ArgumentError) { Ansi256.fg(300) }
assert_raises(ArgumentError) { Ansi256.bg(-1) }
assert_raises(ArgumentError) { Ansi256.bg(300) }
end
def test_fg_bg_underline
assert_equal "\e[38;5;100mHello\e[0m", 'Hello'.fg(100)
assert_equal "\e[48;5;100mHello\e[0m", 'Hello'.bg(100)
assert_equal "\e[31mHello\e[0m", 'Hello'.red
assert_equal "\e[41mHello\e[0m", 'Hello'.on_red
assert_equal "\e[38;5;100mHello\e[38;5;200m world\e[0m", "#{'Hello'.fg(100)} world".fg(200)
assert_equal "\e[38;5;200;4mWow \e[38;5;100mhello\e[38;5;200m world\e[0m",
"Wow #{'hello'.fg(100)} world".fg(200).underline
assert_equal "\e[38;5;200mWow \e[38;5;100;4mhello\e[0m\e[38;5;200m world\e[0m",
"Wow #{'hello'.fg(100).underline} world".fg(200)
assert_equal "\e[38;5;200mWow \e[38;5;100;48;5;50;4mhello\e[0m\e[38;5;200m world\e[0m",
"Wow #{'hello'.fg(100).underline.bg(50)} world".fg(200)
assert_equal "\e[38;5;200;48;5;250mWow \e[38;5;100;48;5;50;4mhello\e[0m\e[38;5;200;48;5;250m world\e[0m",
"Wow #{'hello'.fg(100).underline.bg(50)} world".fg(200).bg(250)
assert_equal "Wow hello world",
"Wow #{'hello'.fg(100).underline.bg(50)} world".fg(200).bg(250).plain
assert_equal "\e[32;48;5;200;1mWow \e[38;5;100;44;1;4mhello\e[0m\e[32;48;5;200;1m world\e[0m",
"Wow #{'hello'.fg(100).underline.on_blue} world".green.bold.bg(200)
end
end
|
module EmberScript
VERSION = "0.0.4"
end
version bump
module EmberScript
VERSION = "0.0.5"
end
|
require 'test/unit'
require 'test/setup'
$TESTING = true
require 'mogilefs/backend'
class MogileFS::Backend
attr_accessor :hosts
attr_reader :timeout, :dead
attr_writer :lasterr, :lasterrstr, :socket
end
class TestBackend < Test::Unit::TestCase
def setup
@backend = MogileFS::Backend.new :hosts => ['localhost:1']
end
def test_initialize
assert_raises ArgumentError do MogileFS::Backend.new end
assert_raises ArgumentError do MogileFS::Backend.new :hosts => [] end
assert_raises ArgumentError do MogileFS::Backend.new :hosts => [''] end
assert_equal ['localhost:1'], @backend.hosts
assert_equal 3, @backend.timeout
assert_equal nil, @backend.lasterr
assert_equal nil, @backend.lasterrstr
assert_equal({}, @backend.dead)
@backend = MogileFS::Backend.new :hosts => ['localhost:6001'], :timeout => 1
assert_equal 1, @backend.timeout
end
def test_do_request
received = ''
tmp = TempServer.new(Proc.new do |serv, port|
client, client_addr = serv.accept
client.sync = true
received = client.recv 4096
client.send "OK 1 you=win\r\n", 0
end)
@backend.hosts = "127.0.0.1:#{tmp.port}"
assert_equal({'you' => 'win'},
@backend.do_request('go!', { 'fight' => 'team fight!' }))
assert_equal "go! fight=team+fight%21\r\n", received
ensure
TempServer.destroy_all!
end
def test_do_request_send_error
socket_request = ''
socket = Object.new
def socket.closed?() false end
def socket.send(request, flags) raise SystemCallError, 'dummy' end
@backend.instance_variable_set '@socket', socket
assert_raises MogileFS::UnreachableBackendError do
@backend.do_request 'go!', { 'fight' => 'team fight!' }
end
assert_equal nil, @backend.instance_variable_get('@socket')
end
def test_automatic_exception
assert ! MogileFS::Backend.const_defined?('PebkacError')
assert @backend.error('pebkac')
assert_equal MogileFS::Error, @backend.error('PebkacError').superclass
assert MogileFS::Backend.const_defined?('PebkacError')
assert ! MogileFS::Backend.const_defined?('PebKacError')
assert @backend.error('peb_kac')
assert_equal MogileFS::Error, @backend.error('PebKacError').superclass
assert MogileFS::Backend.const_defined?('PebKacError')
end
def test_do_request_truncated
socket_request = ''
socket = Object.new
def socket.closed?() false end
def socket.send(request, flags) return request.length - 1 end
@backend.instance_variable_set '@socket', socket
assert_raises MogileFS::RequestTruncatedError do
@backend.do_request 'go!', { 'fight' => 'team fight!' }
end
end
def test_make_request
assert_equal "go! fight=team+fight%21\r\n",
@backend.make_request('go!', { 'fight' => 'team fight!' })
end
def test_parse_response
assert_equal({'foo' => 'bar', 'baz' => 'hoge'},
@backend.parse_response('OK 1 foo=bar&baz=hoge'))
err = nil
begin
@backend.parse_response('ERR you totally suck')
rescue MogileFS::Error => err
assert_equal 'MogileFS::Backend::YouError', err.class.to_s
end
assert_equal 'MogileFS::Backend::YouError', err.class.to_s
assert_equal 'you', @backend.lasterr
assert_equal 'totally suck', @backend.lasterrstr
assert_raises MogileFS::InvalidResponseError do
@backend.parse_response 'garbage'
end
end
def test_readable_eh_readable
accept_nr = 0
tmp = TempServer.new(Proc.new do |serv, port|
client, client_addr = serv.accept
client.sync = true
accept_nr += 1
client.send('.', 0)
sleep
end)
@backend = MogileFS::Backend.new :hosts => [ "127.0.0.1:#{tmp.port}" ]
assert_equal true, @backend.readable?
assert_equal 1, accept_nr
ensure
TempServer.destroy_all!
end
def test_readable_eh_not_readable
tmp = TempServer.new(Proc.new { |a,b| sleep })
@backend = MogileFS::Backend.new :hosts => [ "127.0.0.1:#{tmp.port}" ]
begin
@backend.readable?
rescue MogileFS::UnreadableSocketError => e
assert_equal "127.0.0.1:#{tmp.port} never became readable", e.message
rescue Exception => err
flunk "MogileFS::UnreadableSocketError not raised #{err} #{err.backtrace}"
else
flunk "MogileFS::UnreadableSocketError not raised"
ensure
TempServer.destroy_all!
end
end
def test_socket
assert_equal({}, @backend.dead)
assert_raises MogileFS::UnreachableBackendError do @backend.socket end
assert_equal(['localhost:1'], @backend.dead.keys)
end
def test_socket_robust
bad_accept_nr = accept_nr = 0
queue = Queue.new
bad = Proc.new { |serv,port| sleep; bad_accept_nr += 1 }
good = Proc.new do |serv,port|
client, client_addr = serv.accept
client.sync = true
accept_nr += 1
client.send '.', 0
client.flush
queue.push true
sleep
end
nr = 10
nr.times do
begin
t1 = TempServer.new(bad)
t2 = TempServer.new(good)
hosts = ["0:#{t1.port}", "0:#{t2.port}"]
@backend = MogileFS::Backend.new(:hosts => hosts)
assert_equal({}, @backend.dead)
t1.destroy!
@backend.socket
wait = queue.pop
ensure
TempServer.destroy_all!
end
end # nr.times
assert_equal 0, bad_accept_nr
assert_equal nr, accept_nr
end
def test_shutdown
accept_nr = 0
tmp = TempServer.new(Proc.new do |serv,port|
client, client_addr = serv.accept
accept_nr += 1
sleep
end)
@backend = MogileFS::Backend.new :hosts => [ "127.0.0.1:#{tmp.port}" ]
assert @backend.socket
assert ! @backend.socket.closed?
@backend.shutdown
assert_equal nil, @backend.instance_variable_get(:@socket)
assert_equal 1, accept_nr
ensure
TempServer.destroy_all!
end
def test_url_decode
assert_equal({"\272z" => "\360opy", "f\000" => "\272r"},
@backend.url_decode("%baz=%f0opy&f%00=%bar"))
end
def test_url_encode
params = [["f\000", "\272r"], ["\272z", "\360opy"]]
assert_equal "f%00=%bar&%baz=%f0opy", @backend.url_encode(params)
end
def test_url_escape # \n for unit_diff
actual = (0..255).map { |c| @backend.url_escape c.chr }.join "\n"
expected = []
expected.push(*(0..0x1f).map { |c| "%%%0.2x" % c })
expected << '+'
expected.push(*(0x21..0x2b).map { |c| "%%%0.2x" % c })
expected.push(*%w[, - . /])
expected.push(*('0'..'9'))
expected.push(*%w[: %3b %3c %3d %3e %3f %40])
expected.push(*('A'..'Z'))
expected.push(*%w[%5b \\ %5d %5e _ %60])
expected.push(*('a'..'z'))
expected.push(*(0x7b..0xff).map { |c| "%%%0.2x" % c })
expected = expected.join "\n"
assert_equal expected, actual
end
def test_url_unescape
input = []
input.push(*(0..0x1f).map { |c| "%%%0.2x" % c })
input << '+'
input.push(*(0x21..0x2b).map { |c| "%%%0.2x" % c })
input.push(*%w[, - . /])
input.push(*('0'..'9'))
input.push(*%w[: %3b %3c %3d %3e %3f %40])
input.push(*('A'..'Z'))
input.push(*%w[%5b \\ %5d %5e _ %60])
input.push(*('a'..'z'))
input.push(*(0x7b..0xff).map { |c| "%%%0.2x" % c })
actual = input.map { |c| @backend.url_unescape c }.join "\n"
expected = (0..255).map { |c| c.chr }.join "\n"
expected.sub! '+', ' '
assert_equal expected, actual
end
end
test_backend: shorten timeout test
Since the test server sleeps forever, there's no harm in having
a shorter timeout so our tests run faster (over twice as fast
with `make -j').
require 'test/unit'
require 'test/setup'
$TESTING = true
require 'mogilefs/backend'
class MogileFS::Backend
attr_accessor :hosts
attr_reader :timeout, :dead
attr_writer :lasterr, :lasterrstr, :socket
end
class TestBackend < Test::Unit::TestCase
def setup
@backend = MogileFS::Backend.new :hosts => ['localhost:1']
end
def test_initialize
assert_raises ArgumentError do MogileFS::Backend.new end
assert_raises ArgumentError do MogileFS::Backend.new :hosts => [] end
assert_raises ArgumentError do MogileFS::Backend.new :hosts => [''] end
assert_equal ['localhost:1'], @backend.hosts
assert_equal 3, @backend.timeout
assert_equal nil, @backend.lasterr
assert_equal nil, @backend.lasterrstr
assert_equal({}, @backend.dead)
@backend = MogileFS::Backend.new :hosts => ['localhost:6001'], :timeout => 1
assert_equal 1, @backend.timeout
end
def test_do_request
received = ''
tmp = TempServer.new(Proc.new do |serv, port|
client, client_addr = serv.accept
client.sync = true
received = client.recv 4096
client.send "OK 1 you=win\r\n", 0
end)
@backend.hosts = "127.0.0.1:#{tmp.port}"
assert_equal({'you' => 'win'},
@backend.do_request('go!', { 'fight' => 'team fight!' }))
assert_equal "go! fight=team+fight%21\r\n", received
ensure
TempServer.destroy_all!
end
def test_do_request_send_error
socket_request = ''
socket = Object.new
def socket.closed?() false end
def socket.send(request, flags) raise SystemCallError, 'dummy' end
@backend.instance_variable_set '@socket', socket
assert_raises MogileFS::UnreachableBackendError do
@backend.do_request 'go!', { 'fight' => 'team fight!' }
end
assert_equal nil, @backend.instance_variable_get('@socket')
end
def test_automatic_exception
assert ! MogileFS::Backend.const_defined?('PebkacError')
assert @backend.error('pebkac')
assert_equal MogileFS::Error, @backend.error('PebkacError').superclass
assert MogileFS::Backend.const_defined?('PebkacError')
assert ! MogileFS::Backend.const_defined?('PebKacError')
assert @backend.error('peb_kac')
assert_equal MogileFS::Error, @backend.error('PebKacError').superclass
assert MogileFS::Backend.const_defined?('PebKacError')
end
def test_do_request_truncated
socket_request = ''
socket = Object.new
def socket.closed?() false end
def socket.send(request, flags) return request.length - 1 end
@backend.instance_variable_set '@socket', socket
assert_raises MogileFS::RequestTruncatedError do
@backend.do_request 'go!', { 'fight' => 'team fight!' }
end
end
def test_make_request
assert_equal "go! fight=team+fight%21\r\n",
@backend.make_request('go!', { 'fight' => 'team fight!' })
end
def test_parse_response
assert_equal({'foo' => 'bar', 'baz' => 'hoge'},
@backend.parse_response('OK 1 foo=bar&baz=hoge'))
err = nil
begin
@backend.parse_response('ERR you totally suck')
rescue MogileFS::Error => err
assert_equal 'MogileFS::Backend::YouError', err.class.to_s
end
assert_equal 'MogileFS::Backend::YouError', err.class.to_s
assert_equal 'you', @backend.lasterr
assert_equal 'totally suck', @backend.lasterrstr
assert_raises MogileFS::InvalidResponseError do
@backend.parse_response 'garbage'
end
end
def test_readable_eh_readable
accept_nr = 0
tmp = TempServer.new(Proc.new do |serv, port|
client, client_addr = serv.accept
client.sync = true
accept_nr += 1
client.send('.', 0)
sleep
end)
@backend = MogileFS::Backend.new :hosts => [ "127.0.0.1:#{tmp.port}" ]
assert_equal true, @backend.readable?
assert_equal 1, accept_nr
ensure
TempServer.destroy_all!
end
def test_readable_eh_not_readable
tmp = TempServer.new(Proc.new { |a,b| sleep })
@backend = MogileFS::Backend.new(:hosts => [ "127.0.0.1:#{tmp.port}" ],
:timeout => 0.5)
begin
@backend.readable?
rescue MogileFS::UnreadableSocketError => e
assert_equal "127.0.0.1:#{tmp.port} never became readable", e.message
rescue Exception => err
flunk "MogileFS::UnreadableSocketError not raised #{err} #{err.backtrace}"
else
flunk "MogileFS::UnreadableSocketError not raised"
ensure
TempServer.destroy_all!
end
end
def test_socket
assert_equal({}, @backend.dead)
assert_raises MogileFS::UnreachableBackendError do @backend.socket end
assert_equal(['localhost:1'], @backend.dead.keys)
end
def test_socket_robust
bad_accept_nr = accept_nr = 0
queue = Queue.new
bad = Proc.new { |serv,port| sleep; bad_accept_nr += 1 }
good = Proc.new do |serv,port|
client, client_addr = serv.accept
client.sync = true
accept_nr += 1
client.send '.', 0
client.flush
queue.push true
sleep
end
nr = 10
nr.times do
begin
t1 = TempServer.new(bad)
t2 = TempServer.new(good)
hosts = ["0:#{t1.port}", "0:#{t2.port}"]
@backend = MogileFS::Backend.new(:hosts => hosts)
assert_equal({}, @backend.dead)
t1.destroy!
@backend.socket
wait = queue.pop
ensure
TempServer.destroy_all!
end
end # nr.times
assert_equal 0, bad_accept_nr
assert_equal nr, accept_nr
end
def test_shutdown
accept_nr = 0
tmp = TempServer.new(Proc.new do |serv,port|
client, client_addr = serv.accept
accept_nr += 1
sleep
end)
@backend = MogileFS::Backend.new :hosts => [ "127.0.0.1:#{tmp.port}" ]
assert @backend.socket
assert ! @backend.socket.closed?
@backend.shutdown
assert_equal nil, @backend.instance_variable_get(:@socket)
assert_equal 1, accept_nr
ensure
TempServer.destroy_all!
end
def test_url_decode
assert_equal({"\272z" => "\360opy", "f\000" => "\272r"},
@backend.url_decode("%baz=%f0opy&f%00=%bar"))
end
def test_url_encode
params = [["f\000", "\272r"], ["\272z", "\360opy"]]
assert_equal "f%00=%bar&%baz=%f0opy", @backend.url_encode(params)
end
def test_url_escape # \n for unit_diff
actual = (0..255).map { |c| @backend.url_escape c.chr }.join "\n"
expected = []
expected.push(*(0..0x1f).map { |c| "%%%0.2x" % c })
expected << '+'
expected.push(*(0x21..0x2b).map { |c| "%%%0.2x" % c })
expected.push(*%w[, - . /])
expected.push(*('0'..'9'))
expected.push(*%w[: %3b %3c %3d %3e %3f %40])
expected.push(*('A'..'Z'))
expected.push(*%w[%5b \\ %5d %5e _ %60])
expected.push(*('a'..'z'))
expected.push(*(0x7b..0xff).map { |c| "%%%0.2x" % c })
expected = expected.join "\n"
assert_equal expected, actual
end
def test_url_unescape
input = []
input.push(*(0..0x1f).map { |c| "%%%0.2x" % c })
input << '+'
input.push(*(0x21..0x2b).map { |c| "%%%0.2x" % c })
input.push(*%w[, - . /])
input.push(*('0'..'9'))
input.push(*%w[: %3b %3c %3d %3e %3f %40])
input.push(*('A'..'Z'))
input.push(*%w[%5b \\ %5d %5e _ %60])
input.push(*('a'..'z'))
input.push(*(0x7b..0xff).map { |c| "%%%0.2x" % c })
actual = input.map { |c| @backend.url_unescape c }.join "\n"
expected = (0..255).map { |c| c.chr }.join "\n"
expected.sub! '+', ' '
assert_equal expected, actual
end
end
|
require 'encrypted_strings'
require 'encrypted_attributes/sha_encryptor'
module PluginAWeek #:nodoc:
module EncryptedAttributes
def self.included(base) #:nodoc:
base.extend(MacroMethods)
end
module MacroMethods
# Encrypts the specified attribute.
#
# Configuration options:
# * +mode+ - The mode of encryption to use. Default is sha. See PluginAWeek::EncryptedStrings for other possible modes
# * +to+ - The attribute to write the encrypted value to. Default is the same attribute being encrypted.
# * +if+ - Specifies a method, proc or string to call to determine if the encryption should occur. The method, proc or string should return or evaluate to a true or false value.
# * +unless+ - Specifies a method, proc or string to call to determine if the encryption should not occur. The method, proc or string should return or evaluate to a true or false value.
#
# For additional configuration options used during the actual encryption,
# see the individual encryptor class for the specified mode.
#
# == Encryption timeline
#
# Attributes are encrypted immediately before a record is validated.
# This means that you can still validate the presence of the encrypted
# attribute, but other things like password length cannot be validated
# without either (a) decrypting the value first or (b) using a different
# encryption target. For example,
#
# class User < ActiveRecord::Base
# encrypts :password, :to => :crypted_password
#
# validates_presence_of :password, :crypted_password
# validates_length_of :password, :maximum => 16
# end
#
# In the above example, the actual encrypted password will be stored in
# the +crypted_password+ attribute. This means that validations can
# still run against the model for the original password value.
#
# user = User.new(:password => 'secret')
# user.password # => "secret"
# user.crypted_password # => nil
# user.valid? # => true
# user.crypted_password # => "8152bc582f58c854f580cb101d3182813dec4afe"
#
# user = User.new(:password => 'longer_than_the_maximum_allowed')
# user.valid? # => false
# user.crypted_password # => "e80a709f25798f87d9ca8005a7f64a645964d7c2"
# user.errors[:password] # => "is too long (maximum is 16 characters)"
#
# == Encryption mode examples
#
# SHA encryption:
# class User < ActiveRecord::Base
# encrypts :password
# # encrypts :password, :salt => :create_salt
# end
#
# Symmetric encryption:
# class User < ActiveRecord::Base
# encrypts :password, :mode => :symmetric
# # encrypts :password, :mode => :symmetric, :key => 'custom'
# end
#
# Asymmetric encryption:
# class User < ActiveRecord::Base
# encrypts :password, :mode => :asymmetric
# # encrypts :password, :mode => :asymmetric, :public_key_file => '/keys/public', :private_key_file => '/keys/private'
# end
def encrypts(attr_name, options = {})
attr_name = attr_name.to_s
to_attr_name = options.delete(:to) || attr_name
# Figure out what encryptor is being configured for the attribute
mode = options.delete(:mode) || :sha
class_name = "#{mode.to_s.classify}Encryptor"
if PluginAWeek::EncryptedAttributes.const_defined?(class_name)
encryptor_class = PluginAWeek::EncryptedAttributes.const_get(class_name)
else
encryptor_class = PluginAWeek::EncryptedStrings.const_get(class_name)
end
# Set the encrypted value right before validation takes place
before_validation(:if => options.delete(:if), :unless => options.delete(:unless)) do |record|
record.send(:write_encrypted_attribute, attr_name, to_attr_name, encryptor_class, options)
true
end
# Define the reader when reading the encrypted attribute from the database
define_method(to_attr_name) do
read_encrypted_attribute(to_attr_name, encryptor_class, options)
end
unless included_modules.include?(PluginAWeek::EncryptedAttributes::InstanceMethods)
include PluginAWeek::EncryptedAttributes::InstanceMethods
end
end
end
module InstanceMethods #:nodoc:
private
# Encrypts the given attribute to a target location using the encryption
# options configured for that attribute
def write_encrypted_attribute(attr_name, to_attr_name, encryptor_class, options)
value = send(attr_name)
# Only encrypt values that actually have content and have not already
# been encrypted
unless value.blank? || value.encrypted?
# Create the encryptor configured for this attribute
encryptor = create_encryptor(encryptor_class, options, :write, value)
# Encrypt the value
value = encryptor.encrypt(value)
value.encryptor = encryptor
# Update the value based on the target attribute
send("#{to_attr_name}=", value)
end
end
# Reads the given attribute from the database, adding contextual
# information about how it was encrypted so that equality comparisons
# can be used
def read_encrypted_attribute(to_attr_name, encryptor_class, options)
value = read_attribute(to_attr_name)
# Make sure we set the encryptor for equality comparison when reading
# from the database
unless value.blank? || value.encrypted? || attribute_changed?(to_attr_name)
# Create the encryptor configured for this attribute
value.encryptor = create_encryptor(encryptor_class, options, :read, value)
end
value
end
# Creates a new encryptor with the given configuration options. The
# operator defines the context in which the encryptor will be used.
def create_encryptor(klass, options, operator, value)
if klass.parent == PluginAWeek::EncryptedAttributes
# Only use the contextual information for encryptors defined in this plugin
klass.new(self, value, operator, options.dup)
else
klass.new(options.dup)
end
end
end
end
end
ActiveRecord::Base.class_eval do
include PluginAWeek::EncryptedAttributes
end
Add documentation on reading encrypted attributes
require 'encrypted_strings'
require 'encrypted_attributes/sha_encryptor'
module PluginAWeek #:nodoc:
module EncryptedAttributes
def self.included(base) #:nodoc:
base.extend(MacroMethods)
end
module MacroMethods
# Encrypts the specified attribute.
#
# Configuration options:
# * +mode+ - The mode of encryption to use. Default is sha. See PluginAWeek::EncryptedStrings for other possible modes
# * +to+ - The attribute to write the encrypted value to. Default is the same attribute being encrypted.
# * +if+ - Specifies a method, proc or string to call to determine if the encryption should occur. The method, proc or string should return or evaluate to a true or false value.
# * +unless+ - Specifies a method, proc or string to call to determine if the encryption should not occur. The method, proc or string should return or evaluate to a true or false value.
#
# For additional configuration options used during the actual encryption,
# see the individual encryptor class for the specified mode.
#
# == Encryption timeline
#
# Attributes are encrypted immediately before a record is validated.
# This means that you can still validate the presence of the encrypted
# attribute, but other things like password length cannot be validated
# without either (a) decrypting the value first or (b) using a different
# encryption target. For example,
#
# class User < ActiveRecord::Base
# encrypts :password, :to => :crypted_password
#
# validates_presence_of :password, :crypted_password
# validates_length_of :password, :maximum => 16
# end
#
# In the above example, the actual encrypted password will be stored in
# the +crypted_password+ attribute. This means that validations can
# still run against the model for the original password value.
#
# user = User.new(:password => 'secret')
# user.password # => "secret"
# user.crypted_password # => nil
# user.valid? # => true
# user.crypted_password # => "8152bc582f58c854f580cb101d3182813dec4afe"
#
# user = User.new(:password => 'longer_than_the_maximum_allowed')
# user.valid? # => false
# user.crypted_password # => "e80a709f25798f87d9ca8005a7f64a645964d7c2"
# user.errors[:password] # => "is too long (maximum is 16 characters)"
#
# == Encryption mode examples
#
# SHA encryption:
# class User < ActiveRecord::Base
# encrypts :password
# # encrypts :password, :salt => :create_salt
# end
#
# Symmetric encryption:
# class User < ActiveRecord::Base
# encrypts :password, :mode => :symmetric
# # encrypts :password, :mode => :symmetric, :key => 'custom'
# end
#
# Asymmetric encryption:
# class User < ActiveRecord::Base
# encrypts :password, :mode => :asymmetric
# # encrypts :password, :mode => :asymmetric, :public_key_file => '/keys/public', :private_key_file => '/keys/private'
# end
def encrypts(attr_name, options = {})
attr_name = attr_name.to_s
to_attr_name = options.delete(:to) || attr_name
# Figure out what encryptor is being configured for the attribute
mode = options.delete(:mode) || :sha
class_name = "#{mode.to_s.classify}Encryptor"
if PluginAWeek::EncryptedAttributes.const_defined?(class_name)
encryptor_class = PluginAWeek::EncryptedAttributes.const_get(class_name)
else
encryptor_class = PluginAWeek::EncryptedStrings.const_get(class_name)
end
# Set the encrypted value right before validation takes place
before_validation(:if => options.delete(:if), :unless => options.delete(:unless)) do |record|
record.send(:write_encrypted_attribute, attr_name, to_attr_name, encryptor_class, options)
true
end
# Define the reader when reading the encrypted attribute from the database
define_method(to_attr_name) do
read_encrypted_attribute(to_attr_name, encryptor_class, options)
end
unless included_modules.include?(PluginAWeek::EncryptedAttributes::InstanceMethods)
include PluginAWeek::EncryptedAttributes::InstanceMethods
end
end
end
module InstanceMethods #:nodoc:
private
# Encrypts the given attribute to a target location using the encryption
# options configured for that attribute
def write_encrypted_attribute(attr_name, to_attr_name, encryptor_class, options)
value = send(attr_name)
# Only encrypt values that actually have content and have not already
# been encrypted
unless value.blank? || value.encrypted?
# Create the encryptor configured for this attribute
encryptor = create_encryptor(encryptor_class, options, :write, value)
# Encrypt the value
value = encryptor.encrypt(value)
value.encryptor = encryptor
# Update the value based on the target attribute
send("#{to_attr_name}=", value)
end
end
# Reads the given attribute from the database, adding contextual
# information about how it was encrypted so that equality comparisons
# can be used
def read_encrypted_attribute(to_attr_name, encryptor_class, options)
value = read_attribute(to_attr_name)
# Make sure we set the encryptor for equality comparison when reading
# from the database. This should only be done if the value is *not*
# blank, is *not* encrypted, and hasn't changed since it was read from
# the database. The dirty checking is important when the encypted value
# is written to the same attribute as the unencrypted value (i.e. you
# don't want to encrypt when a new value has been set)
unless value.blank? || value.encrypted? || attribute_changed?(to_attr_name)
# Create the encryptor configured for this attribute
value.encryptor = create_encryptor(encryptor_class, options, :read, value)
end
value
end
# Creates a new encryptor with the given configuration options. The
# operator defines the context in which the encryptor will be used.
def create_encryptor(klass, options, operator, value)
if klass.parent == PluginAWeek::EncryptedAttributes
# Only use the contextual information for encryptors defined in this plugin
klass.new(self, value, operator, options.dup)
else
klass.new(options.dup)
end
end
end
end
end
ActiveRecord::Base.class_eval do
include PluginAWeek::EncryptedAttributes
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.